hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
⌀
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
98cbe3be87c882618afaf3d500e1590959e55837
dcavar/dcavar.github.io
pycl/Code/freq4.py
[ "Apache-2.0" ]
Python
countWords
<not_specific>
def countWords(words, filename): """Counts words in file and returns dictionary.""" count = words.get("__count__", 0) try: file = codecs.open(filename, "r", "utf8") tokens = [ string.strip(string.lower(i)) for i in file.read().split() ] for i in tokens: words[i] = words.get(i, 0) + 1 count += 1 file.cl...
Counts words in file and returns dictionary.
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
def countWords(words, filename): count = words.get("__count__", 0) try: file = codecs.open(filename, "r", "utf8") tokens = [ string.strip(string.lower(i)) for i in file.read().split() ] for i in tokens: words[i] = words.get(i, 0) + 1 count += 1 file.close() except IOError: print "Cannot read from fil...
[ "def", "countWords", "(", "words", ",", "filename", ")", ":", "count", "=", "words", ".", "get", "(", "\"__count__\"", ",", "0", ")", "try", ":", "file", "=", "codecs", ".", "open", "(", "filename", ",", "\"r\"", ",", "\"utf8\"", ")", "tokens", "=", ...
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
[ "\"\"\"Counts words in file and returns dictionary.\"\"\"" ]
[ { "param": "words", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "words", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_token...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
clean
<not_specific>
def clean(self, line): """Cleans the parentheses from the parsed evaluation file. """ line = string.replace(line, "(", " ") line = string.replace(line, ")", " ") while string.count(line, " ") != 0: line = string.replace(line, " ", " ") return line
Cleans the parentheses from the parsed evaluation file.
Cleans the parentheses from the parsed evaluation file.
[ "Cleans", "the", "parentheses", "from", "the", "parsed", "evaluation", "file", "." ]
def clean(self, line): line = string.replace(line, "(", " ") line = string.replace(line, ")", " ") while string.count(line, " ") != 0: line = string.replace(line, " ", " ") return line
[ "def", "clean", "(", "self", ",", "line", ")", ":", "line", "=", "string", ".", "replace", "(", "line", ",", "\"(\"", ",", "\" \"", ")", "line", "=", "string", ".", "replace", "(", "line", ",", "\")\"", ",", "\" \"", ")", "while", "string", ".", ...
Cleans the parentheses from the parsed evaluation file.
[ "Cleans", "the", "parentheses", "from", "the", "parsed", "evaluation", "file", "." ]
[ "\"\"\"Cleans the parentheses from the parsed evaluation file. \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "line", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "line", "type": null, "docstring": null, "docstring_tokens": [...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
scoreParse
<not_specific>
def scoreParse(self, parse, correct): """Compares the algorithms parse and the correct parse and assigns a score for that parse. The score is based upon how far apart the right and left parentheses are from each other in the two parses and also includes a penalty for parentheses in one parse but not the o...
Compares the algorithms parse and the correct parse and assigns a score for that parse. The score is based upon how far apart the right and left parentheses are from each other in the two parses and also includes a penalty for parentheses in one parse but not the other.
Compares the algorithms parse and the correct parse and assigns a score for that parse. The score is based upon how far apart the right and left parentheses are from each other in the two parses and also includes a penalty for parentheses in one parse but not the other.
[ "Compares", "the", "algorithms", "parse", "and", "the", "correct", "parse", "and", "assigns", "a", "score", "for", "that", "parse", ".", "The", "score", "is", "based", "upon", "how", "far", "apart", "the", "right", "and", "left", "parentheses", "are", "fro...
def scoreParse(self, parse, correct): score = 0 compCnt = string.count(parse, "(") realCnt = string.count(correct, "(") compPos = -1 realPos = -1 for i in range(compCnt): compPos = string.find(parse, "(", compPos+1, len(parse)) realPos = string.find(correct, "(", realPos+1, len(correct)) score += a...
[ "def", "scoreParse", "(", "self", ",", "parse", ",", "correct", ")", ":", "score", "=", "0", "compCnt", "=", "string", ".", "count", "(", "parse", ",", "\"(\"", ")", "realCnt", "=", "string", ".", "count", "(", "correct", ",", "\"(\"", ")", "compPos"...
Compares the algorithms parse and the correct parse and assigns a score for that parse.
[ "Compares", "the", "algorithms", "parse", "and", "the", "correct", "parse", "and", "assigns", "a", "score", "for", "that", "parse", "." ]
[ "\"\"\"Compares the algorithms parse and the correct parse and assigns a score for that parse.\n\t\t\t The score is based upon how far apart the right and left parentheses are from each other\n\t\t\t in the two parses and also includes a penalty for parentheses in one parse but not the\n\t\t\t other.\n\t\t\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "parse", "type": null }, { "param": "correct", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parse", "type": null, "docstring": null, "docstring_tokens": ...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
makeMinList
<not_specific>
def makeMinList(self, list, curr, final): """Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go. """ if len(list) <= 2: return list if curr == final: return list pos = self.fi...
Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go.
Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go.
[ "Recursively", "creates", "the", "structure", "of", "the", "sentence", "my", "marking", "halves", "and", "recurring", "on", "the", "halves", ".", "Curr", "is", "the", "current", "depth", "of", "the", "recursion", "and", "final", "is", "the", "maximum", "dept...
def makeMinList(self, list, curr, final): if len(list) <= 2: return list if curr == final: return list pos = self.findMinima(list) if pos == -1: return list else: return [ self.makeMinList(list[:pos], curr+1, final), self.makeMinList(list[pos + 1:], curr+1, final) ]
[ "def", "makeMinList", "(", "self", ",", "list", ",", "curr", ",", "final", ")", ":", "if", "len", "(", "list", ")", "<=", "2", ":", "return", "list", "if", "curr", "==", "final", ":", "return", "list", "pos", "=", "self", ".", "findMinima", "(", ...
Recursively creates the structure of the sentence my marking halves and recurring on the halves.
[ "Recursively", "creates", "the", "structure", "of", "the", "sentence", "my", "marking", "halves", "and", "recurring", "on", "the", "halves", "." ]
[ "\"\"\"Recursively creates the structure of the sentence my marking halves and recurring on the halves.\n\t\t\tCurr is the current depth of the recursion and final is the maximum depth to go.\n\t\t\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "list", "type": null }, { "param": "curr", "type": null }, { "param": "final", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "list", "type": null, "docstring": null, "docstring_tokens": [...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
makeMaxList
<not_specific>
def makeMaxList(self, list, curr, final): """Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go. """ if len(list) <= 2: return list if curr == final: return list pos = self.fi...
Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go.
Recursively creates the structure of the sentence my marking halves and recurring on the halves. Curr is the current depth of the recursion and final is the maximum depth to go.
[ "Recursively", "creates", "the", "structure", "of", "the", "sentence", "my", "marking", "halves", "and", "recurring", "on", "the", "halves", ".", "Curr", "is", "the", "current", "depth", "of", "the", "recursion", "and", "final", "is", "the", "maximum", "dept...
def makeMaxList(self, list, curr, final): if len(list) <= 2: return list if curr == final: return list pos = self.findMaxima(list) if pos == -1: return list else: return [ self.makeMaxList(list[:pos], curr+1, final), self.makeMaxList(list[pos + 1:], curr+1, final) ]
[ "def", "makeMaxList", "(", "self", ",", "list", ",", "curr", ",", "final", ")", ":", "if", "len", "(", "list", ")", "<=", "2", ":", "return", "list", "if", "curr", "==", "final", ":", "return", "list", "pos", "=", "self", ".", "findMaxima", "(", ...
Recursively creates the structure of the sentence my marking halves and recurring on the halves.
[ "Recursively", "creates", "the", "structure", "of", "the", "sentence", "my", "marking", "halves", "and", "recurring", "on", "the", "halves", "." ]
[ "\"\"\"Recursively creates the structure of the sentence my marking halves and recurring on the halves.\n\t\t\tCurr is the current depth of the recursion and final is the maximum depth to go.\n\t\t\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "list", "type": null }, { "param": "curr", "type": null }, { "param": "final", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "list", "type": null, "docstring": null, "docstring_tokens": [...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
trim
<not_specific>
def trim(self, words): """Removes the tags and floats from an utterance. """ result = [] for x in words: if isinstance(x, list): result.append(self.trim(x)) elif not isinstance(x, float): brownsplit=compiled.match(x); word=[brownsplit.group(1), brownsplit.group(2)]; result.append(word[0]) ...
Removes the tags and floats from an utterance.
Removes the tags and floats from an utterance.
[ "Removes", "the", "tags", "and", "floats", "from", "an", "utterance", "." ]
def trim(self, words): result = [] for x in words: if isinstance(x, list): result.append(self.trim(x)) elif not isinstance(x, float): brownsplit=compiled.match(x); word=[brownsplit.group(1), brownsplit.group(2)]; result.append(word[0]) return result
[ "def", "trim", "(", "self", ",", "words", ")", ":", "result", "=", "[", "]", "for", "x", "in", "words", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "result", ".", "append", "(", "self", ".", "trim", "(", "x", ")", ")", "elif", "...
Removes the tags and floats from an utterance.
[ "Removes", "the", "tags", "and", "floats", "from", "an", "utterance", "." ]
[ "\"\"\"Removes the tags and floats from an utterance.\n\t\t\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "words", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "words", "type": null, "docstring": null, "docstring_tokens": ...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
scm
<not_specific>
def scm(self, parse): """Takes a parse of an utterance in list from and converts into a parenthesized string. That is similar to the scheme code format used by the Penn Treebank parses. """ str = "(" for x in parse: if isinstance(x, list): str += self.scm(x) else: str += x str += ")" retur...
Takes a parse of an utterance in list from and converts into a parenthesized string. That is similar to the scheme code format used by the Penn Treebank parses.
Takes a parse of an utterance in list from and converts into a parenthesized string. That is similar to the scheme code format used by the Penn Treebank parses.
[ "Takes", "a", "parse", "of", "an", "utterance", "in", "list", "from", "and", "converts", "into", "a", "parenthesized", "string", ".", "That", "is", "similar", "to", "the", "scheme", "code", "format", "used", "by", "the", "Penn", "Treebank", "parses", "." ]
def scm(self, parse): str = "(" for x in parse: if isinstance(x, list): str += self.scm(x) else: str += x str += ")" return str
[ "def", "scm", "(", "self", ",", "parse", ")", ":", "str", "=", "\"(\"", "for", "x", "in", "parse", ":", "if", "isinstance", "(", "x", ",", "list", ")", ":", "str", "+=", "self", ".", "scm", "(", "x", ")", "else", ":", "str", "+=", "x", "str",...
Takes a parse of an utterance in list from and converts into a parenthesized string.
[ "Takes", "a", "parse", "of", "an", "utterance", "in", "list", "from", "and", "converts", "into", "a", "parenthesized", "string", "." ]
[ "\"\"\"Takes a parse of an utterance in list from and converts into a parenthesized string.\n\t\t\t That is similar to the scheme code format used by the Penn Treebank parses.\n\t\t\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "parse", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "parse", "type": null, "docstring": null, "docstring_tokens": ...
3f9f35b8816014636f304b23ced03ced3eb93b89
dcavar/dcavar.github.io
IntroCModelingLA/Code/MIParser.py
[ "Apache-2.0" ]
Python
MI
<not_specific>
def MI(self, bigram, ltype, rtype): """Calculate the mutual information for bigram. MI = log2 ( P(XY) / P(X) P(Y) ).""" if ltype == TOKEN and rtype == TOKEN: bigrams = self.totoBigrams unileft = self.tokens uniright = self.tokens elif ltype == TOKEN and rtype == TYPE: bigrams = self.totyBigrams ...
Calculate the mutual information for bigram. MI = log2 ( P(XY) / P(X) P(Y) ).
Calculate the mutual information for bigram.
[ "Calculate", "the", "mutual", "information", "for", "bigram", "." ]
def MI(self, bigram, ltype, rtype): if ltype == TOKEN and rtype == TOKEN: bigrams = self.totoBigrams unileft = self.tokens uniright = self.tokens elif ltype == TOKEN and rtype == TYPE: bigrams = self.totyBigrams unileft = self.tokens uniright = self.types elif ltype == TYPE and rtype == TOKEN:...
[ "def", "MI", "(", "self", ",", "bigram", ",", "ltype", ",", "rtype", ")", ":", "if", "ltype", "==", "TOKEN", "and", "rtype", "==", "TOKEN", ":", "bigrams", "=", "self", ".", "totoBigrams", "unileft", "=", "self", ".", "tokens", "uniright", "=", "self...
Calculate the mutual information for bigram.
[ "Calculate", "the", "mutual", "information", "for", "bigram", "." ]
[ "\"\"\"Calculate the mutual information for bigram.\n\t\t\tMI = log2 ( P(XY) / P(X) P(Y) ).\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "bigram", "type": null }, { "param": "ltype", "type": null }, { "param": "rtype", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bigram", "type": null, "docstring": null, "docstring_tokens":...
b8ccdd615282802cf35804ab63878c287ee295e7
dcavar/dcavar.github.io
IntroCModelingLA/Code/frequencyNFW.py
[ "Apache-2.0" ]
Python
countWords
<not_specific>
def countWords(words, filename): """Counts words in file and returns dictionary.""" try: file = open(filename, "r") for x in file.readlines(): for i in string.split(x): i = string.strip(string.lower(i)) if len(i) == 0: continue while i[-1] in string.punctuation: i = i[:-1] if len(i) ...
Counts words in file and returns dictionary.
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
def countWords(words, filename): try: file = open(filename, "r") for x in file.readlines(): for i in string.split(x): i = string.strip(string.lower(i)) if len(i) == 0: continue while i[-1] in string.punctuation: i = i[:-1] if len(i) == 0: break if len(i) == 0: continue ...
[ "def", "countWords", "(", "words", ",", "filename", ")", ":", "try", ":", "file", "=", "open", "(", "filename", ",", "\"r\"", ")", "for", "x", "in", "file", ".", "readlines", "(", ")", ":", "for", "i", "in", "string", ".", "split", "(", "x", ")",...
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
[ "\"\"\"Counts words in file and returns dictionary.\"\"\"", "# increment the count of this word", "# append the word and its length" ]
[ { "param": "words", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "words", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_token...
5fb5537617e92d89e4073419778cee1290f9ca83
dcavar/dcavar.github.io
IntroCModelingLA/Code/MI.py
[ "Apache-2.0" ]
Python
MI
<not_specific>
def MI(bigram, bigramprob, tokens, tokencount): """Returns the mutual information for bigrams. MI = P(XY|X) log2 ( P(XY) / P(X) P(Y) ) P(XY|X) = num of bigrams XY over num bigrams with X left """ tokenlist = string.split(bigram) if tokens.has_key(tokenlist[0]): px = float(tokens[tokenlist[0]])/float(tokencou...
Returns the mutual information for bigrams. MI = P(XY|X) log2 ( P(XY) / P(X) P(Y) ) P(XY|X) = num of bigrams XY over num bigrams with X left
Returns the mutual information for bigrams.
[ "Returns", "the", "mutual", "information", "for", "bigrams", "." ]
def MI(bigram, bigramprob, tokens, tokencount): tokenlist = string.split(bigram) if tokens.has_key(tokenlist[0]): px = float(tokens[tokenlist[0]])/float(tokencount) else: px = 0.0 if tokens.has_key(tokenlist[1]): py = float(tokens[tokenlist[1]])/float(tokencount) else: py = 0.0 if py == 0.0 or px == 0.0: ...
[ "def", "MI", "(", "bigram", ",", "bigramprob", ",", "tokens", ",", "tokencount", ")", ":", "tokenlist", "=", "string", ".", "split", "(", "bigram", ")", "if", "tokens", ".", "has_key", "(", "tokenlist", "[", "0", "]", ")", ":", "px", "=", "float", ...
Returns the mutual information for bigrams.
[ "Returns", "the", "mutual", "information", "for", "bigrams", "." ]
[ "\"\"\"Returns the mutual information for bigrams.\n\t\tMI = P(XY|X) log2 ( P(XY) / P(X) P(Y) )\n\t\tP(XY|X) = num of bigrams XY over num bigrams with X left\n\t\"\"\"" ]
[ { "param": "bigram", "type": null }, { "param": "bigramprob", "type": null }, { "param": "tokens", "type": null }, { "param": "tokencount", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "bigram", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bigramprob", "type": null, "docstring": null, "docstring_to...
8a29043b353c8b888bb5803bba86cf5a6f6c9c92
dcavar/dcavar.github.io
pycl/Code/TDAParser.py
[ "Apache-2.0" ]
Python
tdparse
null
def tdparse(input, goal, grammar, agenda): """Recursive top-down parse function with weak generative capacity.""" #print "Got : %s\tinput: %s\nwith agenda:\n%s" % (goal, input, agenda) print "Got : %s\tinput: %s" % (goal, input) if goal == input == []: print "Success" elif goal == [] or input == []: if agenda...
Recursive top-down parse function with weak generative capacity.
Recursive top-down parse function with weak generative capacity.
[ "Recursive", "top", "-", "down", "parse", "function", "with", "weak", "generative", "capacity", "." ]
def tdparse(input, goal, grammar, agenda): print "Got : %s\tinput: %s" % (goal, input) if goal == input == []: print "Success" elif goal == [] or input == []: if agenda == []: print "Fail: Agenda empty!" else: entry = agenda.pop(strategy) print "Backing up to: %s with %s" % (entry[0], entry[1]) tdpars...
[ "def", "tdparse", "(", "input", ",", "goal", ",", "grammar", ",", "agenda", ")", ":", "print", "\"Got : %s\\tinput: %s\"", "%", "(", "goal", ",", "input", ")", "if", "goal", "==", "input", "==", "[", "]", ":", "print", "\"Success\"", "elif", "goal", "=...
Recursive top-down parse function with weak generative capacity.
[ "Recursive", "top", "-", "down", "parse", "function", "with", "weak", "generative", "capacity", "." ]
[ "\"\"\"Recursive top-down parse function with weak generative capacity.\"\"\"", "#print \"Got : %s\\tinput: %s\\nwith agenda:\\n%s\" % (goal, input, agenda)", "# there is something in goal and input", "# if initial symbols match, reduce lists, parse" ]
[ { "param": "input", "type": null }, { "param": "goal", "type": null }, { "param": "grammar", "type": null }, { "param": "agenda", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "goal", "type": null, "docstring": null, "docstring_tokens": ...
8a3d9ea61f8fa6059f32fe280a4222324ef7235a
dcavar/dcavar.github.io
pycl/Code/Charty/Charty.py
[ "Apache-2.0" ]
Python
match
<not_specific>
def match(aedge, iedge): """Returns 1 if the active edge and the inactive edge match, otherwise 0.""" if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return 1 return 0
Returns 1 if the active edge and the inactive edge match, otherwise 0.
Returns 1 if the active edge and the inactive edge match, otherwise 0.
[ "Returns", "1", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "0", "." ]
def match(aedge, iedge): if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return 1 return 0
[ "def", "match", "(", "aedge", ",", "iedge", ")", ":", "if", "aedge", "[", "1", "]", "==", "iedge", "[", "0", "]", ":", "if", "aedge", "[", "4", "]", "[", "aedge", "[", "2", "]", "]", "==", "iedge", "[", "3", "]", ":", "return", "1", "return...
Returns 1 if the active edge and the inactive edge match, otherwise 0.
[ "Returns", "1", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "0", "." ]
[ "\"\"\"Returns 1 if the active edge and the inactive edge match,\n\t otherwise 0.\"\"\"" ]
[ { "param": "aedge", "type": null }, { "param": "iedge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "aedge", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "iedge", "type": null, "docstring": null, "docstring_tokens":...
8a3d9ea61f8fa6059f32fe280a4222324ef7235a
dcavar/dcavar.github.io
pycl/Code/Charty/Charty.py
[ "Apache-2.0" ]
Python
structToStr
<not_specific>
def structToStr(edges): """Returns a string representation of the parse with labled brackets.""" tmpstr = "" for i in edges: if chart[i][5]: tmpstr = tmpstr + "[" + chart[i][3] + " " + structToStr(chart[i][5]) + " ] " else: tmpstr = tmpstr + "[" + chart[i][3] + " " for x in chart[i][4]: tmpstr =...
Returns a string representation of the parse with labled brackets.
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
def structToStr(edges): tmpstr = "" for i in edges: if chart[i][5]: tmpstr = tmpstr + "[" + chart[i][3] + " " + structToStr(chart[i][5]) + " ] " else: tmpstr = tmpstr + "[" + chart[i][3] + " " for x in chart[i][4]: tmpstr = " ".join([tmpstr, x]) tmpstr = tmpstr + " ] " return tmpstr
[ "def", "structToStr", "(", "edges", ")", ":", "tmpstr", "=", "\"\"", "for", "i", "in", "edges", ":", "if", "chart", "[", "i", "]", "[", "5", "]", ":", "tmpstr", "=", "tmpstr", "+", "\"[\"", "+", "chart", "[", "i", "]", "[", "3", "]", "+", "\"...
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
[ "\"\"\"Returns a string representation of the parse with\n\t labled brackets.\"\"\"" ]
[ { "param": "edges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "edges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8a3d9ea61f8fa6059f32fe280a4222324ef7235a
dcavar/dcavar.github.io
pycl/Code/Charty/Charty.py
[ "Apache-2.0" ]
Python
ruleInvocation
<not_specific>
def ruleInvocation(lststart): """Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.""" global chart change = 0 for i in range(lststart, len(chart)): if chart[i][2] >= len(chart[i][4...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
def ruleInvocation(lststart): global chart change = 0 for i in range(lststart, len(chart)): if chart[i][2] >= len(chart[i][4]): (start, end, index, lhs, rhs, consumed) = chart[i] if grammar.rhshash.has_key(lhs): for k in grammar.rhshash[lhs]: if len(grammar.rhs[k]) > inputlength - start: cont...
[ "def", "ruleInvocation", "(", "lststart", ")", ":", "global", "chart", "change", "=", "0", "for", "i", "in", "range", "(", "lststart", ",", "len", "(", "chart", ")", ")", ":", "if", "chart", "[", "i", "]", "[", "2", "]", ">=", "len", "(", "chart"...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
[ "\"\"\"Add all the rules of the grammar to the chart that\n\t are relavant:\n\t\tFind the rule with the LHS of edge as the leftmost RHS\n\t\tsymbol and maximally the remaining length of the input.\"\"\"", "# only inactive edge" ]
[ { "param": "lststart", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lststart", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8a3d9ea61f8fa6059f32fe280a4222324ef7235a
dcavar/dcavar.github.io
pycl/Code/Charty/Charty.py
[ "Apache-2.0" ]
Python
fundamentalRule
<not_specific>
def fundamentalRule(): """The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.""" global chart change = 0 for aedge in chart: if isActive(aedge): for k in range(len(chart)): if isInactive(chart[k]): if match(aedge, chart[k]): newedge = aed...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", "." ]
def fundamentalRule(): global chart change = 0 for aedge in chart: if isActive(aedge): for k in range(len(chart)): if isInactive(chart[k]): if match(aedge, chart[k]): newedge = aedge[:] newedge[5] = aedge[5][:] newedge[5].append(k) newedge[1] = chart[k][1] newedge[2] = new...
[ "def", "fundamentalRule", "(", ")", ":", "global", "chart", "change", "=", "0", "for", "aedge", "in", "chart", ":", "if", "isActive", "(", "aedge", ")", ":", "for", "k", "in", "range", "(", "len", "(", "chart", ")", ")", ":", "if", "isInactive", "(...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", "." ]
[ "\"\"\"The fundamental rule of chart parsing generates new edges by\n\t combining fitting active and inactive edges.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8a3d9ea61f8fa6059f32fe280a4222324ef7235a
dcavar/dcavar.github.io
pycl/Code/Charty/Charty.py
[ "Apache-2.0" ]
Python
parse
null
def parse(input): """Parse a list of tokens. """ global chart, inputlength chart = [] inputlength = len(input) chartpos = 0 # remember start-position in chart for i in range(len(input)): # initialize with input token chart.append([ i, i + 1, 1, grammar.getTag(input[i]), [ input[i] ], [] ]) if DEBUG: p...
Parse a list of tokens.
Parse a list of tokens.
[ "Parse", "a", "list", "of", "tokens", "." ]
def parse(input): global chart, inputlength chart = [] inputlength = len(input) chartpos = 0 for i in range(len(input)): chart.append([ i, i + 1, 1, grammar.getTag(input[i]), [ input[i] ], [] ]) if DEBUG: print "Adding edge:", chart[len(chart) - 1] change = 1 while change: change = 0 chartlen = ...
[ "def", "parse", "(", "input", ")", ":", "global", "chart", ",", "inputlength", "chart", "=", "[", "]", "inputlength", "=", "len", "(", "input", ")", "chartpos", "=", "0", "for", "i", "in", "range", "(", "len", "(", "input", ")", ")", ":", "chart", ...
Parse a list of tokens.
[ "Parse", "a", "list", "of", "tokens", "." ]
[ "\"\"\"Parse a list of tokens.\n\t\"\"\"", "# remember start-position in chart", "# initialize with input token", "# set pointer to new edge in chart" ]
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
freqProfile
<not_specific>
def freqProfile(tokenlist, model=None): """Generates a frequency profile from a token list. Parameter: tokenlist: an iterable sequence of tokens. Optional parameter: model: a dictionary data structure, i.e. a frequency profile default = None """ if m...
Generates a frequency profile from a token list. Parameter: tokenlist: an iterable sequence of tokens. Optional parameter: model: a dictionary data structure, i.e. a frequency profile default = None
Generates a frequency profile from a token list. Parameter. an iterable sequence of tokens. Optional parameter. a dictionary data structure, i.e. a frequency profile default = None
[ "Generates", "a", "frequency", "profile", "from", "a", "token", "list", ".", "Parameter", ".", "an", "iterable", "sequence", "of", "tokens", ".", "Optional", "parameter", ".", "a", "dictionary", "data", "structure", "i", ".", "e", ".", "a", "frequency", "p...
def freqProfile(tokenlist, model=None): if model: return mergeFreqProfiles(model, dict(Counter(tokenlist))) else: return dict(Counter(tokenlist))
[ "def", "freqProfile", "(", "tokenlist", ",", "model", "=", "None", ")", ":", "if", "model", ":", "return", "mergeFreqProfiles", "(", "model", ",", "dict", "(", "Counter", "(", "tokenlist", ")", ")", ")", "else", ":", "return", "dict", "(", "Counter", "...
Generates a frequency profile from a token list.
[ "Generates", "a", "frequency", "profile", "from", "a", "token", "list", "." ]
[ "\"\"\"Generates a frequency profile from a token list.\n \n Parameter:\n \n tokenlist: an iterable sequence of tokens.\n \n Optional parameter:\n \n model: a dictionary data structure, i.e. a frequency profile\n default = None\n \"\"\"" ]
[ { "param": "tokenlist", "type": null }, { "param": "model", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tokenlist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": null, "docstring": null, "docstring_toke...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
textKWIC
<not_specific>
def textKWIC(text, token, contextchars=15, wordboundary=True): """Returns a list of left and right context tuples for token. The context is default of length 15, the context obeys word boundaries in the default. !!! TODO !!! """ pos = text.find(token) res = [] while pos > -1: left...
Returns a list of left and right context tuples for token. The context is default of length 15, the context obeys word boundaries in the default. !!! TODO !!!
Returns a list of left and right context tuples for token. The context is default of length 15, the context obeys word boundaries in the default. TODO
[ "Returns", "a", "list", "of", "left", "and", "right", "context", "tuples", "for", "token", ".", "The", "context", "is", "default", "of", "length", "15", "the", "context", "obeys", "word", "boundaries", "in", "the", "default", ".", "TODO" ]
def textKWIC(text, token, contextchars=15, wordboundary=True): pos = text.find(token) res = [] while pos > -1: left = text[max(0,pos-contextchars):pos].strip() right = text[pos+len(token):max(contextchars,len(text)+pos+len(token))].strip() res.append( (left, right) ) if pos + 1 < len(te...
[ "def", "textKWIC", "(", "text", ",", "token", ",", "contextchars", "=", "15", ",", "wordboundary", "=", "True", ")", ":", "pos", "=", "text", ".", "find", "(", "token", ")", "res", "=", "[", "]", "while", "pos", ">", "-", "1", ":", "left", "=", ...
Returns a list of left and right context tuples for token.
[ "Returns", "a", "list", "of", "left", "and", "right", "context", "tuples", "for", "token", "." ]
[ "\"\"\"Returns a list of left and right context tuples for token.\n The context is default of length 15,\n the context obeys word boundaries in the default.\n !!! TODO !!!\n \"\"\"" ]
[ { "param": "text", "type": null }, { "param": "token", "type": null }, { "param": "contextchars", "type": null }, { "param": "wordboundary", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "token", "type": null, "docstring": null, "docstring_tokens": ...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
mergeFreqProfiles
<not_specific>
def mergeFreqProfiles(freqp1, freqp2): """Returns a frequency profile from two merged frequency profiles. The two frequency profiles must be dictionary types. Parameters: freqp1: dictionary, i.e. frequency profile freqp2: dictionary, i.e. frequency profile Th...
Returns a frequency profile from two merged frequency profiles. The two frequency profiles must be dictionary types. Parameters: freqp1: dictionary, i.e. frequency profile freqp2: dictionary, i.e. frequency profile This function only works with absolute frequenc...
Returns a frequency profile from two merged frequency profiles. The two frequency profiles must be dictionary types. This function only works with absolute frequency profiles.
[ "Returns", "a", "frequency", "profile", "from", "two", "merged", "frequency", "profiles", ".", "The", "two", "frequency", "profiles", "must", "be", "dictionary", "types", ".", "This", "function", "only", "works", "with", "absolute", "frequency", "profiles", "." ...
def mergeFreqProfiles(freqp1, freqp2): return dict(((i, freqp1.get(i, 0) + freqp2.get(i, 0)) for i in set.union(set(freqp1), set(freqp2))))
[ "def", "mergeFreqProfiles", "(", "freqp1", ",", "freqp2", ")", ":", "return", "dict", "(", "(", "(", "i", ",", "freqp1", ".", "get", "(", "i", ",", "0", ")", "+", "freqp2", ".", "get", "(", "i", ",", "0", ")", ")", "for", "i", "in", "set", "....
Returns a frequency profile from two merged frequency profiles.
[ "Returns", "a", "frequency", "profile", "from", "two", "merged", "frequency", "profiles", "." ]
[ "\"\"\"Returns a frequency profile from two merged frequency profiles.\n The two frequency profiles must be dictionary types.\n \n Parameters:\n \n freqp1: dictionary, i.e. frequency profile\n \n freqp2: dictionary, i.e. frequency profile\n \n This function only works wi...
[ { "param": "freqp1", "type": null }, { "param": "freqp2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "freqp1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "freqp2", "type": null, "docstring": null, "docstring_tokens...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
relFreqProfile
<not_specific>
def relFreqProfile(freqprof): """Generates a relative frequency profile from an absolute frequency profile.""" tokenCount = sum(freqprof.values()) if tokenCount > 0: return dict(((i[0], i[1]/tokenCount) for i in freqprof.items()))
Generates a relative frequency profile from an absolute frequency profile.
Generates a relative frequency profile from an absolute frequency profile.
[ "Generates", "a", "relative", "frequency", "profile", "from", "an", "absolute", "frequency", "profile", "." ]
def relFreqProfile(freqprof): tokenCount = sum(freqprof.values()) if tokenCount > 0: return dict(((i[0], i[1]/tokenCount) for i in freqprof.items()))
[ "def", "relFreqProfile", "(", "freqprof", ")", ":", "tokenCount", "=", "sum", "(", "freqprof", ".", "values", "(", ")", ")", "if", "tokenCount", ">", "0", ":", "return", "dict", "(", "(", "(", "i", "[", "0", "]", ",", "i", "[", "1", "]", "/", "...
Generates a relative frequency profile from an absolute frequency profile.
[ "Generates", "a", "relative", "frequency", "profile", "from", "an", "absolute", "frequency", "profile", "." ]
[ "\"\"\"Generates a relative frequency profile from an absolute frequency\n profile.\"\"\"" ]
[ { "param": "freqprof", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "freqprof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
ngramList
<not_specific>
def ngramList(tokenlist, n): """Returns a N-gram list from a tokenlist. The returned list is just a list of N-grams, not a frequency profile.""" if len(tokenlist) >= n: return tuple((tuple(tokenlist[i:i+n]) for i in range(len(tokenlist) - (n - 1)))) return ()
Returns a N-gram list from a tokenlist. The returned list is just a list of N-grams, not a frequency profile.
Returns a N-gram list from a tokenlist. The returned list is just a list of N-grams, not a frequency profile.
[ "Returns", "a", "N", "-", "gram", "list", "from", "a", "tokenlist", ".", "The", "returned", "list", "is", "just", "a", "list", "of", "N", "-", "grams", "not", "a", "frequency", "profile", "." ]
def ngramList(tokenlist, n): if len(tokenlist) >= n: return tuple((tuple(tokenlist[i:i+n]) for i in range(len(tokenlist) - (n - 1)))) return ()
[ "def", "ngramList", "(", "tokenlist", ",", "n", ")", ":", "if", "len", "(", "tokenlist", ")", ">=", "n", ":", "return", "tuple", "(", "(", "tuple", "(", "tokenlist", "[", "i", ":", "i", "+", "n", "]", ")", "for", "i", "in", "range", "(", "len",...
Returns a N-gram list from a tokenlist.
[ "Returns", "a", "N", "-", "gram", "list", "from", "a", "tokenlist", "." ]
[ "\"\"\"Returns a N-gram list from a tokenlist.\n The returned list is just a list of N-grams, not a frequency profile.\"\"\"" ]
[ { "param": "tokenlist", "type": null }, { "param": "n", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tokenlist", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n", "type": null, "docstring": null, "docstring_tokens":...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
dotProduct
<not_specific>
def dotProduct(vector1, vector2): """Returns the dot product of two vectors.""" if len(vector1) == len(vector2): return sum((vector1[i] * vector2[i] for i in range(len(vector1)))) return None
Returns the dot product of two vectors.
Returns the dot product of two vectors.
[ "Returns", "the", "dot", "product", "of", "two", "vectors", "." ]
def dotProduct(vector1, vector2): if len(vector1) == len(vector2): return sum((vector1[i] * vector2[i] for i in range(len(vector1)))) return None
[ "def", "dotProduct", "(", "vector1", ",", "vector2", ")", ":", "if", "len", "(", "vector1", ")", "==", "len", "(", "vector2", ")", ":", "return", "sum", "(", "(", "vector1", "[", "i", "]", "*", "vector2", "[", "i", "]", "for", "i", "in", "range",...
Returns the dot product of two vectors.
[ "Returns", "the", "dot", "product", "of", "two", "vectors", "." ]
[ "\"\"\"Returns the dot product of two vectors.\"\"\"" ]
[ { "param": "vector1", "type": null }, { "param": "vector2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "vector1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "vector2", "type": null, "docstring": null, "docstring_toke...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
cosineSimilarity
<not_specific>
def cosineSimilarity(vector1, vector2): """Returns the cosine similarity of two vectors.""" if len(vector1) == len(vector2): magnitude = sqrt(sum((i**2 for i in vector1))) * sqrt(sum((i**2 for i in vector2))) if magnitude > 0: return dotProduct(vector1, vector2) / magnitude return None
Returns the cosine similarity of two vectors.
Returns the cosine similarity of two vectors.
[ "Returns", "the", "cosine", "similarity", "of", "two", "vectors", "." ]
def cosineSimilarity(vector1, vector2): if len(vector1) == len(vector2): magnitude = sqrt(sum((i**2 for i in vector1))) * sqrt(sum((i**2 for i in vector2))) if magnitude > 0: return dotProduct(vector1, vector2) / magnitude return None
[ "def", "cosineSimilarity", "(", "vector1", ",", "vector2", ")", ":", "if", "len", "(", "vector1", ")", "==", "len", "(", "vector2", ")", ":", "magnitude", "=", "sqrt", "(", "sum", "(", "(", "i", "**", "2", "for", "i", "in", "vector1", ")", ")", "...
Returns the cosine similarity of two vectors.
[ "Returns", "the", "cosine", "similarity", "of", "two", "vectors", "." ]
[ "\"\"\"Returns the cosine similarity of two vectors.\"\"\"" ]
[ { "param": "vector1", "type": null }, { "param": "vector2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "vector1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "vector2", "type": null, "docstring": null, "docstring_toke...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
euclideanDistance
<not_specific>
def euclideanDistance(vector1, vector2): """Returns the Euclidean distance of two vectors.""" if len(vector1) == len(vector2): return sqrt(sum((vector1[i] - vector2[i])**2 for i in range(len(vector1)))) return None
Returns the Euclidean distance of two vectors.
Returns the Euclidean distance of two vectors.
[ "Returns", "the", "Euclidean", "distance", "of", "two", "vectors", "." ]
def euclideanDistance(vector1, vector2): if len(vector1) == len(vector2): return sqrt(sum((vector1[i] - vector2[i])**2 for i in range(len(vector1)))) return None
[ "def", "euclideanDistance", "(", "vector1", ",", "vector2", ")", ":", "if", "len", "(", "vector1", ")", "==", "len", "(", "vector2", ")", ":", "return", "sqrt", "(", "sum", "(", "(", "vector1", "[", "i", "]", "-", "vector2", "[", "i", "]", ")", "...
Returns the Euclidean distance of two vectors.
[ "Returns", "the", "Euclidean", "distance", "of", "two", "vectors", "." ]
[ "\"\"\"Returns the Euclidean distance of two vectors.\"\"\"" ]
[ { "param": "vector1", "type": null }, { "param": "vector2", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "vector1", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "vector2", "type": null, "docstring": null, "docstring_toke...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
termInDocsProfile
<not_specific>
def termInDocsProfile(docsprofiles): """Returns a profile with terms and number of documents in which the term occurs as a key value pair in a dicitionary data structure. Parameter: docsprofiles: list with a. frequency profiles for documents (dictionary data structure), or ...
Returns a profile with terms and number of documents in which the term occurs as a key value pair in a dicitionary data structure. Parameter: docsprofiles: list with a. frequency profiles for documents (dictionary data structure), or b. lists or tuples with document tokens ...
Returns a profile with terms and number of documents in which the term occurs as a key value pair in a dicitionary data structure. list with a. frequency profiles for documents (dictionary data structure), or b. lists or tuples with document tokens c. set of document tokens
[ "Returns", "a", "profile", "with", "terms", "and", "number", "of", "documents", "in", "which", "the", "term", "occurs", "as", "a", "key", "value", "pair", "in", "a", "dicitionary", "data", "structure", ".", "list", "with", "a", ".", "frequency", "profiles"...
def termInDocsProfile(docsprofiles): mycount = Counter() for doc in docsprofiles: if type(doc) == type(dict): mycount.update(doc.items()) elif type(doc) == type([]) or type(doc) == type(tuple()): mycount.update(set(doc)) elif type(doc) == type(set()): mycount.update(do...
[ "def", "termInDocsProfile", "(", "docsprofiles", ")", ":", "mycount", "=", "Counter", "(", ")", "for", "doc", "in", "docsprofiles", ":", "if", "type", "(", "doc", ")", "==", "type", "(", "dict", ")", ":", "mycount", ".", "update", "(", "doc", ".", "i...
Returns a profile with terms and number of documents in which the term occurs as a key value pair in a dicitionary data structure.
[ "Returns", "a", "profile", "with", "terms", "and", "number", "of", "documents", "in", "which", "the", "term", "occurs", "as", "a", "key", "value", "pair", "in", "a", "dicitionary", "data", "structure", "." ]
[ "\"\"\"Returns a profile with terms and number of documents in which the term\n occurs as a key value pair in a dicitionary data structure.\n \n Parameter:\n \n docsprofiles: list with\n a. frequency profiles for documents (dictionary data structure), or\n b. lists or tuples with ...
[ { "param": "docsprofiles", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "docsprofiles", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
tfidfProfile
<not_specific>
def tfidfProfile(docfprof, numdocs, termsindocprofile): """Returns a document profile after applying tf-idf reranking to it. Parameters: docfprof: document frequency profile with absolute frequencies termsindocprofile: a dictionary data structure with term and count of documents it occurs in ...
Returns a document profile after applying tf-idf reranking to it. Parameters: docfprof: document frequency profile with absolute frequencies termsindocprofile: a dictionary data structure with term and count of documents it occurs in pairs.
Returns a document profile after applying tf-idf reranking to it. Parameters. document frequency profile with absolute frequencies a dictionary data structure with term and count of documents it occurs in pairs.
[ "Returns", "a", "document", "profile", "after", "applying", "tf", "-", "idf", "reranking", "to", "it", ".", "Parameters", ".", "document", "frequency", "profile", "with", "absolute", "frequencies", "a", "dictionary", "data", "structure", "with", "term", "and", ...
def tfidfProfile(docfprof, numdocs, termsindocprofile): total = sum(docfprof.values()) if total > 0: return dict((tuple(i, tfidfScore(docfprof[i]/total, numdocs, termsindocprofile[i])) for i in docfprof)) return None
[ "def", "tfidfProfile", "(", "docfprof", ",", "numdocs", ",", "termsindocprofile", ")", ":", "total", "=", "sum", "(", "docfprof", ".", "values", "(", ")", ")", "if", "total", ">", "0", ":", "return", "dict", "(", "(", "tuple", "(", "i", ",", "tfidfSc...
Returns a document profile after applying tf-idf reranking to it.
[ "Returns", "a", "document", "profile", "after", "applying", "tf", "-", "idf", "reranking", "to", "it", "." ]
[ "\"\"\"Returns a document profile after applying tf-idf reranking to it.\n \n Parameters:\n \n docfprof: document frequency profile with absolute frequencies\n \n termsindocprofile: a dictionary data structure with term and count of\n documents it occurs in pairs.\n \"\"\"" ]
[ { "param": "docfprof", "type": null }, { "param": "numdocs", "type": null }, { "param": "termsindocprofile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "docfprof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "numdocs", "type": null, "docstring": null, "docstring_tok...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
tfidfScore
<not_specific>
def tfidfScore(tf, numdocs, numtermincorp): """Returns the tf-idf-score for a term. Parameters: tf: text frequency of the term, i.e. the relative frequency of a term in a document, or number of times a term occurs in a document divided by the number of terms in the document. ...
Returns the tf-idf-score for a term. Parameters: tf: text frequency of the term, i.e. the relative frequency of a term in a document, or number of times a term occurs in a document divided by the number of terms in the document. numdoc: the total number of documents in...
Returns the tf-idf-score for a term. Parameters. text frequency of the term, i.e. the relative frequency of a term in a document, or number of times a term occurs in a document divided by the number of terms in the document. the total number of documents in the corpus, i.e. number of documents in all classes. number...
[ "Returns", "the", "tf", "-", "idf", "-", "score", "for", "a", "term", ".", "Parameters", ".", "text", "frequency", "of", "the", "term", "i", ".", "e", ".", "the", "relative", "frequency", "of", "a", "term", "in", "a", "document", "or", "number", "of"...
def tfidfScore(tf, numdocs, numtermincorp): return tf * log(numdocs / (1 + numtermincorp))
[ "def", "tfidfScore", "(", "tf", ",", "numdocs", ",", "numtermincorp", ")", ":", "return", "tf", "*", "log", "(", "numdocs", "/", "(", "1", "+", "numtermincorp", ")", ")" ]
Returns the tf-idf-score for a term.
[ "Returns", "the", "tf", "-", "idf", "-", "score", "for", "a", "term", "." ]
[ "\"\"\"Returns the tf-idf-score for a term.\n \n Parameters:\n \n tf: text frequency of the term, i.e. the relative frequency of a term in\n a document, or number of times a term occurs in a document divided by\n the number of terms in the document.\n \n numdoc: the total num...
[ { "param": "tf", "type": null }, { "param": "numdocs", "type": null }, { "param": "numtermincorp", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tf", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "numdocs", "type": null, "docstring": null, "docstring_tokens": ...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
naiveBayesianScore
<not_specific>
def naiveBayesianScore(model, tokenlist, pdoc): """Returns the Naive Bayesian score given a model and a tokenlist. The score is the sum of logs of the document probability and the individual token probabilities in the tokenlist, taken from model. Parameters: model: dictionary with tok...
Returns the Naive Bayesian score given a model and a tokenlist. The score is the sum of logs of the document probability and the individual token probabilities in the tokenlist, taken from model. Parameters: model: dictionary with token - relative frequency pairs tokenlist: iterab...
Returns the Naive Bayesian score given a model and a tokenlist. The score is the sum of logs of the document probability and the individual token probabilities in the tokenlist, taken from model. dictionary with token - relative frequency pairs iterable list or tuple of tokens float with the probability to get a d...
[ "Returns", "the", "Naive", "Bayesian", "score", "given", "a", "model", "and", "a", "tokenlist", ".", "The", "score", "is", "the", "sum", "of", "logs", "of", "the", "document", "probability", "and", "the", "individual", "token", "probabilities", "in", "the", ...
def naiveBayesianScore(model, tokenlist, pdoc): return log(pdoc) + sum((log(model.get(i, NAIVEBAYESIANCOUNTOFF)) for i in tokenlist))
[ "def", "naiveBayesianScore", "(", "model", ",", "tokenlist", ",", "pdoc", ")", ":", "return", "log", "(", "pdoc", ")", "+", "sum", "(", "(", "log", "(", "model", ".", "get", "(", "i", ",", "NAIVEBAYESIANCOUNTOFF", ")", ")", "for", "i", "in", "tokenli...
Returns the Naive Bayesian score given a model and a tokenlist.
[ "Returns", "the", "Naive", "Bayesian", "score", "given", "a", "model", "and", "a", "tokenlist", "." ]
[ "\"\"\"Returns the Naive Bayesian score given a model and a tokenlist.\n The score is the sum of logs of the document probability and\n the individual token probabilities in the tokenlist, taken from model.\n \n Parameters:\n\n model: dictionary with token - relative frequency pairs\n\n ...
[ { "param": "model", "type": null }, { "param": "tokenlist", "type": null }, { "param": "pdoc", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "model", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "tokenlist", "type": null, "docstring": null, "docstring_toke...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
chi2Score
<not_specific>
def chi2Score(observation, expectation): """Returns the Chi2-score for an observation and expectation value list.""" if len(observation) == len(expectation): return sum((observation[i] - max(expectation[i], CI2EXPECTATIONCOUNTOFF))**2 / max(expectation[i], CI2EXPECTATIONCOUNTOFF) for i in range(len(observat...
Returns the Chi2-score for an observation and expectation value list.
Returns the Chi2-score for an observation and expectation value list.
[ "Returns", "the", "Chi2", "-", "score", "for", "an", "observation", "and", "expectation", "value", "list", "." ]
def chi2Score(observation, expectation): if len(observation) == len(expectation): return sum((observation[i] - max(expectation[i], CI2EXPECTATIONCOUNTOFF))**2 / max(expectation[i], CI2EXPECTATIONCOUNTOFF) for i in range(len(observation))) return None
[ "def", "chi2Score", "(", "observation", ",", "expectation", ")", ":", "if", "len", "(", "observation", ")", "==", "len", "(", "expectation", ")", ":", "return", "sum", "(", "(", "observation", "[", "i", "]", "-", "max", "(", "expectation", "[", "i", ...
Returns the Chi2-score for an observation and expectation value list.
[ "Returns", "the", "Chi2", "-", "score", "for", "an", "observation", "and", "expectation", "value", "list", "." ]
[ "\"\"\"Returns the Chi2-score for an observation and expectation value list.\"\"\"" ]
[ { "param": "observation", "type": null }, { "param": "expectation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "observation", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "expectation", "type": null, "docstring": null, "docstr...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
highestNTermsChi2
<not_specific>
def highestNTermsChi2(docfprof, corpfprof, n=10): """Returns a list of the first n tokens with the highest Chi2 score. """ doctotal = sum(docfprof.values()) corptotal = sum(corpfprof.values()) res = [ (j[0], chi2Score(j[1:],expectationFromObservationDF1(j[1:]))) for j in ((i, docfprof.get(i, 0), corp...
Returns a list of the first n tokens with the highest Chi2 score.
Returns a list of the first n tokens with the highest Chi2 score.
[ "Returns", "a", "list", "of", "the", "first", "n", "tokens", "with", "the", "highest", "Chi2", "score", "." ]
def highestNTermsChi2(docfprof, corpfprof, n=10): doctotal = sum(docfprof.values()) corptotal = sum(corpfprof.values()) res = [ (j[0], chi2Score(j[1:],expectationFromObservationDF1(j[1:]))) for j in ((i, docfprof.get(i, 0), corpfprof.get(i, 0) - docfprof.get(i, 0), doctotal - docfprof.get(i, 0), corptotal - (...
[ "def", "highestNTermsChi2", "(", "docfprof", ",", "corpfprof", ",", "n", "=", "10", ")", ":", "doctotal", "=", "sum", "(", "docfprof", ".", "values", "(", ")", ")", "corptotal", "=", "sum", "(", "corpfprof", ".", "values", "(", ")", ")", "res", "=", ...
Returns a list of the first n tokens with the highest Chi2 score.
[ "Returns", "a", "list", "of", "the", "first", "n", "tokens", "with", "the", "highest", "Chi2", "score", "." ]
[ "\"\"\"Returns a list of the first n tokens with the highest Chi2 score.\n \"\"\"" ]
[ { "param": "docfprof", "type": null }, { "param": "corpfprof", "type": null }, { "param": "n", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "docfprof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "corpfprof", "type": null, "docstring": null, "docstring_t...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
significantTermsChi2
<not_specific>
def significantTermsChi2(docfprof, corpfprof): """Returns a list of significant terms from a document, given the documents frequency profile and the corpus frequency profile. The significance test is based on Chi2. Parameters: docfprof: absolute frequency profile for one ...
Returns a list of significant terms from a document, given the documents frequency profile and the corpus frequency profile. The significance test is based on Chi2. Parameters: docfprof: absolute frequency profile for one document. corpfprof: absolute freqeuncy ...
Returns a list of significant terms from a document, given the documents frequency profile and the corpus frequency profile. The significance test is based on Chi2. absolute frequency profile for one document. absolute freqeuncy profile for the complete corpus. It is presupposed that all terms in docfprof are als...
[ "Returns", "a", "list", "of", "significant", "terms", "from", "a", "document", "given", "the", "documents", "frequency", "profile", "and", "the", "corpus", "frequency", "profile", ".", "The", "significance", "test", "is", "based", "on", "Chi2", ".", "absolute"...
def significantTermsChi2(docfprof, corpfprof): doctotal = sum(docfprof.values()) corptotal = sum(corpfprof.values()) return (k[0] for k in ((j[0], chi2Score(j[1:],expectationFromObservationDF1(j[1:]))) for j in ((i, docfprof.get(i, 0), corpfprof.get(i, 0) - docfprof.get(i, 0), doctotal - docfprof.get(i, 0), c...
[ "def", "significantTermsChi2", "(", "docfprof", ",", "corpfprof", ")", ":", "doctotal", "=", "sum", "(", "docfprof", ".", "values", "(", ")", ")", "corptotal", "=", "sum", "(", "corpfprof", ".", "values", "(", ")", ")", "return", "(", "k", "[", "0", ...
Returns a list of significant terms from a document, given the documents frequency profile and the corpus frequency profile.
[ "Returns", "a", "list", "of", "significant", "terms", "from", "a", "document", "given", "the", "documents", "frequency", "profile", "and", "the", "corpus", "frequency", "profile", "." ]
[ "\"\"\"Returns a list of significant terms from a document, given the documents\n frequency profile and the corpus frequency profile.\n \n The significance test is based on Chi2.\n \n Parameters:\n \n docfprof: absolute frequency profile for one document.\n \n corpfprof:...
[ { "param": "docfprof", "type": null }, { "param": "corpfprof", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "docfprof", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "corpfprof", "type": null, "docstring": null, "docstring_t...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
chi2Significant
<not_specific>
def chi2Significant(tuple, unigrams, bigrams): """Returns true, if token1 and token2 are significantly coocurring, false otherwise. The used test is the Chi2-test. Parameters: tuple: tuple of tokens unigrams: unigrams dictionary data structure bigrams: bigrams dictionary...
Returns true, if token1 and token2 are significantly coocurring, false otherwise. The used test is the Chi2-test. Parameters: tuple: tuple of tokens unigrams: unigrams dictionary data structure bigrams: bigrams dictionary data structure
Returns true, if token1 and token2 are significantly coocurring, false otherwise. The used test is the Chi2-test. tuple of tokens unigrams dictionary data structure bigrams dictionary data structure
[ "Returns", "true", "if", "token1", "and", "token2", "are", "significantly", "coocurring", "false", "otherwise", ".", "The", "used", "test", "is", "the", "Chi2", "-", "test", ".", "tuple", "of", "tokens", "unigrams", "dictionary", "data", "structure", "bigrams"...
def chi2Significant(tuple, unigrams, bigrams): yes_yes = bigrams.get(tuple, 0) yes_not = unigrams.get(tuple[0], 0) - yes_yes not_yes = unigrams.get(tuple[1], 0) - bigrams.get(tuple, 0) not_not = sum(bigrams.values()) - 1 - yes_not - not_yes + yes_yes chi2score = chi2Score((yes_yes, yes_not, not_yes, not_...
[ "def", "chi2Significant", "(", "tuple", ",", "unigrams", ",", "bigrams", ")", ":", "yes_yes", "=", "bigrams", ".", "get", "(", "tuple", ",", "0", ")", "yes_not", "=", "unigrams", ".", "get", "(", "tuple", "[", "0", "]", ",", "0", ")", "-", "yes_yes...
Returns true, if token1 and token2 are significantly coocurring, false otherwise.
[ "Returns", "true", "if", "token1", "and", "token2", "are", "significantly", "coocurring", "false", "otherwise", "." ]
[ "\"\"\"Returns true, if token1 and token2 are significantly coocurring,\n false otherwise. The used test is the Chi2-test.\n \n Parameters:\n \n tuple: tuple of tokens\n\n unigrams: unigrams dictionary data structure\n\n bigrams: bigrams dictionary data structure\n \"\"\"" ]
[ { "param": "tuple", "type": null }, { "param": "unigrams", "type": null }, { "param": "bigrams", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tuple", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "unigrams", "type": null, "docstring": null, "docstring_token...
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
expectationFromObservationDF1
<not_specific>
def expectationFromObservationDF1(observation): """Returns the expectation values for observation values, assuming a table of two columns and two rows represented in a value list observations. That is, the first two values are assumed to be row 1, the second two values are assumed to be row 2. ...
Returns the expectation values for observation values, assuming a table of two columns and two rows represented in a value list observations. That is, the first two values are assumed to be row 1, the second two values are assumed to be row 2. A table like: ------------------------...
Returns the expectation values for observation values, assuming a table of two columns and two rows represented in a value list observations. That is, the first two values are assumed to be row 1, the second two values are assumed to be row 2. A table like.
[ "Returns", "the", "expectation", "values", "for", "observation", "values", "assuming", "a", "table", "of", "two", "columns", "and", "two", "rows", "represented", "in", "a", "value", "list", "observations", ".", "That", "is", "the", "first", "two", "values", ...
def expectationFromObservationDF1(observation): if len(observation) == 4: rowtotal1 = sum(observation[:2]) rowtotal2 = sum(observation[2:]) columntotal1 = sum(observation[::2]) columntotal2 = sum(observation[1::2]) total = sum(observation) return ( (rowtotal1 * columntotal1) / tot...
[ "def", "expectationFromObservationDF1", "(", "observation", ")", ":", "if", "len", "(", "observation", ")", "==", "4", ":", "rowtotal1", "=", "sum", "(", "observation", "[", ":", "2", "]", ")", "rowtotal2", "=", "sum", "(", "observation", "[", "2", ":", ...
Returns the expectation values for observation values, assuming a table of two columns and two rows represented in a value list observations.
[ "Returns", "the", "expectation", "values", "for", "observation", "values", "assuming", "a", "table", "of", "two", "columns", "and", "two", "rows", "represented", "in", "a", "value", "list", "observations", "." ]
[ "\"\"\"Returns the expectation values for observation values, assuming a table\n of two columns and two rows represented in a value list observations.\n That is, the first two values are assumed to be row 1, the second two\n values are assumed to be row 2.\n \n A table like:\n -------...
[ { "param": "observation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "observation", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
05e926930885e1918404ee12213a62a10f38fcd9
dcavar/dcavar.github.io
textstat/resources/TextStat.py
[ "Apache-2.0" ]
Python
pointwiseMI
<not_specific>
def pointwiseMI(ngram, ngrammodel, unigrammodel): """Return the Mutual Information score for an N-gram based on the N-gram frquency profile and the individual frequencies. """ return ngrammodel.get(ngram, 0.000000001) * log(ngrammodel.get(ngram, 0.000000001) / reduce(mul, (unigrammodel.get(i, 0.000000001...
Return the Mutual Information score for an N-gram based on the N-gram frquency profile and the individual frequencies.
Return the Mutual Information score for an N-gram based on the N-gram frquency profile and the individual frequencies.
[ "Return", "the", "Mutual", "Information", "score", "for", "an", "N", "-", "gram", "based", "on", "the", "N", "-", "gram", "frquency", "profile", "and", "the", "individual", "frequencies", "." ]
def pointwiseMI(ngram, ngrammodel, unigrammodel): return ngrammodel.get(ngram, 0.000000001) * log(ngrammodel.get(ngram, 0.000000001) / reduce(mul, (unigrammodel.get(i, 0.000000001) for i in ngram )), 2)
[ "def", "pointwiseMI", "(", "ngram", ",", "ngrammodel", ",", "unigrammodel", ")", ":", "return", "ngrammodel", ".", "get", "(", "ngram", ",", "0.000000001", ")", "*", "log", "(", "ngrammodel", ".", "get", "(", "ngram", ",", "0.000000001", ")", "/", "reduc...
Return the Mutual Information score for an N-gram based on the N-gram frquency profile and the individual frequencies.
[ "Return", "the", "Mutual", "Information", "score", "for", "an", "N", "-", "gram", "based", "on", "the", "N", "-", "gram", "frquency", "profile", "and", "the", "individual", "frequencies", "." ]
[ "\"\"\"Return the Mutual Information score for an N-gram based on the N-gram\n frquency profile and the individual frequencies.\n \"\"\"" ]
[ { "param": "ngram", "type": null }, { "param": "ngrammodel", "type": null }, { "param": "unigrammodel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ngram", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ngrammodel", "type": null, "docstring": null, "docstring_tok...
624993cd0c378b2f3714a6d303fb5093c9fe51f6
dcavar/dcavar.github.io
IntroCModelingLA/Code/frequency.py
[ "Apache-2.0" ]
Python
countWords
<not_specific>
def countWords(words, filename): """Counts words in file and returns dictionary.""" try: file = open(filename, "r") for x in file.readlines(): for i in string.split(x): i = string.strip(i) if words.has_key(i): # increment the count of this word words[i][0] += 1 else: # append the wor...
Counts words in file and returns dictionary.
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
def countWords(words, filename): try: file = open(filename, "r") for x in file.readlines(): for i in string.split(x): i = string.strip(i) if words.has_key(i): words[i][0] += 1 else: words[i] = [ 1, len(i) ] except IOError: print "Cannot read from file:", filename file.close() else: ...
[ "def", "countWords", "(", "words", ",", "filename", ")", ":", "try", ":", "file", "=", "open", "(", "filename", ",", "\"r\"", ")", "for", "x", "in", "file", ".", "readlines", "(", ")", ":", "for", "i", "in", "string", ".", "split", "(", "x", ")",...
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
[ "\"\"\"Counts words in file and returns dictionary.\"\"\"", "# increment the count of this word", "# append the word and its length" ]
[ { "param": "words", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "words", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_token...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
match
<not_specific>
def match(aedge, iedge): """Returns True if the active edge and the inactive edge match, otherwise False. """ if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return True return False
Returns True if the active edge and the inactive edge match, otherwise False.
Returns True if the active edge and the inactive edge match, otherwise False.
[ "Returns", "True", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "False", "." ]
def match(aedge, iedge): if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return True return False
[ "def", "match", "(", "aedge", ",", "iedge", ")", ":", "if", "aedge", "[", "1", "]", "==", "iedge", "[", "0", "]", ":", "if", "aedge", "[", "4", "]", "[", "aedge", "[", "2", "]", "]", "==", "iedge", "[", "3", "]", ":", "return", "True", "ret...
Returns True if the active edge and the inactive edge match, otherwise False.
[ "Returns", "True", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "False", "." ]
[ "\"\"\"Returns True if the active edge and the inactive edge match,\n otherwise False.\n \"\"\"" ]
[ { "param": "aedge", "type": null }, { "param": "iedge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "aedge", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "iedge", "type": null, "docstring": null, "docstring_tokens":...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
struct2Str
<not_specific>
def struct2Str(edge, chart, grammar): """Returns a string representation of the parse with labled brackets. Parameters: edges - the lsit of edges that make a parse chart - the current chart (list of edges) """ tmpstr = "" edgenums = chart[edge][5] tmpstr = "".join((tmpstr, "[", g...
Returns a string representation of the parse with labled brackets. Parameters: edges - the lsit of edges that make a parse chart - the current chart (list of edges)
Returns a string representation of the parse with labled brackets. the lsit of edges that make a parse chart - the current chart (list of edges)
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", ".", "the", "lsit", "of", "edges", "that", "make", "a", "parse", "chart", "-", "the", "current", "chart", "(", "list", "of", "edges", ")" ]
def struct2Str(edge, chart, grammar): tmpstr = "" edgenums = chart[edge][5] tmpstr = "".join((tmpstr, "[", grammar.id2s(chart[edge][3]))) for x in chart[edge][4]: if grammar.isTerminal(x): tmpstr = " ".join( (tmpstr, grammar.id2s(x)) ) else: tmpstr = " ".join( (tmpstr, struct2S...
[ "def", "struct2Str", "(", "edge", ",", "chart", ",", "grammar", ")", ":", "tmpstr", "=", "\"\"", "edgenums", "=", "chart", "[", "edge", "]", "[", "5", "]", "tmpstr", "=", "\"\"", ".", "join", "(", "(", "tmpstr", ",", "\"[\"", ",", "grammar", ".", ...
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
[ "\"\"\"Returns a string representation of the parse with\n labled brackets.\n\n Parameters:\n edges - the lsit of edges that make a parse\n chart - the current chart (list of edges)\n \"\"\"" ]
[ { "param": "edge", "type": null }, { "param": "chart", "type": null }, { "param": "grammar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "edge", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "chart", "type": null, "docstring": null, "docstring_tokens": ...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
struct2QtreeStr
<not_specific>
def struct2QtreeStr(edge, chart, grammar): """Returns a string representation of the parse with labled brackets. Parameters: edges - the lsit of edges that make a parse chart - the current chart (list of edges) """ tmpstr = "" edgenums = chart[edge][5] tmpstr = "".join((tmpstr, "...
Returns a string representation of the parse with labled brackets. Parameters: edges - the lsit of edges that make a parse chart - the current chart (list of edges)
Returns a string representation of the parse with labled brackets. the lsit of edges that make a parse chart - the current chart (list of edges)
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", ".", "the", "lsit", "of", "edges", "that", "make", "a", "parse", "chart", "-", "the", "current", "chart", "(", "list", "of", "edges", ")" ]
def struct2QtreeStr(edge, chart, grammar): tmpstr = "" edgenums = chart[edge][5] tmpstr = "".join((tmpstr, "[.", grammar.id2s(chart[edge][3]))) for x in chart[edge][4]: if grammar.isTerminal(x): tmpstr = " ".join( (tmpstr, grammar.id2s(x)) ) else: tmpstr = " ".join( (tmpstr, st...
[ "def", "struct2QtreeStr", "(", "edge", ",", "chart", ",", "grammar", ")", ":", "tmpstr", "=", "\"\"", "edgenums", "=", "chart", "[", "edge", "]", "[", "5", "]", "tmpstr", "=", "\"\"", ".", "join", "(", "(", "tmpstr", ",", "\"[.\"", ",", "grammar", ...
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
[ "\"\"\"Returns a string representation of the parse with\n labled brackets.\n\n Parameters:\n edges - the lsit of edges that make a parse\n chart - the current chart (list of edges)\n \"\"\"" ]
[ { "param": "edge", "type": null }, { "param": "chart", "type": null }, { "param": "grammar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "edge", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "chart", "type": null, "docstring": null, "docstring_tokens": ...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
ruleInvocation
<not_specific>
def ruleInvocation(lststart, chart, inputlength, grammar): """Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input. Parameters: lststart - start position at edge in...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input. Parameters: lststart - start position at edge in chart chart - the current chart inputlength - the le...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input. start position at edge in chart chart - the current chart inputlength - the length of the input sentence grammar - the grammar object raturned ...
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
def ruleInvocation(lststart, chart, inputlength, grammar): change = False for i in range(lststart, len(chart)): if chart[i][2] >= len(chart[i][4]): (start, end, index, lhs, rhs, consumed) = chart[i] for k in grammar.rhshash.get(lhs, ()): if len(k[1]) > inputlength - start: ...
[ "def", "ruleInvocation", "(", "lststart", ",", "chart", ",", "inputlength", ",", "grammar", ")", ":", "change", "=", "False", "for", "i", "in", "range", "(", "lststart", ",", "len", "(", "chart", ")", ")", ":", "if", "chart", "[", "i", "]", "[", "2...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
[ "\"\"\"Add all the rules of the grammar to the chart that\n are relavant:\n Find the rule with the LHS of edge as the leftmost RHS\n symbol and maximally the remaining length of the input.\n\n Parameters:\n lststart - start position at edge in chart\n chart - the current chart\n i...
[ { "param": "lststart", "type": null }, { "param": "chart", "type": null }, { "param": "inputlength", "type": null }, { "param": "grammar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lststart", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "chart", "type": null, "docstring": null, "docstring_token...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
fundamentalRule
<not_specific>
def fundamentalRule(chart, grammar): """The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges. Parameters: chart - the current chart """ change = False for aedge in chart: if isActive(aedge): for k in range(len(chart)): ...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges. Parameters: chart - the current chart
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges. the current chart
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", ".", "the", "current", "chart" ]
def fundamentalRule(chart, grammar): change = False for aedge in chart: if isActive(aedge): for k in range(len(chart)): if isInactive(chart[k]): if match(aedge, chart[k]): newedge = (aedge[0], chart[k][1], aedge[2] + 1, aedge...
[ "def", "fundamentalRule", "(", "chart", ",", "grammar", ")", ":", "change", "=", "False", "for", "aedge", "in", "chart", ":", "if", "isActive", "(", "aedge", ")", ":", "for", "k", "in", "range", "(", "len", "(", "chart", ")", ")", ":", "if", "isIna...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", "." ]
[ "\"\"\"The fundamental rule of chart parsing generates new edges by\n combining fitting active and inactive edges.\n\n Parameters:\n chart - the current chart\n \"\"\"" ]
[ { "param": "chart", "type": null }, { "param": "grammar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "chart", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "grammar", "type": null, "docstring": null, "docstring_tokens...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
parse
<not_specific>
def parse(inp, grammar): """Parse a list of tokens. Arguments: inp = a list of tokens grammar = an object returned by PSGParse """ chart = [] inputlength = len(inp) chartpos = 0 # remember start-position in chart for i in range(inputlength): # initialize with input token ...
Parse a list of tokens. Arguments: inp = a list of tokens grammar = an object returned by PSGParse
Parse a list of tokens. Arguments: inp = a list of tokens grammar = an object returned by PSGParse
[ "Parse", "a", "list", "of", "tokens", ".", "Arguments", ":", "inp", "=", "a", "list", "of", "tokens", "grammar", "=", "an", "object", "returned", "by", "PSGParse" ]
def parse(inp, grammar): chart = [] inputlength = len(inp) chartpos = 0 for i in range(inputlength): rules = grammar.rhshash.get(grammar.symb2id[inp[i]], ( ("", ()) ) ) for rule in rules: if rule[0]: chart.append( ( i, i + 1, 1, rule[0], rule[1], () ) ) if DEBUG: ...
[ "def", "parse", "(", "inp", ",", "grammar", ")", ":", "chart", "=", "[", "]", "inputlength", "=", "len", "(", "inp", ")", "chartpos", "=", "0", "for", "i", "in", "range", "(", "inputlength", ")", ":", "rules", "=", "grammar", ".", "rhshash", ".", ...
Parse a list of tokens.
[ "Parse", "a", "list", "of", "tokens", "." ]
[ "\"\"\"Parse a list of tokens.\n\n Arguments:\n inp = a list of tokens\n grammar = an object returned by PSGParse\n \"\"\"", "# remember start-position in chart", "# initialize with input token", "# set pointer to new edge in chart" ]
[ { "param": "inp", "type": null }, { "param": "grammar", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "inp", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "grammar", "type": null, "docstring": null, "docstring_tokens":...
8049a8addd1e9d6ecde275ca4a644ca43e90ee61
dcavar/dcavar.github.io
Charty/resources/ChartyPy.py
[ "Apache-2.0" ]
Python
printParses
null
def printParses(parses): """Prints the parse as brackated string to the screen.""" numparses = len(parses) counter = 0 for i in parses: counter += 1 print "Parse:", counter, "of", numparses print i
Prints the parse as brackated string to the screen.
Prints the parse as brackated string to the screen.
[ "Prints", "the", "parse", "as", "brackated", "string", "to", "the", "screen", "." ]
def printParses(parses): numparses = len(parses) counter = 0 for i in parses: counter += 1 print "Parse:", counter, "of", numparses print i
[ "def", "printParses", "(", "parses", ")", ":", "numparses", "=", "len", "(", "parses", ")", "counter", "=", "0", "for", "i", "in", "parses", ":", "counter", "+=", "1", "print", "\"Parse:\"", ",", "counter", ",", "\"of\"", ",", "numparses", "print", "i"...
Prints the parse as brackated string to the screen.
[ "Prints", "the", "parse", "as", "brackated", "string", "to", "the", "screen", "." ]
[ "\"\"\"Prints the parse as brackated string to the screen.\"\"\"" ]
[ { "param": "parses", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "parses", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
dc1b92f4e26c080d2b991ab2a187beb2be702bb3
dcavar/dcavar.github.io
IntroCModelingLA/Code/ngram.py
[ "Apache-2.0" ]
Python
eliminateFrequences
null
def eliminateFrequences(self, num): """Eliminates all ngrams with a frequency <= num.""" for x in self.ngrams.keys(): if self.ngrams[x] <= num: self.num -= self.ngrams[x] del self.ngrams[x]
Eliminates all ngrams with a frequency <= num.
Eliminates all ngrams with a frequency <= num.
[ "Eliminates", "all", "ngrams", "with", "a", "frequency", "<", "=", "num", "." ]
def eliminateFrequences(self, num): for x in self.ngrams.keys(): if self.ngrams[x] <= num: self.num -= self.ngrams[x] del self.ngrams[x]
[ "def", "eliminateFrequences", "(", "self", ",", "num", ")", ":", "for", "x", "in", "self", ".", "ngrams", ".", "keys", "(", ")", ":", "if", "self", ".", "ngrams", "[", "x", "]", "<=", "num", ":", "self", ".", "num", "-=", "self", ".", "ngrams", ...
Eliminates all ngrams with a frequency <= num.
[ "Eliminates", "all", "ngrams", "with", "a", "frequency", "<", "=", "num", "." ]
[ "\"\"\"Eliminates all ngrams with a frequency <= num.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "num", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "num", "type": null, "docstring": null, "docstring_tokens": []...
dc1b92f4e26c080d2b991ab2a187beb2be702bb3
dcavar/dcavar.github.io
IntroCModelingLA/Code/ngram.py
[ "Apache-2.0" ]
Python
cleanText
<not_specific>
def cleanText(self, text): """Eliminates punctuation symbols from the submitted text.""" for i in ":<>,./?\\';!()[]{}-" + '"': # punctuation: if i in text: text = replace(text, i, " ") return text
Eliminates punctuation symbols from the submitted text.
Eliminates punctuation symbols from the submitted text.
[ "Eliminates", "punctuation", "symbols", "from", "the", "submitted", "text", "." ]
def cleanText(self, text): for i in ":<>,./?\\';!()[]{}-" + '"': if i in text: text = replace(text, i, " ") return text
[ "def", "cleanText", "(", "self", ",", "text", ")", ":", "for", "i", "in", "\":<>,./?\\\\';!()[]{}-\"", "+", "'\"'", ":", "if", "i", "in", "text", ":", "text", "=", "replace", "(", "text", ",", "i", ",", "\" \"", ")", "return", "text" ]
Eliminates punctuation symbols from the submitted text.
[ "Eliminates", "punctuation", "symbols", "from", "the", "submitted", "text", "." ]
[ "\"\"\"Eliminates punctuation symbols from the submitted text.\"\"\"", "# punctuation:" ]
[ { "param": "self", "type": null }, { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [...
dc1b92f4e26c080d2b991ab2a187beb2be702bb3
dcavar/dcavar.github.io
IntroCModelingLA/Code/ngram.py
[ "Apache-2.0" ]
Python
cleanFWords
null
def cleanFWords(self): """Eliminate ngrams that contain function words.""" for i in self.ngrams.keys(): parts = split(i) for x in parts: if x in self.functionWords: del self.ngrams[i]
Eliminate ngrams that contain function words.
Eliminate ngrams that contain function words.
[ "Eliminate", "ngrams", "that", "contain", "function", "words", "." ]
def cleanFWords(self): for i in self.ngrams.keys(): parts = split(i) for x in parts: if x in self.functionWords: del self.ngrams[i]
[ "def", "cleanFWords", "(", "self", ")", ":", "for", "i", "in", "self", ".", "ngrams", ".", "keys", "(", ")", ":", "parts", "=", "split", "(", "i", ")", "for", "x", "in", "parts", ":", "if", "x", "in", "self", ".", "functionWords", ":", "del", "...
Eliminate ngrams that contain function words.
[ "Eliminate", "ngrams", "that", "contain", "function", "words", "." ]
[ "\"\"\"Eliminate ngrams that contain function words.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
38b4eb979febb1c966115bdcfd3e5f98c085fe89
dcavar/dcavar.github.io
pycl/Code/freq6.py
[ "Apache-2.0" ]
Python
countWords
<not_specific>
def countWords(words, filename): """Counts words in file and returns dictionary.""" count = words.get(countername, 0) try: file = codecs.open(filename, "r", "utf8") tokens = [string.lower(i) for i in re.findall(ur"[A-Za-zčČćĆšŠžŽđĐ]+'?[A-Za-zčČćĆšŠžŽđĐ]?",file.read())] for i in tokens: if i not in functionW...
Counts words in file and returns dictionary.
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
def countWords(words, filename): count = words.get(countername, 0) try: file = codecs.open(filename, "r", "utf8") tokens = [string.lower(i) for i in re.findall(ur"[A-Za-zčČćĆšŠžŽđĐ]+'?[A-Za-zčČćĆšŠžŽđĐ]?",file.read())] for i in tokens: if i not in functionWordsEN: words[i] = words.get(i, 0) + 1 count...
[ "def", "countWords", "(", "words", ",", "filename", ")", ":", "count", "=", "words", ".", "get", "(", "countername", ",", "0", ")", "try", ":", "file", "=", "codecs", ".", "open", "(", "filename", ",", "\"r\"", ",", "\"utf8\"", ")", "tokens", "=", ...
Counts words in file and returns dictionary.
[ "Counts", "words", "in", "file", "and", "returns", "dictionary", "." ]
[ "\"\"\"Counts words in file and returns dictionary.\"\"\"" ]
[ { "param": "words", "type": null }, { "param": "filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "words", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filename", "type": null, "docstring": null, "docstring_token...
7bd517fb28612cc406ca395d2b35ca87fba2236b
dcavar/dcavar.github.io
IntroCModelingLA/Code/stattools.py
[ "Apache-2.0" ]
Python
puncTrim
<not_specific>
def puncTrim(word): """Eliminates spaces and punctuation marks left and right of words.""" word = string.strip(word) if len(word) > 0: while word[0] in string.punctuation + "1234567890": word = word[1:] if word == "": break if len(word) > 0: while word[-1] in string.punctuation: word = word[:-1] ...
Eliminates spaces and punctuation marks left and right of words.
Eliminates spaces and punctuation marks left and right of words.
[ "Eliminates", "spaces", "and", "punctuation", "marks", "left", "and", "right", "of", "words", "." ]
def puncTrim(word): word = string.strip(word) if len(word) > 0: while word[0] in string.punctuation + "1234567890": word = word[1:] if word == "": break if len(word) > 0: while word[-1] in string.punctuation: word = word[:-1] if word == "": break return word
[ "def", "puncTrim", "(", "word", ")", ":", "word", "=", "string", ".", "strip", "(", "word", ")", "if", "len", "(", "word", ")", ">", "0", ":", "while", "word", "[", "0", "]", "in", "string", ".", "punctuation", "+", "\"1234567890\"", ":", "word", ...
Eliminates spaces and punctuation marks left and right of words.
[ "Eliminates", "spaces", "and", "punctuation", "marks", "left", "and", "right", "of", "words", "." ]
[ "\"\"\"Eliminates spaces and punctuation marks left and right of words.\"\"\"" ]
[ { "param": "word", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "word", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a6c1691f5b587d141a3c662ab640860f6120a8c3
dcavar/dcavar.github.io
Charty/download/files/ChartyPy.py
[ "Apache-2.0" ]
Python
match
<not_specific>
def match(aedge, iedge): """Returns 1 if the active edge and the inactive edge match, otherwise 0.""" if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return 1 return 0
Returns 1 if the active edge and the inactive edge match, otherwise 0.
Returns 1 if the active edge and the inactive edge match, otherwise 0.
[ "Returns", "1", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "0", "." ]
def match(aedge, iedge): if aedge[1] == iedge[0]: if aedge[4][aedge[2]] == iedge[3]: return 1 return 0
[ "def", "match", "(", "aedge", ",", "iedge", ")", ":", "if", "aedge", "[", "1", "]", "==", "iedge", "[", "0", "]", ":", "if", "aedge", "[", "4", "]", "[", "aedge", "[", "2", "]", "]", "==", "iedge", "[", "3", "]", ":", "return", "1", "return...
Returns 1 if the active edge and the inactive edge match, otherwise 0.
[ "Returns", "1", "if", "the", "active", "edge", "and", "the", "inactive", "edge", "match", "otherwise", "0", "." ]
[ "\"\"\"Returns 1 if the active edge and the inactive edge match,\n otherwise 0.\"\"\"" ]
[ { "param": "aedge", "type": null }, { "param": "iedge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "aedge", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "iedge", "type": null, "docstring": null, "docstring_tokens":...
a6c1691f5b587d141a3c662ab640860f6120a8c3
dcavar/dcavar.github.io
Charty/download/files/ChartyPy.py
[ "Apache-2.0" ]
Python
structToStr
<not_specific>
def structToStr(edges): """Returns a string representation of the parse with labled brackets.""" tmpstr = "" for i in edges: if chart[i][5]: tmpstr = tmpstr + "[" + chart[i][3] + " " + structToStr(chart[i][5]) + " ] " else: tmpstr = tmpstr + "[" + chart[i][3] + " " ...
Returns a string representation of the parse with labled brackets.
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
def structToStr(edges): tmpstr = "" for i in edges: if chart[i][5]: tmpstr = tmpstr + "[" + chart[i][3] + " " + structToStr(chart[i][5]) + " ] " else: tmpstr = tmpstr + "[" + chart[i][3] + " " for x in chart[i][4]: tmpstr = " ".join([tmpstr, x]) tmpstr =...
[ "def", "structToStr", "(", "edges", ")", ":", "tmpstr", "=", "\"\"", "for", "i", "in", "edges", ":", "if", "chart", "[", "i", "]", "[", "5", "]", ":", "tmpstr", "=", "tmpstr", "+", "\"[\"", "+", "chart", "[", "i", "]", "[", "3", "]", "+", "\"...
Returns a string representation of the parse with labled brackets.
[ "Returns", "a", "string", "representation", "of", "the", "parse", "with", "labled", "brackets", "." ]
[ "\"\"\"Returns a string representation of the parse with\n labled brackets.\"\"\"" ]
[ { "param": "edges", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "edges", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a6c1691f5b587d141a3c662ab640860f6120a8c3
dcavar/dcavar.github.io
Charty/download/files/ChartyPy.py
[ "Apache-2.0" ]
Python
ruleInvocation
<not_specific>
def ruleInvocation(lststart): """Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.""" change = 0 for i in range(lststart, len(chart)): if chart[i][2] >= len(char...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
def ruleInvocation(lststart): change = 0 for i in range(lststart, len(chart)): if chart[i][2] >= len(chart[i][4]): (start, end, index, lhs, rhs, consumed) = chart[i] if grammar.rhshash.has_key(lhs): for k in grammar.rhshash[lhs]: if len(grammar.rhs[k]) > inputle...
[ "def", "ruleInvocation", "(", "lststart", ")", ":", "change", "=", "0", "for", "i", "in", "range", "(", "lststart", ",", "len", "(", "chart", ")", ")", ":", "if", "chart", "[", "i", "]", "[", "2", "]", ">=", "len", "(", "chart", "[", "i", "]", ...
Add all the rules of the grammar to the chart that are relavant: Find the rule with the LHS of edge as the leftmost RHS symbol and maximally the remaining length of the input.
[ "Add", "all", "the", "rules", "of", "the", "grammar", "to", "the", "chart", "that", "are", "relavant", ":", "Find", "the", "rule", "with", "the", "LHS", "of", "edge", "as", "the", "leftmost", "RHS", "symbol", "and", "maximally", "the", "remaining", "leng...
[ "\"\"\"Add all the rules of the grammar to the chart that\n are relavant:\n Find the rule with the LHS of edge as the leftmost RHS\n symbol and maximally the remaining length of the input.\"\"\"", "# only inactive edge" ]
[ { "param": "lststart", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lststart", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a6c1691f5b587d141a3c662ab640860f6120a8c3
dcavar/dcavar.github.io
Charty/download/files/ChartyPy.py
[ "Apache-2.0" ]
Python
fundamentalRule
<not_specific>
def fundamentalRule(): """The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.""" change = 0 for aedge in chart: if isActive(aedge): for k in range(len(chart)): if isInactive(chart[k]): if match(aedge, chart[k]...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", "." ]
def fundamentalRule(): change = 0 for aedge in chart: if isActive(aedge): for k in range(len(chart)): if isInactive(chart[k]): if match(aedge, chart[k]): newedge = aedge[:] newedge[5] = aedge[5][:] newedge[5].append(k)...
[ "def", "fundamentalRule", "(", ")", ":", "change", "=", "0", "for", "aedge", "in", "chart", ":", "if", "isActive", "(", "aedge", ")", ":", "for", "k", "in", "range", "(", "len", "(", "chart", ")", ")", ":", "if", "isInactive", "(", "chart", "[", ...
The fundamental rule of chart parsing generates new edges by combining fitting active and inactive edges.
[ "The", "fundamental", "rule", "of", "chart", "parsing", "generates", "new", "edges", "by", "combining", "fitting", "active", "and", "inactive", "edges", "." ]
[ "\"\"\"The fundamental rule of chart parsing generates new edges by\n combining fitting active and inactive edges.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
a6c1691f5b587d141a3c662ab640860f6120a8c3
dcavar/dcavar.github.io
Charty/download/files/ChartyPy.py
[ "Apache-2.0" ]
Python
parse
null
def parse(input): """Parse a list of tokens. """ global chart global inputlength chart = [] inputlength = len(input) chartpos = 0 # remember start-position in chart for i in range(len(input)): # initialize with input token chart.append([ i, i + 1, 1, grammar.getTag(input[i]), [ inp...
Parse a list of tokens.
Parse a list of tokens.
[ "Parse", "a", "list", "of", "tokens", "." ]
def parse(input): global chart global inputlength chart = [] inputlength = len(input) chartpos = 0 for i in range(len(input)): chart.append([ i, i + 1, 1, grammar.getTag(input[i]), [ input[i] ], [] ]) if DEBUG: print "Adding edge:", chart[len(chart) - 1] change = 1 w...
[ "def", "parse", "(", "input", ")", ":", "global", "chart", "global", "inputlength", "chart", "=", "[", "]", "inputlength", "=", "len", "(", "input", ")", "chartpos", "=", "0", "for", "i", "in", "range", "(", "len", "(", "input", ")", ")", ":", "cha...
Parse a list of tokens.
[ "Parse", "a", "list", "of", "tokens", "." ]
[ "\"\"\"Parse a list of tokens.\n \"\"\"", "# remember start-position in chart", "# initialize with input token", "# set pointer to new edge in chart" ]
[ { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9cecf587f45cbdee9fadf473ff62e729168fe015
dcavar/dcavar.github.io
LID/resources/lid.py
[ "Apache-2.0" ]
Python
createTrigrams
null
def createTrigrams(self, text): """Creates tri-grams from characters.""" self.num = 0 # storage for the number of trigrams self.trigrams = {} # dictionary storage for trigrams text = re.sub(r"\n", " ", text) # replace newlines in text text = self.cleanTextSC(text) # clean tri...
Creates tri-grams from characters.
Creates tri-grams from characters.
[ "Creates", "tri", "-", "grams", "from", "characters", "." ]
def createTrigrams(self, text): self.num = 0 self.trigrams = {} text = re.sub(r"\n", " ", text) text = self.cleanTextSC(text) text = re.sub(r"\s+", " ", text) self.characters = len(text) for i in range(len(text) - 2): trigram = text[i:i+3] self.num += 1 ...
[ "def", "createTrigrams", "(", "self", ",", "text", ")", ":", "self", ".", "num", "=", "0", "self", ".", "trigrams", "=", "{", "}", "text", "=", "re", ".", "sub", "(", "r\"\\n\"", ",", "\" \"", ",", "text", ")", "text", "=", "self", ".", "cleanTex...
Creates tri-grams from characters.
[ "Creates", "tri", "-", "grams", "from", "characters", "." ]
[ "\"\"\"Creates tri-grams from characters.\"\"\"", "# storage for the number of trigrams", "# dictionary storage for trigrams", "# replace newlines in text", "# clean trigrams with punctuation marks", "# replace multiple spaces/tabs ", "# get number of characters", "# go thru list up to one but last wo...
[ { "param": "self", "type": null }, { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [...
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """ Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding projection with a SerializedLinear layer - Adds r...
Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding projection with a SerializedLinear layer - Adds recomputation checkpoints
Transform the model to run in an IPU pipeline. Adds pipeline stages to the model Replaces self-attention layers with fused-qkv self-attention layers (If enabled) Replaces the word embedding projection with a SerializedLinear layer Adds recomputation checkpoints
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", ".", "Adds", "pipeline", "stages", "to", "the", "model", "Replaces", "self", "-", "attention", "layers", "with", "fused", "-", "qkv", "self", "-", "attention", "layers", "(", "If", ...
def parallelize(self): super().parallelize() for layer in self.bert.encoder.layer: layer.attention.self.__class__ = BertFusedSelfAttention if self.ipu_config.embedding_serialization_factor > 1: serialized_decoder = SerializedLinear( self.config.hidden_size...
[ "def", "parallelize", "(", "self", ")", ":", "super", "(", ")", ".", "parallelize", "(", ")", "for", "layer", "in", "self", ".", "bert", ".", "encoder", ".", "layer", ":", "layer", ".", "attention", ".", "self", ".", "__class__", "=", "BertFusedSelfAtt...
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"\n Transform the model to run in an IPU pipeline.\n - Adds pipeline stages to the model\n - Replaces self-attention layers with fused-qkv self-attention layers\n - (If enabled) Replaces the word embedding projection with a SerializedLinear layer\n - Adds recomputation check...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
deparallelize
<not_specific>
def deparallelize(self): """ Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model. """ super().deparallelize() for layer in self.bert.encoder....
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model.
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", ".", "You", "should", "call", "this", "before", "doing", "`", "save_pretrained", "`", "so", "that", "the", "`", "model", ".", "state_dict", "`", "is", "compatible", "w...
def deparallelize(self): super().deparallelize() for layer in self.bert.encoder.layer: layer.attention.self.__class__ = BertSelfAttention if self.ipu_config.embedding_serialization_factor > 1: decoder = nn.Linear( self.config.hidden_size, s...
[ "def", "deparallelize", "(", "self", ")", ":", "super", "(", ")", ".", "deparallelize", "(", ")", "for", "layer", "in", "self", ".", "bert", ".", "encoder", ".", "layer", ":", "layer", ".", "attention", ".", "self", ".", "__class__", "=", "BertSelfAtte...
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
[ "\"\"\"\n Undo the changes to the model done by `parallelize`.\n You should call this before doing `save_pretrained` so that the `model.state_dict` is\n compatible with the original model.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
truncated_normal_
null
def truncated_normal_(tensor, mean=0, std=1): """ Truncated Normal distribution, truncated at 2 sigma """ r = torch.tensor(truncnorm.rvs(-2, 2, loc=mean, scale=std, size=tensor.shape)) tensor.data.copy_(r)
Truncated Normal distribution, truncated at 2 sigma
Truncated Normal distribution, truncated at 2 sigma
[ "Truncated", "Normal", "distribution", "truncated", "at", "2", "sigma" ]
def truncated_normal_(tensor, mean=0, std=1): r = torch.tensor(truncnorm.rvs(-2, 2, loc=mean, scale=std, size=tensor.shape)) tensor.data.copy_(r)
[ "def", "truncated_normal_", "(", "tensor", ",", "mean", "=", "0", ",", "std", "=", "1", ")", ":", "r", "=", "torch", ".", "tensor", "(", "truncnorm", ".", "rvs", "(", "-", "2", ",", "2", ",", "loc", "=", "mean", ",", "scale", "=", "std", ",", ...
Truncated Normal distribution, truncated at 2 sigma
[ "Truncated", "Normal", "distribution", "truncated", "at", "2", "sigma" ]
[ "\"\"\"\n Truncated Normal distribution, truncated at 2 sigma\n \"\"\"" ]
[ { "param": "tensor", "type": null }, { "param": "mean", "type": null }, { "param": "std", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tensor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mean", "type": null, "docstring": null, "docstring_tokens":...
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """ Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding projection with a SerializedLinear layer - Adds r...
Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding projection with a SerializedLinear layer - Adds recomputation checkpoints
Transform the model to run in an IPU pipeline. Adds pipeline stages to the model Replaces self-attention layers with fused-qkv self-attention layers (If enabled) Replaces the word embedding projection with a SerializedLinear layer Adds recomputation checkpoints
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", ".", "Adds", "pipeline", "stages", "to", "the", "model", "Replaces", "self", "-", "attention", "layers", "with", "fused", "-", "qkv", "self", "-", "attention", "layers", "(", "If", ...
def parallelize(self): super().parallelize() for layer in self.bert.encoder.layer: fused = BertFusedSelfAttention(self.config) fused.load_state_dict(layer.attention.self.state_dict()) layer.attention.self = fused if self.ipu_config.embedding_serialization_fact...
[ "def", "parallelize", "(", "self", ")", ":", "super", "(", ")", ".", "parallelize", "(", ")", "for", "layer", "in", "self", ".", "bert", ".", "encoder", ".", "layer", ":", "fused", "=", "BertFusedSelfAttention", "(", "self", ".", "config", ")", "fused"...
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"\n Transform the model to run in an IPU pipeline.\n - Adds pipeline stages to the model\n - Replaces self-attention layers with fused-qkv self-attention layers\n - (If enabled) Replaces the word embedding projection with a SerializedLinear layer\n - Adds recomputation check...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """ Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding with a SerializedEmbedding - Adds recomputation c...
Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - Replaces self-attention layers with fused-qkv self-attention layers - (If enabled) Replaces the word embedding with a SerializedEmbedding - Adds recomputation checkpoints
Transform the model to run in an IPU pipeline. Adds pipeline stages to the model Replaces self-attention layers with fused-qkv self-attention layers (If enabled) Replaces the word embedding with a SerializedEmbedding Adds recomputation checkpoints
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", ".", "Adds", "pipeline", "stages", "to", "the", "model", "Replaces", "self", "-", "attention", "layers", "with", "fused", "-", "qkv", "self", "-", "attention", "layers", "(", "If", ...
def parallelize(self): super().parallelize() for layer in self.bert.encoder.layer: layer.attention.self.__class__ = BertFusedSelfAttention layer_ipu = get_layer_ipu(self.ipu_config.layers_per_ipu) logger.info("-------------------- Device Allocation --------------------") ...
[ "def", "parallelize", "(", "self", ")", ":", "super", "(", ")", ".", "parallelize", "(", ")", "for", "layer", "in", "self", ".", "bert", ".", "encoder", ".", "layer", ":", "layer", ".", "attention", ".", "self", ".", "__class__", "=", "BertFusedSelfAtt...
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"\n Transform the model to run in an IPU pipeline.\n - Adds pipeline stages to the model\n - Replaces self-attention layers with fused-qkv self-attention layers\n - (If enabled) Replaces the word embedding with a SerializedEmbedding\n - Adds recomputation checkpoints\n ...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8c376760d8eed1a9c4e5be206c59bdc0b1c72dbd
huggingface/optimum-graphcore
optimum/graphcore/models/bert/modeling_bert.py
[ "Apache-2.0" ]
Python
deparallelize
<not_specific>
def deparallelize(self): """ Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model. """ super().deparallelize() for layer in self.bert.encoder....
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model.
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is compatible with the original model.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", ".", "You", "should", "call", "this", "before", "doing", "`", "save_pretrained", "`", "so", "that", "the", "`", "model", ".", "state_dict", "`", "is", "compatible", "w...
def deparallelize(self): super().deparallelize() for layer in self.bert.encoder.layer: layer.attention.self.__class__ = BertSelfAttention if self.ipu_config.embedding_serialization_factor > 1: self.bert.embeddings.word_embeddings = self.bert.embeddings.word_embeddings.des...
[ "def", "deparallelize", "(", "self", ")", ":", "super", "(", ")", ".", "deparallelize", "(", ")", "for", "layer", "in", "self", ".", "bert", ".", "encoder", ".", "layer", ":", "layer", ".", "attention", ".", "self", ".", "__class__", "=", "BertSelfAtte...
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
[ "\"\"\"\n Undo the changes to the model done by `parallelize`.\n You should call this before doing `save_pretrained` so that the `model.state_dict` is\n compatible with the original model.\n \"\"\"", "# Deserialize the serialized word embedding" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3e7aa29c06b52705821e91eb0c9114f73fa0f90d
huggingface/optimum-graphcore
optimum/graphcore/modeling_utils.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """Transform the model to run in an IPU pipeline.""" self._hooks = [] self._has_ipu_config_check() return self
Transform the model to run in an IPU pipeline.
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
def parallelize(self): self._hooks = [] self._has_ipu_config_check() return self
[ "def", "parallelize", "(", "self", ")", ":", "self", ".", "_hooks", "=", "[", "]", "self", ".", "_has_ipu_config_check", "(", ")", "return", "self" ]
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"Transform the model to run in an IPU pipeline.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3e7aa29c06b52705821e91eb0c9114f73fa0f90d
huggingface/optimum-graphcore
optimum/graphcore/modeling_utils.py
[ "Apache-2.0" ]
Python
recomputation_checkpoint
<not_specific>
def recomputation_checkpoint(module: nn.Module): """Annotates the output of a module to be checkpointed instead of recomputed""" def recompute_outputs(module, inputs, outputs): if isinstance(outputs, torch.Tensor): return poptorch.recomputationCheckpoint(outputs) elif isinstance...
Annotates the output of a module to be checkpointed instead of recomputed
Annotates the output of a module to be checkpointed instead of recomputed
[ "Annotates", "the", "output", "of", "a", "module", "to", "be", "checkpointed", "instead", "of", "recomputed" ]
def recomputation_checkpoint(module: nn.Module): def recompute_outputs(module, inputs, outputs): if isinstance(outputs, torch.Tensor): return poptorch.recomputationCheckpoint(outputs) elif isinstance(outputs, tuple): return tuple(poptorch.recomputationCheckpoint(y) for y in o...
[ "def", "recomputation_checkpoint", "(", "module", ":", "nn", ".", "Module", ")", ":", "def", "recompute_outputs", "(", "module", ",", "inputs", ",", "outputs", ")", ":", "if", "isinstance", "(", "outputs", ",", "torch", ".", "Tensor", ")", ":", "return", ...
Annotates the output of a module to be checkpointed instead of recomputed
[ "Annotates", "the", "output", "of", "a", "module", "to", "be", "checkpointed", "instead", "of", "recomputed" ]
[ "\"\"\"Annotates the output of a module to be checkpointed instead of\n recomputed\"\"\"" ]
[ { "param": "module", "type": "nn.Module" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "module", "type": "nn.Module", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
3e7aa29c06b52705821e91eb0c9114f73fa0f90d
huggingface/optimum-graphcore
optimum/graphcore/modeling_utils.py
[ "Apache-2.0" ]
Python
outline_attribute
<not_specific>
def outline_attribute(module: nn.Module, value: str): """Adds an attribute to a module. This attribute will be used when comparing operation equivalence in outlining. For example: layer1 = nn.Linear(...) layer2 = nn.Linear(...) layer3 = nn.Linear(...) layer4 = nn.Linear(...) outline_attribu...
Adds an attribute to a module. This attribute will be used when comparing operation equivalence in outlining. For example: layer1 = nn.Linear(...) layer2 = nn.Linear(...) layer3 = nn.Linear(...) layer4 = nn.Linear(...) outline_attribute(layer1, "A") outline_attribute(layer2, "A") outlin...
Adds an attribute to a module. This attribute will be used when comparing operation equivalence in outlining. For example. The code for layer1 can be reused for layer2. But it can't be used for layer3 or layer4.
[ "Adds", "an", "attribute", "to", "a", "module", ".", "This", "attribute", "will", "be", "used", "when", "comparing", "operation", "equivalence", "in", "outlining", ".", "For", "example", ".", "The", "code", "for", "layer1", "can", "be", "reused", "for", "l...
def outline_attribute(module: nn.Module, value: str): context = poptorch.Attribute(__outline={"layer": value}) def enable(*args): context.__enter__() def disable(*args): context.__exit__(None, None, None) handles = [] handles.append(module.register_forward_pre_hook(enable)) handl...
[ "def", "outline_attribute", "(", "module", ":", "nn", ".", "Module", ",", "value", ":", "str", ")", ":", "context", "=", "poptorch", ".", "Attribute", "(", "__outline", "=", "{", "\"layer\"", ":", "value", "}", ")", "def", "enable", "(", "*", "args", ...
Adds an attribute to a module.
[ "Adds", "an", "attribute", "to", "a", "module", "." ]
[ "\"\"\"Adds an attribute to a module. This attribute will be used\n when comparing operation equivalence in outlining. For example:\n\n layer1 = nn.Linear(...)\n layer2 = nn.Linear(...)\n layer3 = nn.Linear(...)\n layer4 = nn.Linear(...)\n outline_attribute(layer1, \"A\")\n outline_attribute(la...
[ { "param": "module", "type": "nn.Module" }, { "param": "value", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "module", "type": "nn.Module", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": "str", "docstring": null, "docstring...
3e7aa29c06b52705821e91eb0c9114f73fa0f90d
huggingface/optimum-graphcore
optimum/graphcore/modeling_utils.py
[ "Apache-2.0" ]
Python
deserialize
<not_specific>
def deserialize(self): """ Deserialize the internal wrapped embedding layer and return it as a `nn.Embedding` object. Returns: `nn.Embedding` layer """ return nn.Embedding.from_pretrained(torch.vstack([l.weight for l in self.split_embeddings]), padding_idx=0)
Deserialize the internal wrapped embedding layer and return it as a `nn.Embedding` object. Returns: `nn.Embedding` layer
Deserialize the internal wrapped embedding layer and return it as a `nn.Embedding` object.
[ "Deserialize", "the", "internal", "wrapped", "embedding", "layer", "and", "return", "it", "as", "a", "`", "nn", ".", "Embedding", "`", "object", "." ]
def deserialize(self): return nn.Embedding.from_pretrained(torch.vstack([l.weight for l in self.split_embeddings]), padding_idx=0)
[ "def", "deserialize", "(", "self", ")", ":", "return", "nn", ".", "Embedding", ".", "from_pretrained", "(", "torch", ".", "vstack", "(", "[", "l", ".", "weight", "for", "l", "in", "self", ".", "split_embeddings", "]", ")", ",", "padding_idx", "=", "0",...
Deserialize the internal wrapped embedding layer and return it as a `nn.Embedding` object.
[ "Deserialize", "the", "internal", "wrapped", "embedding", "layer", "and", "return", "it", "as", "a", "`", "nn", ".", "Embedding", "`", "object", "." ]
[ "\"\"\"\n Deserialize the internal wrapped embedding layer and return it as a\n `nn.Embedding` object.\n\n Returns:\n `nn.Embedding` layer\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
3e7aa29c06b52705821e91eb0c9114f73fa0f90d
huggingface/optimum-graphcore
optimum/graphcore/modeling_utils.py
[ "Apache-2.0" ]
Python
forward
<not_specific>
def forward(self, sequence, positions): """ Gather the vectors at the specific positions over a batch. """ num_classes = int(sequence.shape[1]) one_hot_positions = F.one_hot(positions, num_classes) if self._is_half: one_hot_positions = one_hot_positions.half()...
Gather the vectors at the specific positions over a batch.
Gather the vectors at the specific positions over a batch.
[ "Gather", "the", "vectors", "at", "the", "specific", "positions", "over", "a", "batch", "." ]
def forward(self, sequence, positions): num_classes = int(sequence.shape[1]) one_hot_positions = F.one_hot(positions, num_classes) if self._is_half: one_hot_positions = one_hot_positions.half() else: one_hot_positions = one_hot_positions.float() return tor...
[ "def", "forward", "(", "self", ",", "sequence", ",", "positions", ")", ":", "num_classes", "=", "int", "(", "sequence", ".", "shape", "[", "1", "]", ")", "one_hot_positions", "=", "F", ".", "one_hot", "(", "positions", ",", "num_classes", ")", "if", "s...
Gather the vectors at the specific positions over a batch.
[ "Gather", "the", "vectors", "at", "the", "specific", "positions", "over", "a", "batch", "." ]
[ "\"\"\"\n Gather the vectors at the specific positions over a batch.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "sequence", "type": null }, { "param": "positions", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sequence", "type": null, "docstring": null, "docstring_tokens...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_pytorch_optimizer_to_poptorch
poptorch.optim.Optimizer
def _pytorch_optimizer_to_poptorch( self, optimizer: optim.Optimizer, model: Union[PreTrainedModel, nn.Module], pipelined_model: Union[PreTrainedModel, nn.Module], ) -> poptorch.optim.Optimizer: """ Converts a PyTorch optimizer to a poptorch optimizer. Args: ...
Converts a PyTorch optimizer to a poptorch optimizer. Args: optimizer (`~torch.optim.Optimizer`): The optimizer to convert. model (~transformers.modeling_utils.PreTrainedModel or torch.nn.Module): The original model the optimizer has parameter references to. ...
Converts a PyTorch optimizer to a poptorch optimizer.
[ "Converts", "a", "PyTorch", "optimizer", "to", "a", "poptorch", "optimizer", "." ]
def _pytorch_optimizer_to_poptorch( self, optimizer: optim.Optimizer, model: Union[PreTrainedModel, nn.Module], pipelined_model: Union[PreTrainedModel, nn.Module], ) -> poptorch.optim.Optimizer: first_order_type = torch.float16 if self.ipu_config.enable_half_first_order_momen...
[ "def", "_pytorch_optimizer_to_poptorch", "(", "self", ",", "optimizer", ":", "optim", ".", "Optimizer", ",", "model", ":", "Union", "[", "PreTrainedModel", ",", "nn", ".", "Module", "]", ",", "pipelined_model", ":", "Union", "[", "PreTrainedModel", ",", "nn", ...
Converts a PyTorch optimizer to a poptorch optimizer.
[ "Converts", "a", "PyTorch", "optimizer", "to", "a", "poptorch", "optimizer", "." ]
[ "\"\"\"\n Converts a PyTorch optimizer to a poptorch optimizer.\n\n Args:\n optimizer (`~torch.optim.Optimizer`): The optimizer to convert.\n model (~transformers.modeling_utils.PreTrainedModel or torch.nn.Module):\n The original model the optimizer has parameter r...
[ { "param": "self", "type": null }, { "param": "optimizer", "type": "optim.Optimizer" }, { "param": "model", "type": "Union[PreTrainedModel, nn.Module]" }, { "param": "pipelined_model", "type": "Union[PreTrainedModel, nn.Module]" } ]
{ "returns": [ { "docstring": "The converted poptorch optimizer.", "docstring_tokens": [ "The", "converted", "poptorch", "optimizer", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, ...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_compile_model
<not_specific>
def _compile_model( self, model: poptorch.PoplarExecutor, sample_batch: Union[Dict[str, torch.Tensor], Tuple[torch.Tensor]], log: bool = False, ): """ Compiles the model with poptorch. Args: model: The model to compile (already wrapped). ...
Compiles the model with poptorch. Args: model: The model to compile (already wrapped). sample_batch: The inputs to use the compilation, this will set the input shapes that the compiled model can accept. log: Whether to log that compilation is happeni...
Compiles the model with poptorch.
[ "Compiles", "the", "model", "with", "poptorch", "." ]
def _compile_model( self, model: poptorch.PoplarExecutor, sample_batch: Union[Dict[str, torch.Tensor], Tuple[torch.Tensor]], log: bool = False, ): if model.isCompiled(): return if log: logger.info("Compiling Model...") sample_batch = se...
[ "def", "_compile_model", "(", "self", ",", "model", ":", "poptorch", ".", "PoplarExecutor", ",", "sample_batch", ":", "Union", "[", "Dict", "[", "str", ",", "torch", ".", "Tensor", "]", ",", "Tuple", "[", "torch", ".", "Tensor", "]", "]", ",", "log", ...
Compiles the model with poptorch.
[ "Compiles", "the", "model", "with", "poptorch", "." ]
[ "\"\"\"\n Compiles the model with poptorch.\n\n Args:\n model: The model to compile (already wrapped).\n sample_batch: The inputs to use the compilation, this will set the input shapes that the compiled model\n can accept.\n log: Whether to log that comp...
[ { "param": "self", "type": null }, { "param": "model", "type": "poptorch.PoplarExecutor" }, { "param": "sample_batch", "type": "Union[Dict[str, torch.Tensor], Tuple[torch.Tensor]]" }, { "param": "log", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": "poptorch.PoplarExecutor", "docstring": "The model ...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
create_optimizer_and_scheduler
null
def create_optimizer_and_scheduler(self, num_training_steps: int): """ Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subcla...
Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer` and/or :obj:`c...
Setup the optimizer and the learning rate scheduler. We provide a reasonable default that works well.
[ "Setup", "the", "optimizer", "and", "the", "learning", "rate", "scheduler", ".", "We", "provide", "a", "reasonable", "default", "that", "works", "well", "." ]
def create_optimizer_and_scheduler(self, num_training_steps: int): self.create_optimizer() self.create_scheduler(num_training_steps=num_training_steps, optimizer=self.optimizer)
[ "def", "create_optimizer_and_scheduler", "(", "self", ",", "num_training_steps", ":", "int", ")", ":", "self", ".", "create_optimizer", "(", ")", "self", ".", "create_scheduler", "(", "num_training_steps", "=", "num_training_steps", ",", "optimizer", "=", "self", ...
Setup the optimizer and the learning rate scheduler.
[ "Setup", "the", "optimizer", "and", "the", "learning", "rate", "scheduler", "." ]
[ "\"\"\"\n Setup the optimizer and the learning rate scheduler.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method (or :obj:`create_optimizer`\n ...
[ { "param": "self", "type": null }, { "param": "num_training_steps", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "num_training_steps", "type": "int", "docstring": null, "docst...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
create_optimizer
<not_specific>
def create_optimizer(self): """ Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass. """ if self....
Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
Setup the optimizer. We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
[ "Setup", "the", "optimizer", ".", "We", "provide", "a", "reasonable", "default", "that", "works", "well", ".", "If", "you", "want", "to", "use", "something", "else", "you", "can", "pass", "a", "tuple", "in", "the", "Trainer", "'", "s", "init", "through",...
def create_optimizer(self): if self.optimizer is None: decay_parameters = get_parameter_names(self.model, [nn.LayerNorm]) decay_parameters = [name for name in decay_parameters if "bias" not in name] optimizer_grouped_parameters = [ { "param...
[ "def", "create_optimizer", "(", "self", ")", ":", "if", "self", ".", "optimizer", "is", "None", ":", "decay_parameters", "=", "get_parameter_names", "(", "self", ".", "model", ",", "[", "nn", ".", "LayerNorm", "]", ")", "decay_parameters", "=", "[", "name"...
Setup the optimizer.
[ "Setup", "the", "optimizer", "." ]
[ "\"\"\"\n Setup the optimizer.\n\n We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the\n Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.\n \"\"\"", "# TODO: disabled max_grad_norm ...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
create_scheduler
<not_specific>
def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer = None): """ Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number ...
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument. Args: num_training_steps (int): The number of training steps to do.
Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or passed as an argument.
[ "Setup", "the", "scheduler", ".", "The", "optimizer", "of", "the", "trainer", "must", "have", "been", "set", "up", "either", "before", "this", "method", "is", "called", "or", "passed", "as", "an", "argument", "." ]
def create_scheduler(self, num_training_steps: int, optimizer: torch.optim.Optimizer = None): optimizer = self.optimizer if optimizer is None else optimizer if self.lr_scheduler is None: self.lr_scheduler = get_scheduler( self.args.lr_scheduler_type, optimizer...
[ "def", "create_scheduler", "(", "self", ",", "num_training_steps", ":", "int", ",", "optimizer", ":", "torch", ".", "optim", ".", "Optimizer", "=", "None", ")", ":", "optimizer", "=", "self", ".", "optimizer", "if", "optimizer", "is", "None", "else", "opti...
Setup the scheduler.
[ "Setup", "the", "scheduler", "." ]
[ "\"\"\"\n Setup the scheduler. The optimizer of the trainer must have been set up either before this method is called or\n passed as an argument.\n\n Args:\n num_training_steps (int): The number of training steps to do.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "num_training_steps", "type": "int" }, { "param": "optimizer", "type": "torch.optim.Optimizer" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "num_training_steps", "type": "int", "docstring": "The number of tra...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_wrap_model
PoplarExecutor
def _wrap_model(self, model: Union[PreTrainedModel, PoplarExecutor], training=True) -> PoplarExecutor: """ Wraps a model for poptorch, either for training or for inference. Args: model (`~transformers.modeling_utils.PreTrainedModel` or `PoplarExecutor`): the model to wrap ...
Wraps a model for poptorch, either for training or for inference. Args: model (`~transformers.modeling_utils.PreTrainedModel` or `PoplarExecutor`): the model to wrap training (`bool`, *optional*, defaults to `True`): whether to wrap the model for training or not. Retur...
Wraps a model for poptorch, either for training or for inference.
[ "Wraps", "a", "model", "for", "poptorch", "either", "for", "training", "or", "for", "inference", "." ]
def _wrap_model(self, model: Union[PreTrainedModel, PoplarExecutor], training=True) -> PoplarExecutor: wrapped = None if isinstance(model, PoplarExecutor): wrapped = model elif training: if self.training_model is None: self.training_model = poptorch.traini...
[ "def", "_wrap_model", "(", "self", ",", "model", ":", "Union", "[", "PreTrainedModel", ",", "PoplarExecutor", "]", ",", "training", "=", "True", ")", "->", "PoplarExecutor", ":", "wrapped", "=", "None", "if", "isinstance", "(", "model", ",", "PoplarExecutor"...
Wraps a model for poptorch, either for training or for inference.
[ "Wraps", "a", "model", "for", "poptorch", "either", "for", "training", "or", "for", "inference", "." ]
[ "\"\"\"\n Wraps a model for poptorch, either for training or for inference.\n\n Args:\n model (`~transformers.modeling_utils.PreTrainedModel` or `PoplarExecutor`): the model to wrap\n training (`bool`, *optional*, defaults to `True`): whether to wrap the model for training or not...
[ { "param": "self", "type": null }, { "param": "model", "type": "Union[PreTrainedModel, PoplarExecutor]" }, { "param": "training", "type": null } ]
{ "returns": [ { "docstring": "The wrapped model.", "docstring_tokens": [ "The", "wrapped", "model", "." ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_load_optimizer_and_scheduler
<not_specific>
def _load_optimizer_and_scheduler(self, checkpoint): """If optimizer and scheduler states exist, load them.""" if checkpoint is None: return if os.path.isfile(os.path.join(checkpoint, OPTIMIZER_NAME)) and os.path.isfile( os.path.join(checkpoint, SCHEDULER_NAME) )...
If optimizer and scheduler states exist, load them.
If optimizer and scheduler states exist, load them.
[ "If", "optimizer", "and", "scheduler", "states", "exist", "load", "them", "." ]
def _load_optimizer_and_scheduler(self, checkpoint): if checkpoint is None: return if os.path.isfile(os.path.join(checkpoint, OPTIMIZER_NAME)) and os.path.isfile( os.path.join(checkpoint, SCHEDULER_NAME) ): self.optimizer.load_state_dict(torch.load(os.path.joi...
[ "def", "_load_optimizer_and_scheduler", "(", "self", ",", "checkpoint", ")", ":", "if", "checkpoint", "is", "None", ":", "return", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "checkpoint", ",", "OPTIMIZER_NAME", ")", ...
If optimizer and scheduler states exist, load them.
[ "If", "optimizer", "and", "scheduler", "states", "exist", "load", "them", "." ]
[ "\"\"\"If optimizer and scheduler states exist, load them.\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "checkpoint", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "checkpoint", "type": null, "docstring": null, "docstring_toke...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_prepare_input
Union[torch.Tensor, Any]
def _prepare_input(self, data: Union[torch.Tensor, Any]) -> Union[torch.Tensor, Any]: """ Prepares one :obj:`data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors. """ if isinstance(data, dict): return type(data)(**{k: self._prepare_input...
Prepares one :obj:`data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
Prepares one :obj:`data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
[ "Prepares", "one", ":", "obj", ":", "`", "data", "`", "before", "feeding", "it", "to", "the", "model", "be", "it", "a", "tensor", "or", "a", "nested", "list", "/", "dictionary", "of", "tensors", "." ]
def _prepare_input(self, data: Union[torch.Tensor, Any]) -> Union[torch.Tensor, Any]: if isinstance(data, dict): return type(data)(**{k: self._prepare_input(v) for k, v in data.items()}) elif isinstance(data, (tuple, list)): return type(data)(self._prepare_input(v) for v in data)...
[ "def", "_prepare_input", "(", "self", ",", "data", ":", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", ")", "->", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "return", ...
Prepares one :obj:`data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.
[ "Prepares", "one", ":", "obj", ":", "`", "data", "`", "before", "feeding", "it", "to", "the", "model", "be", "it", "a", "tensor", "or", "a", "nested", "list", "/", "dictionary", "of", "tensors", "." ]
[ "\"\"\"\n Prepares one :obj:`data` before feeding it to the model, be it a tensor or a nested list/dictionary of tensors.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "data", "type": "Union[torch.Tensor, Any]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": "Union[torch.Tensor, Any]", "docstring": null, ...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
_prepare_inputs
Dict[str, Union[torch.Tensor, Any]]
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: """ Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state. """ inputs = self._prepare_i...
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state.
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state.
[ "Prepare", ":", "obj", ":", "`", "inputs", "`", "before", "feeding", "them", "to", "the", "model", "converting", "them", "to", "tensors", "if", "they", "are", "not", "already", "and", "handling", "potential", "state", "." ]
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: inputs = self._prepare_input(inputs) if self.args.past_index >= 0 and self._past is not None: inputs["mems"] = self._past return inputs
[ "def", "_prepare_inputs", "(", "self", ",", "inputs", ":", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", "]", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", "]", ":", ...
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and handling potential state.
[ "Prepare", ":", "obj", ":", "`", "inputs", "`", "before", "feeding", "them", "to", "the", "model", "converting", "them", "to", "tensors", "if", "they", "are", "not", "already", "and", "handling", "potential", "state", "." ]
[ "\"\"\"\n Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and\n handling potential state.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "inputs", "type": "Dict[str, Union[torch.Tensor, Any]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "inputs", "type": "Dict[str, Union[torch.Tensor, Any]]", "docstring"...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
training_step
torch.Tensor
def training_step( self, model: poptorch.PoplarExecutor, inputs: Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: """ Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): ...
Perform a training step on a batch of inputs. Subclass and override to inject custom behavior. Args: model (:obj:`nn.Module`): The model to train. inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`): The inputs and targets of the model. ...
Perform a training step on a batch of inputs. Subclass and override to inject custom behavior.
[ "Perform", "a", "training", "step", "on", "a", "batch", "of", "inputs", ".", "Subclass", "and", "override", "to", "inject", "custom", "behavior", "." ]
def training_step( self, model: poptorch.PoplarExecutor, inputs: Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: inputs = self._prepare_inputs(inputs) loss = self.compute_loss(model, inputs) loss = loss.mean() return loss
[ "def", "training_step", "(", "self", ",", "model", ":", "poptorch", ".", "PoplarExecutor", ",", "inputs", ":", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", "]", ")", "->", "torch", ".", "Tensor", ":", "inputs", "=",...
Perform a training step on a batch of inputs.
[ "Perform", "a", "training", "step", "on", "a", "batch", "of", "inputs", "." ]
[ "\"\"\"\n Perform a training step on a batch of inputs.\n\n Subclass and override to inject custom behavior.\n\n Args:\n model (:obj:`nn.Module`):\n The model to train.\n inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):\n The inputs and ta...
[ { "param": "self", "type": null }, { "param": "model", "type": "poptorch.PoplarExecutor" }, { "param": "inputs", "type": "Dict[str, Union[torch.Tensor, Any]]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": "poptorch.PoplarExecutor", "docstring": null, ...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
evaluate
Dict[str, float]
def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: """ Run evaluation and returns metrics. The calling script will be responsible for providing a method ...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init :obj:`compute_metrics` argument). You can also subclass and override this method to inject custom behavior. Ar...
Run evaluation and returns metrics. The calling script will be responsible for providing a method to compute metrics, as they are task-dependent (pass it to the init :obj:`compute_metrics` argument). You can also subclass and override this method to inject custom behavior.
[ "Run", "evaluation", "and", "returns", "metrics", ".", "The", "calling", "script", "will", "be", "responsible", "for", "providing", "a", "method", "to", "compute", "metrics", "as", "they", "are", "task", "-", "dependent", "(", "pass", "it", "to", "the", "i...
def evaluate( self, eval_dataset: Optional[Dataset] = None, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval", ) -> Dict[str, float]: self._memory_tracker.start() eval_dataloader = self.get_eval_dataloader(eval_dataset) start_time = time...
[ "def", "evaluate", "(", "self", ",", "eval_dataset", ":", "Optional", "[", "Dataset", "]", "=", "None", ",", "ignore_keys", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "metric_key_prefix", ":", "str", "=", "\"eval\"", ",", ")"...
Run evaluation and returns metrics.
[ "Run", "evaluation", "and", "returns", "metrics", "." ]
[ "\"\"\"\n Run evaluation and returns metrics.\n\n The calling script will be responsible for providing a method to compute metrics, as they are task-dependent\n (pass it to the init :obj:`compute_metrics` argument).\n\n You can also subclass and override this method to inject custom beha...
[ { "param": "self", "type": null }, { "param": "eval_dataset", "type": "Optional[Dataset]" }, { "param": "ignore_keys", "type": "Optional[List[str]]" }, { "param": "metric_key_prefix", "type": "str" } ]
{ "returns": [ { "docstring": "A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The\ndictionary also contains the epoch number which comes from the training state.", "docstring_tokens": [ "A", "dictionary", "containing", ...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
predict
PredictionOutput
def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: """ Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain label...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in :obj:`evaluate()`. Args: test_dataset (:obj:`Dataset`): ...
Run prediction and returns predictions and potential metrics. Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method will also return metrics, like in :obj:`evaluate()`.
[ "Run", "prediction", "and", "returns", "predictions", "and", "potential", "metrics", ".", "Depending", "on", "the", "dataset", "and", "your", "use", "case", "your", "test", "dataset", "may", "contain", "labels", ".", "In", "that", "case", "this", "method", "...
def predict( self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "test" ) -> PredictionOutput: self._memory_tracker.start() test_dataloader = self.get_test_dataloader(test_dataset) start_time = time.time() output = self.evaluation_lo...
[ "def", "predict", "(", "self", ",", "test_dataset", ":", "Dataset", ",", "ignore_keys", ":", "Optional", "[", "List", "[", "str", "]", "]", "=", "None", ",", "metric_key_prefix", ":", "str", "=", "\"test\"", ")", "->", "PredictionOutput", ":", "self", "....
Run prediction and returns predictions and potential metrics.
[ "Run", "prediction", "and", "returns", "predictions", "and", "potential", "metrics", "." ]
[ "\"\"\"\n Run prediction and returns predictions and potential metrics.\n\n Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method\n will also return metrics, like in :obj:`evaluate()`.\n\n Args:\n test_dataset (:obj:`Datase...
[ { "param": "self", "type": null }, { "param": "test_dataset", "type": "Dataset" }, { "param": "ignore_keys", "type": "Optional[List[str]]" }, { "param": "metric_key_prefix", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "test_dataset", "type": "Dataset", "docstring": null, "docstri...
8b08c1ad048ff63c4466569febdde5047cb869ee
huggingface/optimum-graphcore
optimum/graphcore/trainer.py
[ "Apache-2.0" ]
Python
floating_point_ops
<not_specific>
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): """ For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such...
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method. Args: ...
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass. If using another model, either implement such a method in the model or subclass and override this method.
[ "For", "models", "that", "inherit", "from", ":", "class", ":", "`", "~transformers", ".", "PreTrainedModel", "`", "uses", "that", "method", "to", "compute", "the", "number", "of", "floating", "point", "operations", "for", "every", "backward", "+", "forward", ...
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]): if hasattr(self.original_model, "floating_point_ops"): return self.original_model.floating_point_ops(inputs) else: return 0
[ "def", "floating_point_ops", "(", "self", ",", "inputs", ":", "Dict", "[", "str", ",", "Union", "[", "torch", ".", "Tensor", ",", "Any", "]", "]", ")", ":", "if", "hasattr", "(", "self", ".", "original_model", ",", "\"floating_point_ops\"", ")", ":", "...
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of floating point operations for every backward + forward pass.
[ "For", "models", "that", "inherit", "from", ":", "class", ":", "`", "~transformers", ".", "PreTrainedModel", "`", "uses", "that", "method", "to", "compute", "the", "number", "of", "floating", "point", "operations", "for", "every", "backward", "+", "forward", ...
[ "\"\"\"\n For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of\n floating point operations for every backward + forward pass. If using another model, either implement such a\n method in the model or subclass and override this method.\n\n...
[ { "param": "self", "type": null }, { "param": "inputs", "type": "Dict[str, Union[torch.Tensor, Any]]" } ]
{ "returns": [ { "docstring": ":obj:`int`: The number of floating-point operations.", "docstring_tokens": [ ":", "obj", ":", "`", "int", "`", ":", "The", "number", "of", "floating", "-", "point", ...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
_make_causal_mask
<not_specific>
def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): """Makes causal mask used for bi-directional self-attention. This differs from the original implementation by: - Making the mask creation simpler in terms of operations used - Changing the va...
Makes causal mask used for bi-directional self-attention. This differs from the original implementation by: - Making the mask creation simpler in terms of operations used - Changing the value for tokens to mask to something compatible with fp16 - Not expanding the final mask to [bsz, 1, tgt_...
Makes causal mask used for bi-directional self-attention. This differs from the original implementation by: Making the mask creation simpler in terms of operations used Changing the value for tokens to mask to something compatible with fp16 Not expanding the final mask to [bsz, 1, tgt_len, src_len]
[ "Makes", "causal", "mask", "used", "for", "bi", "-", "directional", "self", "-", "attention", ".", "This", "differs", "from", "the", "original", "implementation", "by", ":", "Making", "the", "mask", "creation", "simpler", "in", "terms", "of", "operations", "...
def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), -FLOAT16_LIMIT) mask = torch.triu(mask, diagonal=1) return mask[None, None, :, :]
[ "def", "_make_causal_mask", "(", "input_ids_shape", ":", "torch", ".", "Size", ",", "dtype", ":", "torch", ".", "dtype", ",", "past_key_values_length", ":", "int", "=", "0", ")", ":", "bsz", ",", "tgt_len", "=", "input_ids_shape", "mask", "=", "torch", "."...
Makes causal mask used for bi-directional self-attention.
[ "Makes", "causal", "mask", "used", "for", "bi", "-", "directional", "self", "-", "attention", "." ]
[ "\"\"\"Makes causal mask used for bi-directional self-attention.\n This differs from the original implementation by:\n - Making the mask creation simpler in terms of operations used\n - Changing the value for tokens to mask to something compatible with fp16\n - Not expanding the final mask t...
[ { "param": "input_ids_shape", "type": "torch.Size" }, { "param": "dtype", "type": "torch.dtype" }, { "param": "past_key_values_length", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "input_ids_shape", "type": "torch.Size", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dtype", "type": "torch.dtype", "docstring": null...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
forward
Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]
def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions:...
Input shape: Batch x Time x Channel
Input shape: Batch x Time x Channel
[ "Input", "shape", ":", "Batch", "x", "Time", "x", "Channel" ]
def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions:...
[ "def", "forward", "(", "self", ",", "hidden_states", ":", "torch", ".", "Tensor", ",", "key_value_states", ":", "Optional", "[", "torch", ".", "Tensor", "]", "=", "None", ",", "past_key_value", ":", "Optional", "[", "Tuple", "[", "torch", ".", "Tensor", ...
Input shape: Batch x Time x Channel
[ "Input", "shape", ":", "Batch", "x", "Time", "x", "Channel" ]
[ "\"\"\"Input shape: Batch x Time x Channel\"\"\"", "# if key_value_states are provided this layer is used as a cross-attention layer", "# for the decoder", "# get query proj", "# get key, value proj", "# reuse k,v, cross_attentions", "# cross_attentions", "# reuse k, v, self_attention", "# self_atte...
[ { "param": "self", "type": null }, { "param": "hidden_states", "type": "torch.Tensor" }, { "param": "key_value_states", "type": "Optional[torch.Tensor]" }, { "param": "past_key_value", "type": "Optional[Tuple[torch.Tensor]]" }, { "param": "attention_mask", "ty...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hidden_states", "type": "torch.Tensor", "docstring": null, "d...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
encoder_and_decoder_embeddings_computation
null
def encoder_and_decoder_embeddings_computation(self, use_shared_embedding: bool): """Sets the BartModel shared embedding layer to SharedEmbedding that combines the computation under one layer. Args: use_shared_embedding: whether to use SharedEmbedding or not. """ if use_sha...
Sets the BartModel shared embedding layer to SharedEmbedding that combines the computation under one layer. Args: use_shared_embedding: whether to use SharedEmbedding or not.
Sets the BartModel shared embedding layer to SharedEmbedding that combines the computation under one layer.
[ "Sets", "the", "BartModel", "shared", "embedding", "layer", "to", "SharedEmbedding", "that", "combines", "the", "computation", "under", "one", "layer", "." ]
def encoder_and_decoder_embeddings_computation(self, use_shared_embedding: bool): if use_shared_embedding: if isinstance(self.shared, SharedEmbedding): logger.warning("encoder and decoder embeddings computation is already shared") else: self.shared = Share...
[ "def", "encoder_and_decoder_embeddings_computation", "(", "self", ",", "use_shared_embedding", ":", "bool", ")", ":", "if", "use_shared_embedding", ":", "if", "isinstance", "(", "self", ".", "shared", ",", "SharedEmbedding", ")", ":", "logger", ".", "warning", "("...
Sets the BartModel shared embedding layer to SharedEmbedding that combines the computation under one layer.
[ "Sets", "the", "BartModel", "shared", "embedding", "layer", "to", "SharedEmbedding", "that", "combines", "the", "computation", "under", "one", "layer", "." ]
[ "\"\"\"Sets the BartModel shared embedding layer to SharedEmbedding that combines the computation under one layer.\n\n Args:\n use_shared_embedding: whether to use SharedEmbedding or not.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "use_shared_embedding", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "use_shared_embedding", "type": "bool", "docstring": "whether to use...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
change_bart_encoder_and_decoder_classes
null
def change_bart_encoder_and_decoder_classes(self, restore: bool): """Changes the encoder and decoder classes to update their forward pass so that they use our custom versions of _make_causal_mask and _expand_mask. Args: restore: whether to restore the encoder and decoder to their or...
Changes the encoder and decoder classes to update their forward pass so that they use our custom versions of _make_causal_mask and _expand_mask. Args: restore: whether to restore the encoder and decoder to their original version or not.
Changes the encoder and decoder classes to update their forward pass so that they use our custom versions of _make_causal_mask and _expand_mask.
[ "Changes", "the", "encoder", "and", "decoder", "classes", "to", "update", "their", "forward", "pass", "so", "that", "they", "use", "our", "custom", "versions", "of", "_make_causal_mask", "and", "_expand_mask", "." ]
def change_bart_encoder_and_decoder_classes(self, restore: bool): self.encoder.__class__ = BartEncoder if restore else _BartEncoderWithCustomExpandMask self.decoder.__class__ = BartDecoder if restore else _BartDecoderWithCustomMakeCausalAndExpandMask
[ "def", "change_bart_encoder_and_decoder_classes", "(", "self", ",", "restore", ":", "bool", ")", ":", "self", ".", "encoder", ".", "__class__", "=", "BartEncoder", "if", "restore", "else", "_BartEncoderWithCustomExpandMask", "self", ".", "decoder", ".", "__class__",...
Changes the encoder and decoder classes to update their forward pass so that they use our custom versions of _make_causal_mask and _expand_mask.
[ "Changes", "the", "encoder", "and", "decoder", "classes", "to", "update", "their", "forward", "pass", "so", "that", "they", "use", "our", "custom", "versions", "of", "_make_causal_mask", "and", "_expand_mask", "." ]
[ "\"\"\"Changes the encoder and decoder classes to update their forward pass so that they use our custom versions of\n _make_causal_mask and _expand_mask.\n\n Args:\n restore: whether to restore the encoder and decoder to their original version or not.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "restore", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "restore", "type": "bool", "docstring": "whether to restore the enco...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
change_bart_attention_class
null
def change_bart_attention_class(self, restore: bool): """Changes the attention layers to either use the original BartAttention forward or BartAttentionWithoutException forward. Args: restore: whether to restore the attention layers to their original version or not. """ ...
Changes the attention layers to either use the original BartAttention forward or BartAttentionWithoutException forward. Args: restore: whether to restore the attention layers to their original version or not.
Changes the attention layers to either use the original BartAttention forward or BartAttentionWithoutException forward.
[ "Changes", "the", "attention", "layers", "to", "either", "use", "the", "original", "BartAttention", "forward", "or", "BartAttentionWithoutException", "forward", "." ]
def change_bart_attention_class(self, restore: bool): new_cls = BartAttention if restore else _BartAttentionWithoutException for mod in self.modules(): if isinstance(mod, BartAttention): mod.__class__ = new_cls
[ "def", "change_bart_attention_class", "(", "self", ",", "restore", ":", "bool", ")", ":", "new_cls", "=", "BartAttention", "if", "restore", "else", "_BartAttentionWithoutException", "for", "mod", "in", "self", ".", "modules", "(", ")", ":", "if", "isinstance", ...
Changes the attention layers to either use the original BartAttention forward or BartAttentionWithoutException forward.
[ "Changes", "the", "attention", "layers", "to", "either", "use", "the", "original", "BartAttention", "forward", "or", "BartAttentionWithoutException", "forward", "." ]
[ "\"\"\"Changes the attention layers to either use the original BartAttention forward or\n BartAttentionWithoutException forward.\n\n Args:\n restore: whether to restore the attention layers to their original version or not.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "restore", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "restore", "type": "bool", "docstring": "whether to restore the atte...
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """ Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - (If enabled) Replaces the shared embedding with a SerializedEmbedding - Adds recomputation checkpoints Recommended usage: ``` model = Pipelined...
Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - (If enabled) Replaces the shared embedding with a SerializedEmbedding - Adds recomputation checkpoints Recommended usage: ``` model = PipelinedBartForConditionalGeneration(confi...
Transform the model to run in an IPU pipeline. Adds pipeline stages to the model (If enabled) Replaces the shared embedding with a SerializedEmbedding Adds recomputation checkpoints
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", ".", "Adds", "pipeline", "stages", "to", "the", "model", "(", "If", "enabled", ")", "Replaces", "the", "shared", "embedding", "with", "a", "SerializedEmbedding", "Adds", "recomputation", ...
def parallelize(self): super().parallelize() layer_ipu = get_layer_ipu(self.ipu_config.layers_per_ipu) logger.info("-------------------- Device Allocation --------------------") logger.info("Embedding --> IPU 0") if self.ipu_config.embedding_serialization_factor > 1: ...
[ "def", "parallelize", "(", "self", ")", ":", "super", "(", ")", ".", "parallelize", "(", ")", "layer_ipu", "=", "get_layer_ipu", "(", "self", ".", "ipu_config", ".", "layers_per_ipu", ")", "logger", ".", "info", "(", "\"-------------------- Device Allocation ---...
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"\n Transform the model to run in an IPU pipeline.\n - Adds pipeline stages to the model\n - (If enabled) Replaces the shared embedding with a SerializedEmbedding\n - Adds recomputation checkpoints\n\n Recommended usage:\n ```\n model = PipelinedBartForConditio...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a27c0cda49b8444f091db78f9aae6c3acb7d6790
huggingface/optimum-graphcore
optimum/graphcore/models/bart/modeling_bart.py
[ "Apache-2.0" ]
Python
deparallelize
<not_specific>
def deparallelize(self): """ Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is fully compatible with `transformers.BartForConditionalGeneration`. """ super().deparallelize() s...
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is fully compatible with `transformers.BartForConditionalGeneration`.
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
def deparallelize(self): super().deparallelize() self.model.encoder_and_decoder_embeddings_computation(False) self.model.change_bart_encoder_and_decoder_classes(True) self.model.change_bart_attention_class(True) self.model.__class__ = BartModel return self
[ "def", "deparallelize", "(", "self", ")", ":", "super", "(", ")", ".", "deparallelize", "(", ")", "self", ".", "model", ".", "encoder_and_decoder_embeddings_computation", "(", "False", ")", "self", ".", "model", ".", "change_bart_encoder_and_decoder_classes", "(",...
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
[ "\"\"\"\n Undo the changes to the model done by `parallelize`.\n You should call this before doing `save_pretrained` so that the `model.state_dict` is\n fully compatible with `transformers.BartForConditionalGeneration`.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0e6202b4021473b5e4800d87a326adec934ff2d1
huggingface/optimum-graphcore
tests/test_examples.py
[ "Apache-2.0" ]
Python
_get_supported_models_for_script
List[Tuple[str]]
def _get_supported_models_for_script( models_to_test: Dict[str, Tuple[str]], task_mapping: Dict[str, str] ) -> List[Tuple[str]]: """ Filters models that can perform the task from models_to_test. Args: models_to_test: mapping between a model type and a tuple (model_name_or_path, ipu_config_name)...
Filters models that can perform the task from models_to_test. Args: models_to_test: mapping between a model type and a tuple (model_name_or_path, ipu_config_name). task_mapping: mapping bewteen a model config and a model class. Returns: A list of models that are supported for the ...
Filters models that can perform the task from models_to_test.
[ "Filters", "models", "that", "can", "perform", "the", "task", "from", "models_to_test", "." ]
def _get_supported_models_for_script( models_to_test: Dict[str, Tuple[str]], task_mapping: Dict[str, str] ) -> List[Tuple[str]]: def is_valid_model_type(model_type: str, model_class: Type) -> bool: in_task_mapping = CONFIG_MAPPING[model_type] in task_mapping if in_task_mapping: retur...
[ "def", "_get_supported_models_for_script", "(", "models_to_test", ":", "Dict", "[", "str", ",", "Tuple", "[", "str", "]", "]", ",", "task_mapping", ":", "Dict", "[", "str", ",", "str", "]", ")", "->", "List", "[", "Tuple", "[", "str", "]", "]", ":", ...
Filters models that can perform the task from models_to_test.
[ "Filters", "models", "that", "can", "perform", "the", "task", "from", "models_to_test", "." ]
[ "\"\"\"\n Filters models that can perform the task from models_to_test.\n\n Args:\n models_to_test: mapping between a model type and a tuple (model_name_or_path, ipu_config_name).\n task_mapping: mapping bewteen a model config and a model class.\n\n Returns:\n A list of models that are...
[ { "param": "models_to_test", "type": "Dict[str, Tuple[str]]" }, { "param": "task_mapping", "type": "Dict[str, str]" } ]
{ "returns": [ { "docstring": "A list of models that are supported for the task.\nEach element of the list follows the same format: (model_type, (model_name_or_path, ipu_config_name)).", "docstring_tokens": [ "A", "list", "of", "models", "that", "are", ...
0e6202b4021473b5e4800d87a326adec934ff2d1
huggingface/optimum-graphcore
tests/test_examples.py
[ "Apache-2.0" ]
Python
_install_requirements
<not_specific>
def _install_requirements(self, requirements_filename: Union[str, os.PathLike]): """ Installs the necessary requirements to run the example if the provided file exists, otherwise does nothing. """ if not Path(requirements_filename).exists(): return cmd_line = f"pip in...
Installs the necessary requirements to run the example if the provided file exists, otherwise does nothing.
Installs the necessary requirements to run the example if the provided file exists, otherwise does nothing.
[ "Installs", "the", "necessary", "requirements", "to", "run", "the", "example", "if", "the", "provided", "file", "exists", "otherwise", "does", "nothing", "." ]
def _install_requirements(self, requirements_filename: Union[str, os.PathLike]): if not Path(requirements_filename).exists(): return cmd_line = f"pip install -r {requirements_filename}".split() p = subprocess.Popen(cmd_line) return_code = p.wait() self.assertEqual(ret...
[ "def", "_install_requirements", "(", "self", ",", "requirements_filename", ":", "Union", "[", "str", ",", "os", ".", "PathLike", "]", ")", ":", "if", "not", "Path", "(", "requirements_filename", ")", ".", "exists", "(", ")", ":", "return", "cmd_line", "=",...
Installs the necessary requirements to run the example if the provided file exists, otherwise does nothing.
[ "Installs", "the", "necessary", "requirements", "to", "run", "the", "example", "if", "the", "provided", "file", "exists", "otherwise", "does", "nothing", "." ]
[ "\"\"\"\n Installs the necessary requirements to run the example if the provided file exists, otherwise does nothing.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "requirements_filename", "type": "Union[str, os.PathLike]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "requirements_filename", "type": "Union[str, os.PathLike]", "docstri...
0e6202b4021473b5e4800d87a326adec934ff2d1
huggingface/optimum-graphcore
tests/test_examples.py
[ "Apache-2.0" ]
Python
_cleanup_dataset_cache
null
def _cleanup_dataset_cache(self): """ Cleans up the dataset cache to free up space for other tests. """ cmd_line = ["rm" "-r", "/nethome/michaelb/.cache/huggingface/datasets"] p = subprocess.Popen(cmd_line) return_code = p.wait() self.assertEqual(return_code, 0)
Cleans up the dataset cache to free up space for other tests.
Cleans up the dataset cache to free up space for other tests.
[ "Cleans", "up", "the", "dataset", "cache", "to", "free", "up", "space", "for", "other", "tests", "." ]
def _cleanup_dataset_cache(self): cmd_line = ["rm" "-r", "/nethome/michaelb/.cache/huggingface/datasets"] p = subprocess.Popen(cmd_line) return_code = p.wait() self.assertEqual(return_code, 0)
[ "def", "_cleanup_dataset_cache", "(", "self", ")", ":", "cmd_line", "=", "[", "\"rm\"", "\"-r\"", ",", "\"/nethome/michaelb/.cache/huggingface/datasets\"", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd_line", ")", "return_code", "=", "p", ".", "wait", "("...
Cleans up the dataset cache to free up space for other tests.
[ "Cleans", "up", "the", "dataset", "cache", "to", "free", "up", "space", "for", "other", "tests", "." ]
[ "\"\"\"\n Cleans up the dataset cache to free up space for other tests.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
08dfdfa4ae8ab7f795f5a807fa1a5d5bee7d7275
huggingface/optimum-graphcore
optimum/graphcore/models/t5/modeling_t5.py
[ "Apache-2.0" ]
Python
parallelize
<not_specific>
def parallelize(self): """ Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - (If enabled) Replaces the shared embedding with a SerializedEmbedding - Adds recomputation checkpoints Recommended usage: ``` model = Pipelined...
Transform the model to run in an IPU pipeline. - Adds pipeline stages to the model - (If enabled) Replaces the shared embedding with a SerializedEmbedding - Adds recomputation checkpoints Recommended usage: ``` model = PipelinedT5ForConditionalGeneration(config)...
Transform the model to run in an IPU pipeline. Adds pipeline stages to the model (If enabled) Replaces the shared embedding with a SerializedEmbedding Adds recomputation checkpoints
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", ".", "Adds", "pipeline", "stages", "to", "the", "model", "(", "If", "enabled", ")", "Replaces", "the", "shared", "embedding", "with", "a", "SerializedEmbedding", "Adds", "recomputation", ...
def parallelize(self): layer_ipu = get_layer_ipu(self.ipu_config.layers_per_ipu) logger.info("-------------------- Device Allocation --------------------") logger.info("Embedding --> IPU 0") if self.ipu_config.embedding_serialization_factor > 1: serialized_lm_head = Serializ...
[ "def", "parallelize", "(", "self", ")", ":", "layer_ipu", "=", "get_layer_ipu", "(", "self", ".", "ipu_config", ".", "layers_per_ipu", ")", "logger", ".", "info", "(", "\"-------------------- Device Allocation --------------------\"", ")", "logger", ".", "info", "("...
Transform the model to run in an IPU pipeline.
[ "Transform", "the", "model", "to", "run", "in", "an", "IPU", "pipeline", "." ]
[ "\"\"\"\n Transform the model to run in an IPU pipeline.\n - Adds pipeline stages to the model\n - (If enabled) Replaces the shared embedding with a SerializedEmbedding\n - Adds recomputation checkpoints\n\n Recommended usage:\n ```\n model = PipelinedT5ForConditiona...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
08dfdfa4ae8ab7f795f5a807fa1a5d5bee7d7275
huggingface/optimum-graphcore
optimum/graphcore/models/t5/modeling_t5.py
[ "Apache-2.0" ]
Python
deparallelize
<not_specific>
def deparallelize(self): """ Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is fully compatible with `transformers.T5ForConditionalGeneration`. """ # T5ForConditionalGeneration has a ...
Undo the changes to the model done by `parallelize`. You should call this before doing `save_pretrained` so that the `model.state_dict` is fully compatible with `transformers.T5ForConditionalGeneration`.
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
def deparallelize(self): PipelineMixin.deparallelize(self) self.encoder_and_decoder_embeddings_computation(False) self.encoder.__class__ = T5Stack self.decoder.__class__ = T5Stack for mod in self.modules(): if isinstance(mod, T5LayerNorm): mod.forward ...
[ "def", "deparallelize", "(", "self", ")", ":", "PipelineMixin", ".", "deparallelize", "(", "self", ")", "self", ".", "encoder_and_decoder_embeddings_computation", "(", "False", ")", "self", ".", "encoder", ".", "__class__", "=", "T5Stack", "self", ".", "decoder"...
Undo the changes to the model done by `parallelize`.
[ "Undo", "the", "changes", "to", "the", "model", "done", "by", "`", "parallelize", "`", "." ]
[ "\"\"\"\n Undo the changes to the model done by `parallelize`.\n You should call this before doing `save_pretrained` so that the `model.state_dict` is\n fully compatible with `transformers.T5ForConditionalGeneration`.\n \"\"\"", "# T5ForConditionalGeneration has a deparallelize method,...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
bf7ae80659dd8e1d151463c6fef64e2a58e8c227
TheMartianObserver/borg
src/borg/helpers/misc.py
[ "BSD-3-Clause" ]
Python
chunkit
<not_specific>
def chunkit(it, size): """ Chunk an iterator <it> into pieces of <size>. >>> list(chunker('ABCDEFG', 3)) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']] """ iterable = iter(it) return iter(lambda: list(islice(iterable, size)), [])
Chunk an iterator <it> into pieces of <size>. >>> list(chunker('ABCDEFG', 3)) [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
Chunk an iterator into pieces of .
[ "Chunk", "an", "iterator", "into", "pieces", "of", "." ]
def chunkit(it, size): iterable = iter(it) return iter(lambda: list(islice(iterable, size)), [])
[ "def", "chunkit", "(", "it", ",", "size", ")", ":", "iterable", "=", "iter", "(", "it", ")", "return", "iter", "(", "lambda", ":", "list", "(", "islice", "(", "iterable", ",", "size", ")", ")", ",", "[", "]", ")" ]
Chunk an iterator <it> into pieces of <size>.
[ "Chunk", "an", "iterator", "<it", ">", "into", "pieces", "of", "<size", ">", "." ]
[ "\"\"\"\n Chunk an iterator <it> into pieces of <size>.\n\n >>> list(chunker('ABCDEFG', 3))\n [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]\n \"\"\"" ]
[ { "param": "it", "type": null }, { "param": "size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "it", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "size", "type": null, "docstring": null, "docstring_tokens": [],...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
parse_patternfile_line
<not_specific>
def parse_patternfile_line(line, roots, ie_commands, fallback): """Parse a pattern-file line and act depending on which command it represents.""" ie_command = parse_inclexcl_command(line, fallback=fallback) if ie_command.cmd is IECommand.RootPath: roots.append(ie_command.val) elif ie_command.cmd...
Parse a pattern-file line and act depending on which command it represents.
Parse a pattern-file line and act depending on which command it represents.
[ "Parse", "a", "pattern", "-", "file", "line", "and", "act", "depending", "on", "which", "command", "it", "represents", "." ]
def parse_patternfile_line(line, roots, ie_commands, fallback): ie_command = parse_inclexcl_command(line, fallback=fallback) if ie_command.cmd is IECommand.RootPath: roots.append(ie_command.val) elif ie_command.cmd is IECommand.PatternStyle: fallback = ie_command.val else: ie_com...
[ "def", "parse_patternfile_line", "(", "line", ",", "roots", ",", "ie_commands", ",", "fallback", ")", ":", "ie_command", "=", "parse_inclexcl_command", "(", "line", ",", "fallback", "=", "fallback", ")", "if", "ie_command", ".", "cmd", "is", "IECommand", ".", ...
Parse a pattern-file line and act depending on which command it represents.
[ "Parse", "a", "pattern", "-", "file", "line", "and", "act", "depending", "on", "which", "command", "it", "represents", "." ]
[ "\"\"\"Parse a pattern-file line and act depending on which command it represents.\"\"\"", "# it is some kind of include/exclude command" ]
[ { "param": "line", "type": null }, { "param": "roots", "type": null }, { "param": "ie_commands", "type": null }, { "param": "fallback", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "line", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "roots", "type": null, "docstring": null, "docstring_tokens": ...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
_add
null
def _add(self, pattern, cmd): """*cmd* is an IECommand value. """ if isinstance(pattern, PathFullPattern): key = pattern.pattern # full, normalized path self._path_full_patterns[key] = cmd else: self._items.append((pattern, cmd))
*cmd* is an IECommand value.
cmd* is an IECommand value.
[ "cmd", "*", "is", "an", "IECommand", "value", "." ]
def _add(self, pattern, cmd): if isinstance(pattern, PathFullPattern): key = pattern.pattern self._path_full_patterns[key] = cmd else: self._items.append((pattern, cmd))
[ "def", "_add", "(", "self", ",", "pattern", ",", "cmd", ")", ":", "if", "isinstance", "(", "pattern", ",", "PathFullPattern", ")", ":", "key", "=", "pattern", ".", "pattern", "self", ".", "_path_full_patterns", "[", "key", "]", "=", "cmd", "else", ":",...
cmd* is an IECommand value.
[ "cmd", "*", "is", "an", "IECommand", "value", "." ]
[ "\"\"\"*cmd* is an IECommand value.\n \"\"\"", "# full, normalized path" ]
[ { "param": "self", "type": null }, { "param": "pattern", "type": null }, { "param": "cmd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "pattern", "type": null, "docstring": null, "docstring_tokens"...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
add
null
def add(self, patterns, cmd): """Add list of patterns to internal list. *cmd* indicates whether the pattern is an include/exclude pattern, and whether recursion should be done on excluded folders. """ for pattern in patterns: self._add(pattern, cmd)
Add list of patterns to internal list. *cmd* indicates whether the pattern is an include/exclude pattern, and whether recursion should be done on excluded folders.
Add list of patterns to internal list. *cmd* indicates whether the pattern is an include/exclude pattern, and whether recursion should be done on excluded folders.
[ "Add", "list", "of", "patterns", "to", "internal", "list", ".", "*", "cmd", "*", "indicates", "whether", "the", "pattern", "is", "an", "include", "/", "exclude", "pattern", "and", "whether", "recursion", "should", "be", "done", "on", "excluded", "folders", ...
def add(self, patterns, cmd): for pattern in patterns: self._add(pattern, cmd)
[ "def", "add", "(", "self", ",", "patterns", ",", "cmd", ")", ":", "for", "pattern", "in", "patterns", ":", "self", ".", "_add", "(", "pattern", ",", "cmd", ")" ]
Add list of patterns to internal list.
[ "Add", "list", "of", "patterns", "to", "internal", "list", "." ]
[ "\"\"\"Add list of patterns to internal list. *cmd* indicates whether the\n pattern is an include/exclude pattern, and whether recursion should be\n done on excluded folders.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "patterns", "type": null }, { "param": "cmd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "patterns", "type": null, "docstring": null, "docstring_tokens...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
add_includepaths
null
def add_includepaths(self, include_paths): """Used to add inclusion-paths from args.paths (from commandline). """ include_patterns = [parse_pattern(p, PathPrefixPattern) for p in include_paths] self.add(include_patterns, IECommand.Include) self.fallback = not include_patterns ...
Used to add inclusion-paths from args.paths (from commandline).
Used to add inclusion-paths from args.paths (from commandline).
[ "Used", "to", "add", "inclusion", "-", "paths", "from", "args", ".", "paths", "(", "from", "commandline", ")", "." ]
def add_includepaths(self, include_paths): include_patterns = [parse_pattern(p, PathPrefixPattern) for p in include_paths] self.add(include_patterns, IECommand.Include) self.fallback = not include_patterns self.include_patterns = include_patterns
[ "def", "add_includepaths", "(", "self", ",", "include_paths", ")", ":", "include_patterns", "=", "[", "parse_pattern", "(", "p", ",", "PathPrefixPattern", ")", "for", "p", "in", "include_paths", "]", "self", ".", "add", "(", "include_patterns", ",", "IECommand...
Used to add inclusion-paths from args.paths (from commandline).
[ "Used", "to", "add", "inclusion", "-", "paths", "from", "args", ".", "paths", "(", "from", "commandline", ")", "." ]
[ "\"\"\"Used to add inclusion-paths from args.paths (from commandline).\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "include_paths", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "include_paths", "type": null, "docstring": null, "docstring_t...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
add_inclexcl
null
def add_inclexcl(self, patterns): """Add list of patterns (of type CmdTuple) to internal list. """ for pattern, cmd in patterns: self._add(pattern, cmd)
Add list of patterns (of type CmdTuple) to internal list.
Add list of patterns (of type CmdTuple) to internal list.
[ "Add", "list", "of", "patterns", "(", "of", "type", "CmdTuple", ")", "to", "internal", "list", "." ]
def add_inclexcl(self, patterns): for pattern, cmd in patterns: self._add(pattern, cmd)
[ "def", "add_inclexcl", "(", "self", ",", "patterns", ")", ":", "for", "pattern", ",", "cmd", "in", "patterns", ":", "self", ".", "_add", "(", "pattern", ",", "cmd", ")" ]
Add list of patterns (of type CmdTuple) to internal list.
[ "Add", "list", "of", "patterns", "(", "of", "type", "CmdTuple", ")", "to", "internal", "list", "." ]
[ "\"\"\"Add list of patterns (of type CmdTuple) to internal list.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "patterns", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "patterns", "type": null, "docstring": null, "docstring_tokens...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
match
<not_specific>
def match(self, path): """Return True or False depending on whether *path* is matched. If no match is found among the patterns in this matcher, then the value in self.fallback is returned (defaults to None). """ path = normalize_path(path).lstrip(os.path.sep) # do a fas...
Return True or False depending on whether *path* is matched. If no match is found among the patterns in this matcher, then the value in self.fallback is returned (defaults to None).
Return True or False depending on whether *path* is matched. If no match is found among the patterns in this matcher, then the value in self.fallback is returned (defaults to None).
[ "Return", "True", "or", "False", "depending", "on", "whether", "*", "path", "*", "is", "matched", ".", "If", "no", "match", "is", "found", "among", "the", "patterns", "in", "this", "matcher", "then", "the", "value", "in", "self", ".", "fallback", "is", ...
def match(self, path): path = normalize_path(path).lstrip(os.path.sep) non_existent = object() value = self._path_full_patterns.get(path, non_existent) if value is not non_existent: self.recurse_dir = command_recurses_dir(value) return self.is_include_cmd[value] ...
[ "def", "match", "(", "self", ",", "path", ")", ":", "path", "=", "normalize_path", "(", "path", ")", ".", "lstrip", "(", "os", ".", "path", ".", "sep", ")", "non_existent", "=", "object", "(", ")", "value", "=", "self", ".", "_path_full_patterns", "....
Return True or False depending on whether *path* is matched.
[ "Return", "True", "or", "False", "depending", "on", "whether", "*", "path", "*", "is", "matched", "." ]
[ "\"\"\"Return True or False depending on whether *path* is matched.\n\n If no match is found among the patterns in this matcher, then the value\n in self.fallback is returned (defaults to None).\n\n \"\"\"", "# do a fast lookup for full path matches (note: we do not count such matches):", "...
[ { "param": "self", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
match
<not_specific>
def match(self, path, normalize=True): """Return a boolean indicating whether *path* is matched by this pattern. If normalize is True (default), the path will get normalized using normalize_path(), otherwise it is assumed that it already is normalized using that function. """ if...
Return a boolean indicating whether *path* is matched by this pattern. If normalize is True (default), the path will get normalized using normalize_path(), otherwise it is assumed that it already is normalized using that function.
Return a boolean indicating whether *path* is matched by this pattern. If normalize is True (default), the path will get normalized using normalize_path(), otherwise it is assumed that it already is normalized using that function.
[ "Return", "a", "boolean", "indicating", "whether", "*", "path", "*", "is", "matched", "by", "this", "pattern", ".", "If", "normalize", "is", "True", "(", "default", ")", "the", "path", "will", "get", "normalized", "using", "normalize_path", "()", "otherwise"...
def match(self, path, normalize=True): if normalize: path = normalize_path(path) matches = self._match(path) if matches: self.match_count += 1 return matches
[ "def", "match", "(", "self", ",", "path", ",", "normalize", "=", "True", ")", ":", "if", "normalize", ":", "path", "=", "normalize_path", "(", "path", ")", "matches", "=", "self", ".", "_match", "(", "path", ")", "if", "matches", ":", "self", ".", ...
Return a boolean indicating whether *path* is matched by this pattern.
[ "Return", "a", "boolean", "indicating", "whether", "*", "path", "*", "is", "matched", "by", "this", "pattern", "." ]
[ "\"\"\"Return a boolean indicating whether *path* is matched by this pattern.\n\n If normalize is True (default), the path will get normalized using normalize_path(),\n otherwise it is assumed that it already is normalized using that function.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "path", "type": null }, { "param": "normalize", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
parse_pattern
<not_specific>
def parse_pattern(pattern, fallback=FnmatchPattern, recurse_dir=True): """Read pattern from string and return an instance of the appropriate implementation class. """ if len(pattern) > 2 and pattern[2] == ":" and pattern[:2].isalnum(): (style, pattern) = (pattern[:2], pattern[3:]) cls = get...
Read pattern from string and return an instance of the appropriate implementation class.
Read pattern from string and return an instance of the appropriate implementation class.
[ "Read", "pattern", "from", "string", "and", "return", "an", "instance", "of", "the", "appropriate", "implementation", "class", "." ]
def parse_pattern(pattern, fallback=FnmatchPattern, recurse_dir=True): if len(pattern) > 2 and pattern[2] == ":" and pattern[:2].isalnum(): (style, pattern) = (pattern[:2], pattern[3:]) cls = get_pattern_class(style) else: cls = fallback return cls(pattern, recurse_dir)
[ "def", "parse_pattern", "(", "pattern", ",", "fallback", "=", "FnmatchPattern", ",", "recurse_dir", "=", "True", ")", ":", "if", "len", "(", "pattern", ")", ">", "2", "and", "pattern", "[", "2", "]", "==", "\":\"", "and", "pattern", "[", ":", "2", "]...
Read pattern from string and return an instance of the appropriate implementation class.
[ "Read", "pattern", "from", "string", "and", "return", "an", "instance", "of", "the", "appropriate", "implementation", "class", "." ]
[ "\"\"\"Read pattern from string and return an instance of the appropriate implementation class.\n\n \"\"\"" ]
[ { "param": "pattern", "type": null }, { "param": "fallback", "type": null }, { "param": "recurse_dir", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pattern", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fallback", "type": null, "docstring": null, "docstring_tok...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
parse_exclude_pattern
<not_specific>
def parse_exclude_pattern(pattern_str, fallback=FnmatchPattern): """Read pattern from string and return an instance of the appropriate implementation class. """ epattern_obj = parse_pattern(pattern_str, fallback, recurse_dir=False) return CmdTuple(epattern_obj, IECommand.ExcludeNoRecurse)
Read pattern from string and return an instance of the appropriate implementation class.
Read pattern from string and return an instance of the appropriate implementation class.
[ "Read", "pattern", "from", "string", "and", "return", "an", "instance", "of", "the", "appropriate", "implementation", "class", "." ]
def parse_exclude_pattern(pattern_str, fallback=FnmatchPattern): epattern_obj = parse_pattern(pattern_str, fallback, recurse_dir=False) return CmdTuple(epattern_obj, IECommand.ExcludeNoRecurse)
[ "def", "parse_exclude_pattern", "(", "pattern_str", ",", "fallback", "=", "FnmatchPattern", ")", ":", "epattern_obj", "=", "parse_pattern", "(", "pattern_str", ",", "fallback", ",", "recurse_dir", "=", "False", ")", "return", "CmdTuple", "(", "epattern_obj", ",", ...
Read pattern from string and return an instance of the appropriate implementation class.
[ "Read", "pattern", "from", "string", "and", "return", "an", "instance", "of", "the", "appropriate", "implementation", "class", "." ]
[ "\"\"\"Read pattern from string and return an instance of the appropriate implementation class.\n \"\"\"" ]
[ { "param": "pattern_str", "type": null }, { "param": "fallback", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "pattern_str", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fallback", "type": null, "docstring": null, "docstring...
a3e34d40168c444d4302ca6367da5b7fd8d4fee8
TheMartianObserver/borg
src/borg/patterns.py
[ "BSD-3-Clause" ]
Python
parse_inclexcl_command
<not_specific>
def parse_inclexcl_command(cmd_line_str, fallback=ShellPattern): """Read a --patterns-from command from string and return a CmdTuple object.""" cmd_prefix_map = { '-': IECommand.Exclude, '!': IECommand.ExcludeNoRecurse, '+': IECommand.Include, 'R': IECommand.RootPath, 'r...
Read a --patterns-from command from string and return a CmdTuple object.
Read a --patterns-from command from string and return a CmdTuple object.
[ "Read", "a", "--", "patterns", "-", "from", "command", "from", "string", "and", "return", "a", "CmdTuple", "object", "." ]
def parse_inclexcl_command(cmd_line_str, fallback=ShellPattern): cmd_prefix_map = { '-': IECommand.Exclude, '!': IECommand.ExcludeNoRecurse, '+': IECommand.Include, 'R': IECommand.RootPath, 'r': IECommand.RootPath, 'P': IECommand.PatternStyle, 'p': IECommand.P...
[ "def", "parse_inclexcl_command", "(", "cmd_line_str", ",", "fallback", "=", "ShellPattern", ")", ":", "cmd_prefix_map", "=", "{", "'-'", ":", "IECommand", ".", "Exclude", ",", "'!'", ":", "IECommand", ".", "ExcludeNoRecurse", ",", "'+'", ":", "IECommand", ".",...
Read a --patterns-from command from string and return a CmdTuple object.
[ "Read", "a", "--", "patterns", "-", "from", "command", "from", "string", "and", "return", "a", "CmdTuple", "object", "." ]
[ "\"\"\"Read a --patterns-from command from string and return a CmdTuple object.\"\"\"", "# remaining text on command-line following the command character", "# TODO: validate string?", "# then remainder_str is something like 're' or 'sh'", "# determine recurse_dir based on command type" ]
[ { "param": "cmd_line_str", "type": null }, { "param": "fallback", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cmd_line_str", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fallback", "type": null, "docstring": null, "docstrin...