Search is not available for this dataset
identifier
stringlengths 1
155
| parameters
stringlengths 2
6.09k
| docstring
stringlengths 11
63.4k
| docstring_summary
stringlengths 0
63.4k
| function
stringlengths 29
99.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ParserElement.searchString | ( self, instring, maxMatches=_MAX_INT ) |
Another extension to C{L{scanString}}, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
C{maxMatches} argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
prints::
['More', 'Iron', 'Lead', 'Gold', 'I']
|
Another extension to C{L{scanString}}, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
C{maxMatches} argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
prints::
['More', 'Iron', 'Lead', 'Gold', 'I']
| def searchString( self, instring, maxMatches=_MAX_INT ):
"""
Another extension to C{L{scanString}}, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
C{maxMatches} argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
prints::
['More', 'Iron', 'Lead', 'Gold', 'I']
"""
try:
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"try",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
")",
"]",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace\r",
"raise",
"exc"
] | [
1734,
4
] | [
1755,
25
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.split | (self, instring, maxsplit=_MAX_INT, includeSeparators=False) |
Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
|
Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
| def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
"""
Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
"""
splits = 0
last = 0
for t,s,e in self.scanString(instring, maxMatches=maxsplit):
yield instring[last:s]
if includeSeparators:
yield t[0]
last = e
yield instring[last:] | [
"def",
"split",
"(",
"self",
",",
"instring",
",",
"maxsplit",
"=",
"_MAX_INT",
",",
"includeSeparators",
"=",
"False",
")",
":",
"splits",
"=",
"0",
"last",
"=",
"0",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",
"=",
"maxsplit",
")",
":",
"yield",
"instring",
"[",
"last",
":",
"s",
"]",
"if",
"includeSeparators",
":",
"yield",
"t",
"[",
"0",
"]",
"last",
"=",
"e",
"yield",
"instring",
"[",
"last",
":",
"]"
] | [
1757,
4
] | [
1777,
29
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__add__ | (self, other ) |
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
converts them to L{Literal}s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
Prints::
Hello, World! -> ['Hello', ',', 'World', '!']
|
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
converts them to L{Literal}s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
Prints::
Hello, World! -> ['Hello', ',', 'World', '!']
| def __add__(self, other ):
"""
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
converts them to L{Literal}s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
Prints::
Hello, World! -> ['Hello', ',', 'World', '!']
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, other ] ) | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"And",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
1779,
4
] | [
1797,
37
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__radd__ | (self, other ) |
Implementation of + operator when left operand is not a C{L{ParserElement}}
|
Implementation of + operator when left operand is not a C{L{ParserElement}}
| def __radd__(self, other ):
"""
Implementation of + operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other + self | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"+",
"self"
] | [
1799,
4
] | [
1809,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__sub__ | (self, other) |
Implementation of - operator, returns C{L{And}} with error stop
|
Implementation of - operator, returns C{L{And}} with error stop
| def __sub__(self, other):
"""
Implementation of - operator, returns C{L{And}} with error stop
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, And._ErrorStop(), other ] ) | [
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"And",
"(",
"[",
"self",
",",
"And",
".",
"_ErrorStop",
"(",
")",
",",
"other",
"]",
")"
] | [
1811,
4
] | [
1821,
55
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__rsub__ | (self, other ) |
Implementation of - operator when left operand is not a C{L{ParserElement}}
|
Implementation of - operator when left operand is not a C{L{ParserElement}}
| def __rsub__(self, other ):
"""
Implementation of - operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other - self | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"-",
"self"
] | [
1823,
4
] | [
1833,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__mul__ | (self,other) |
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
|
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
| def __mul__(self,other):
"""
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
"""
if isinstance(other,int):
minElements, optElements = other,0
elif isinstance(other,tuple):
other = (other + (None, None))[:2]
if other[0] is None:
other = (0, other[1])
if isinstance(other[0],int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self*other[0] + ZeroOrMore(self)
elif isinstance(other[0],int) and isinstance(other[1],int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
if (optElements):
def makeOptionalList(n):
if n>1:
return Optional(self + makeOptionalList(n-1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self]*minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self]*minElements)
return ret | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
",",
"0",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
":",
"other",
"=",
"(",
"other",
"+",
"(",
"None",
",",
"None",
")",
")",
"[",
":",
"2",
"]",
"if",
"other",
"[",
"0",
"]",
"is",
"None",
":",
"other",
"=",
"(",
"0",
",",
"other",
"[",
"1",
"]",
")",
"if",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"other",
"[",
"1",
"]",
"is",
"None",
":",
"if",
"other",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"ZeroOrMore",
"(",
"self",
")",
"if",
"other",
"[",
"0",
"]",
"==",
"1",
":",
"return",
"OneOrMore",
"(",
"self",
")",
"else",
":",
"return",
"self",
"*",
"other",
"[",
"0",
"]",
"+",
"ZeroOrMore",
"(",
"self",
")",
"elif",
"isinstance",
"(",
"other",
"[",
"0",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"other",
"[",
"1",
"]",
",",
"int",
")",
":",
"minElements",
",",
"optElements",
"=",
"other",
"optElements",
"-=",
"minElements",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and ('%s','%s') objects\"",
",",
"type",
"(",
"other",
"[",
"0",
"]",
")",
",",
"type",
"(",
"other",
"[",
"1",
"]",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"cannot multiply 'ParserElement' and '%s' objects\"",
",",
"type",
"(",
"other",
")",
")",
"if",
"minElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by negative value\"",
")",
"if",
"optElements",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"second tuple value must be greater or equal to first tuple value\"",
")",
"if",
"minElements",
"==",
"optElements",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot multiply ParserElement by 0 or (0,0)\"",
")",
"if",
"(",
"optElements",
")",
":",
"def",
"makeOptionalList",
"(",
"n",
")",
":",
"if",
"n",
">",
"1",
":",
"return",
"Optional",
"(",
"self",
"+",
"makeOptionalList",
"(",
"n",
"-",
"1",
")",
")",
"else",
":",
"return",
"Optional",
"(",
"self",
")",
"if",
"minElements",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"+",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"ret",
"=",
"makeOptionalList",
"(",
"optElements",
")",
"else",
":",
"if",
"minElements",
"==",
"1",
":",
"ret",
"=",
"self",
"else",
":",
"ret",
"=",
"And",
"(",
"[",
"self",
"]",
"*",
"minElements",
")",
"return",
"ret"
] | [
1835,
4
] | [
1901,
18
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__or__ | (self, other ) |
Implementation of | operator - returns C{L{MatchFirst}}
|
Implementation of | operator - returns C{L{MatchFirst}}
| def __or__(self, other ):
"""
Implementation of | operator - returns C{L{MatchFirst}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return MatchFirst( [ self, other ] ) | [
"def",
"__or__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"MatchFirst",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
1906,
4
] | [
1916,
44
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__ror__ | (self, other ) |
Implementation of | operator when left operand is not a C{L{ParserElement}}
|
Implementation of | operator when left operand is not a C{L{ParserElement}}
| def __ror__(self, other ):
"""
Implementation of | operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other | self | [
"def",
"__ror__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"|",
"self"
] | [
1918,
4
] | [
1928,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__xor__ | (self, other ) |
Implementation of ^ operator - returns C{L{Or}}
|
Implementation of ^ operator - returns C{L{Or}}
| def __xor__(self, other ):
"""
Implementation of ^ operator - returns C{L{Or}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Or( [ self, other ] ) | [
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"Or",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
1930,
4
] | [
1940,
36
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__rxor__ | (self, other ) |
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
|
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
| def __rxor__(self, other ):
"""
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other ^ self | [
"def",
"__rxor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"^",
"self"
] | [
1942,
4
] | [
1952,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__and__ | (self, other ) |
Implementation of & operator - returns C{L{Each}}
|
Implementation of & operator - returns C{L{Each}}
| def __and__(self, other ):
"""
Implementation of & operator - returns C{L{Each}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Each( [ self, other ] ) | [
"def",
"__and__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"Each",
"(",
"[",
"self",
",",
"other",
"]",
")"
] | [
1954,
4
] | [
1964,
38
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__rand__ | (self, other ) |
Implementation of & operator when left operand is not a C{L{ParserElement}}
|
Implementation of & operator when left operand is not a C{L{ParserElement}}
| def __rand__(self, other ):
"""
Implementation of & operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"ParserElement",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Cannot combine element of type %s with ParserElement\"",
"%",
"type",
"(",
"other",
")",
",",
"SyntaxWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"None",
"return",
"other",
"&",
"self"
] | [
1966,
4
] | [
1976,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__invert__ | ( self ) |
Implementation of ~ operator - returns C{L{NotAny}}
|
Implementation of ~ operator - returns C{L{NotAny}}
| def __invert__( self ):
"""
Implementation of ~ operator - returns C{L{NotAny}}
"""
return NotAny( self ) | [
"def",
"__invert__",
"(",
"self",
")",
":",
"return",
"NotAny",
"(",
"self",
")"
] | [
1978,
4
] | [
1982,
29
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.__call__ | (self, name=None) |
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
|
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
| def __call__(self, name=None):
"""
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
"""
if name is not None:
return self.setResultsName(name)
else:
return self.copy() | [
"def",
"__call__",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"setResultsName",
"(",
"name",
")",
"else",
":",
"return",
"self",
".",
"copy",
"(",
")"
] | [
1984,
4
] | [
2001,
30
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.suppress | ( self ) |
Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output.
|
Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output.
| def suppress( self ):
"""
Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress( self ) | [
"def",
"suppress",
"(",
"self",
")",
":",
"return",
"Suppress",
"(",
"self",
")"
] | [
2003,
4
] | [
2008,
31
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.leaveWhitespace | ( self ) |
Disables the skipping of whitespace before matching the characters in the
C{ParserElement}'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
|
Disables the skipping of whitespace before matching the characters in the
C{ParserElement}'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
| def leaveWhitespace( self ):
"""
Disables the skipping of whitespace before matching the characters in the
C{ParserElement}'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
self.skipWhitespace = False
return self | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"return",
"self"
] | [
2010,
4
] | [
2017,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setWhitespaceChars | ( self, chars ) |
Overrides the default whitespace chars
|
Overrides the default whitespace chars
| def setWhitespaceChars( self, chars ):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self | [
"def",
"setWhitespaceChars",
"(",
"self",
",",
"chars",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"True",
"self",
".",
"whiteChars",
"=",
"chars",
"self",
".",
"copyDefaultWhiteChars",
"=",
"False",
"return",
"self"
] | [
2019,
4
] | [
2026,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.parseWithTabs | ( self ) |
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
|
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
| def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | [
2028,
4
] | [
2035,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.ignore | ( self, other ) |
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
|
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
| def ignore( self, other ):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
"""
if isinstance(other, basestring):
other = Suppress(other)
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
self.ignoreExprs.append(other)
else:
self.ignoreExprs.append( Suppress( other.copy() ) )
return self | [
"def",
"ignore",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"Suppress",
"(",
"other",
")",
"if",
"isinstance",
"(",
"other",
",",
"Suppress",
")",
":",
"if",
"other",
"not",
"in",
"self",
".",
"ignoreExprs",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"other",
")",
"else",
":",
"self",
".",
"ignoreExprs",
".",
"append",
"(",
"Suppress",
"(",
"other",
".",
"copy",
"(",
")",
")",
")",
"return",
"self"
] | [
2037,
4
] | [
2058,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setDebugActions | ( self, startAction, successAction, exceptionAction ) |
Enable display of debugging messages while doing pattern matching.
|
Enable display of debugging messages while doing pattern matching.
| def setDebugActions( self, startAction, successAction, exceptionAction ):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self | [
"def",
"setDebugActions",
"(",
"self",
",",
"startAction",
",",
"successAction",
",",
"exceptionAction",
")",
":",
"self",
".",
"debugActions",
"=",
"(",
"startAction",
"or",
"_defaultStartDebugAction",
",",
"successAction",
"or",
"_defaultSuccessDebugAction",
",",
"exceptionAction",
"or",
"_defaultExceptionDebugAction",
")",
"self",
".",
"debug",
"=",
"True",
"return",
"self"
] | [
2060,
4
] | [
2068,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setDebug | ( self, flag=True ) |
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
|
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
| def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug",
"=",
"False",
"return",
"self"
] | [
2070,
4
] | [
2109,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.validate | ( self, validateTrace=[] ) |
Check defined expressions for valid structure, check for infinite recursive definitions.
|
Check defined expressions for valid structure, check for infinite recursive definitions.
| def validate( self, validateTrace=[] ):
"""
Check defined expressions for valid structure, check for infinite recursive definitions.
"""
self.checkRecursion( [] ) | [
"def",
"validate",
"(",
"self",
",",
"validateTrace",
"=",
"[",
"]",
")",
":",
"self",
".",
"checkRecursion",
"(",
"[",
"]",
")"
] | [
2125,
4
] | [
2129,
33
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.parseFile | ( self, file_or_filename, parseAll=False ) |
Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
|
Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
| def parseFile( self, file_or_filename, parseAll=False ):
"""
Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
"""
try:
file_contents = file_or_filename.read()
except AttributeError:
with open(file_or_filename, "r") as f:
file_contents = f.read()
try:
return self.parseString(file_contents, parseAll)
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc | [
"def",
"parseFile",
"(",
"self",
",",
"file_or_filename",
",",
"parseAll",
"=",
"False",
")",
":",
"try",
":",
"file_contents",
"=",
"file_or_filename",
".",
"read",
"(",
")",
"except",
"AttributeError",
":",
"with",
"open",
"(",
"file_or_filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"file_contents",
"=",
"f",
".",
"read",
"(",
")",
"try",
":",
"return",
"self",
".",
"parseString",
"(",
"file_contents",
",",
"parseAll",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace\r",
"raise",
"exc"
] | [
2131,
4
] | [
2149,
25
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.matches | (self, testString, parseAll=True) |
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
|
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
| def matches(self, testString, parseAll=True):
"""
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
"""
try:
self.parseString(_ustr(testString), parseAll=parseAll)
return True
except ParseBaseException:
return False | [
"def",
"matches",
"(",
"self",
",",
"testString",
",",
"parseAll",
"=",
"True",
")",
":",
"try",
":",
"self",
".",
"parseString",
"(",
"_ustr",
"(",
"testString",
")",
",",
"parseAll",
"=",
"parseAll",
")",
"return",
"True",
"except",
"ParseBaseException",
":",
"return",
"False"
] | [
2171,
4
] | [
2188,
24
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.runTests | (self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False) |
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.)
|
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.)
| def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False):
"""
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.)
"""
if isinstance(tests, basestring):
tests = list(map(str.strip, tests.rstrip().splitlines()))
if isinstance(comment, basestring):
comment = Literal(comment)
allResults = []
comments = []
success = True
for t in tests:
if comment is not None and comment.matches(t, False) or comments and not t:
comments.append(t)
continue
if not t:
continue
out = ['\n'.join(comments), t]
comments = []
try:
t = t.replace(r'\n','\n')
result = self.parseString(t, parseAll=parseAll)
out.append(result.dump(full=fullDump))
success = success and not failureTests
except ParseBaseException as pe:
fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
if '\n' in t:
out.append(line(pe.loc, t))
out.append(' '*(col(pe.loc,t)-1) + '^' + fatal)
else:
out.append(' '*pe.loc + '^' + fatal)
out.append("FAIL: " + str(pe))
success = success and failureTests
result = pe
except Exception as exc:
out.append("FAIL-EXCEPTION: " + str(exc))
success = success and failureTests
result = exc
if printResults:
if fullDump:
out.append('')
print('\n'.join(out))
allResults.append((t, result))
return success, allResults | [
"def",
"runTests",
"(",
"self",
",",
"tests",
",",
"parseAll",
"=",
"True",
",",
"comment",
"=",
"'#'",
",",
"fullDump",
"=",
"True",
",",
"printResults",
"=",
"True",
",",
"failureTests",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"tests",
",",
"basestring",
")",
":",
"tests",
"=",
"list",
"(",
"map",
"(",
"str",
".",
"strip",
",",
"tests",
".",
"rstrip",
"(",
")",
".",
"splitlines",
"(",
")",
")",
")",
"if",
"isinstance",
"(",
"comment",
",",
"basestring",
")",
":",
"comment",
"=",
"Literal",
"(",
"comment",
")",
"allResults",
"=",
"[",
"]",
"comments",
"=",
"[",
"]",
"success",
"=",
"True",
"for",
"t",
"in",
"tests",
":",
"if",
"comment",
"is",
"not",
"None",
"and",
"comment",
".",
"matches",
"(",
"t",
",",
"False",
")",
"or",
"comments",
"and",
"not",
"t",
":",
"comments",
".",
"append",
"(",
"t",
")",
"continue",
"if",
"not",
"t",
":",
"continue",
"out",
"=",
"[",
"'\\n'",
".",
"join",
"(",
"comments",
")",
",",
"t",
"]",
"comments",
"=",
"[",
"]",
"try",
":",
"t",
"=",
"t",
".",
"replace",
"(",
"r'\\n'",
",",
"'\\n'",
")",
"result",
"=",
"self",
".",
"parseString",
"(",
"t",
",",
"parseAll",
"=",
"parseAll",
")",
"out",
".",
"append",
"(",
"result",
".",
"dump",
"(",
"full",
"=",
"fullDump",
")",
")",
"success",
"=",
"success",
"and",
"not",
"failureTests",
"except",
"ParseBaseException",
"as",
"pe",
":",
"fatal",
"=",
"\"(FATAL)\"",
"if",
"isinstance",
"(",
"pe",
",",
"ParseFatalException",
")",
"else",
"\"\"",
"if",
"'\\n'",
"in",
"t",
":",
"out",
".",
"append",
"(",
"line",
"(",
"pe",
".",
"loc",
",",
"t",
")",
")",
"out",
".",
"append",
"(",
"' '",
"*",
"(",
"col",
"(",
"pe",
".",
"loc",
",",
"t",
")",
"-",
"1",
")",
"+",
"'^'",
"+",
"fatal",
")",
"else",
":",
"out",
".",
"append",
"(",
"' '",
"*",
"pe",
".",
"loc",
"+",
"'^'",
"+",
"fatal",
")",
"out",
".",
"append",
"(",
"\"FAIL: \"",
"+",
"str",
"(",
"pe",
")",
")",
"success",
"=",
"success",
"and",
"failureTests",
"result",
"=",
"pe",
"except",
"Exception",
"as",
"exc",
":",
"out",
".",
"append",
"(",
"\"FAIL-EXCEPTION: \"",
"+",
"str",
"(",
"exc",
")",
")",
"success",
"=",
"success",
"and",
"failureTests",
"result",
"=",
"exc",
"if",
"printResults",
":",
"if",
"fullDump",
":",
"out",
".",
"append",
"(",
"''",
")",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"out",
")",
")",
"allResults",
".",
"append",
"(",
"(",
"t",
",",
"result",
")",
")",
"return",
"success",
",",
"allResults"
] | [
2190,
4
] | [
2319,
34
] | python | en | ['en', 'ja', 'th'] | False |
ReadFile.__init__ | (self, input_file, sep='\t', header=None, names=None, as_binary=False, binary_col=2) |
ReadFile is responsible to read and process all input files in the Case Recommender
We used as default csv files with delimiter '\t'. e.g: user item score\n
:param input_file: Input File with at least 2 columns.
:type input_file: str
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param header: Skip header line (only work with method: read_with_pandas)
:type header: int, default None
:param names: Name of columns (only work with method: read_with_pandas)
:type names: str, default None
:param as_binary: If True, the explicit feedback will be transform to binary
:type as_binary: bool, default False
:param binary_col: Index of columns to read as binary (only work with method: read_with_pandas)
:type binary_col: int, default 2
|
ReadFile is responsible to read and process all input files in the Case Recommender | def __init__(self, input_file, sep='\t', header=None, names=None, as_binary=False, binary_col=2):
"""
ReadFile is responsible to read and process all input files in the Case Recommender
We used as default csv files with delimiter '\t'. e.g: user item score\n
:param input_file: Input File with at least 2 columns.
:type input_file: str
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param header: Skip header line (only work with method: read_with_pandas)
:type header: int, default None
:param names: Name of columns (only work with method: read_with_pandas)
:type names: str, default None
:param as_binary: If True, the explicit feedback will be transform to binary
:type as_binary: bool, default False
:param binary_col: Index of columns to read as binary (only work with method: read_with_pandas)
:type binary_col: int, default 2
"""
self.input_file = input_file
self.sep = sep
self.header = header
self.names = names
self.as_binary = as_binary
self.binary_col = binary_col
check_error_file(self.input_file) | [
"def",
"__init__",
"(",
"self",
",",
"input_file",
",",
"sep",
"=",
"'\\t'",
",",
"header",
"=",
"None",
",",
"names",
"=",
"None",
",",
"as_binary",
"=",
"False",
",",
"binary_col",
"=",
"2",
")",
":",
"self",
".",
"input_file",
"=",
"input_file",
"self",
".",
"sep",
"=",
"sep",
"self",
".",
"header",
"=",
"header",
"self",
".",
"names",
"=",
"names",
"self",
".",
"as_binary",
"=",
"as_binary",
"self",
".",
"binary_col",
"=",
"binary_col",
"check_error_file",
"(",
"self",
".",
"input_file",
")"
] | [
16,
4
] | [
49,
41
] | python | en | ['en', 'error', 'th'] | False |
ReadFile.read | (self) |
Method to read files and collect important information.
:return: Dictionary with file information
:rtype: dict
|
Method to read files and collect important information. | def read(self):
"""
Method to read files and collect important information.
:return: Dictionary with file information
:rtype: dict
"""
list_users = set()
list_items = set()
list_feedback = []
dict_feedback = {}
items_unobserved = {}
items_seen_by_user = {}
users_viewed_item = {}
mean_value = 0
number_interactions = 0
with open(self.input_file) as infile:
for line in infile:
if line.strip():
inline = line.split(self.sep)
if len(inline) == 1:
raise TypeError("Error: Space type (sep) is invalid!")
user, item, value = int(inline[0]), int(inline[1]), float(inline[2])
dict_feedback.setdefault(user, {}).update({item: 1.0 if self.as_binary else value})
items_seen_by_user.setdefault(user, set()).add(item)
users_viewed_item.setdefault(item, set()).add(user)
list_users.add(user)
list_items.add(item)
mean_value += 1.0 if self.as_binary else value
list_feedback.append(1.0 if self.as_binary else value)
number_interactions += 1
mean_value /= float(number_interactions)
list_users = sorted(list(list_users))
list_items = sorted(list(list_items))
# Create a dictionary with unobserved items for each user / Map user with its respective id
for user in list_users:
items_unobserved[user] = list(set(list_items) - set(items_seen_by_user[user]))
# Calculate the sparsity of the set: N / (nu * ni)
sparsity = (1 - (number_interactions / float(len(list_users) * len(list_items)))) * 100
dict_file = {
'feedback': dict_feedback,
'users': list_users,
'items': list_items,
'sparsity': sparsity,
'number_interactions': number_interactions,
'users_viewed_item': users_viewed_item,
'items_unobserved': items_unobserved,
'items_seen_by_user': items_seen_by_user,
'mean_value': mean_value,
'max_value': max(list_feedback),
'min_value': min(list_feedback),
}
return dict_file | [
"def",
"read",
"(",
"self",
")",
":",
"list_users",
"=",
"set",
"(",
")",
"list_items",
"=",
"set",
"(",
")",
"list_feedback",
"=",
"[",
"]",
"dict_feedback",
"=",
"{",
"}",
"items_unobserved",
"=",
"{",
"}",
"items_seen_by_user",
"=",
"{",
"}",
"users_viewed_item",
"=",
"{",
"}",
"mean_value",
"=",
"0",
"number_interactions",
"=",
"0",
"with",
"open",
"(",
"self",
".",
"input_file",
")",
"as",
"infile",
":",
"for",
"line",
"in",
"infile",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"inline",
"=",
"line",
".",
"split",
"(",
"self",
".",
"sep",
")",
"if",
"len",
"(",
"inline",
")",
"==",
"1",
":",
"raise",
"TypeError",
"(",
"\"Error: Space type (sep) is invalid!\"",
")",
"user",
",",
"item",
",",
"value",
"=",
"int",
"(",
"inline",
"[",
"0",
"]",
")",
",",
"int",
"(",
"inline",
"[",
"1",
"]",
")",
",",
"float",
"(",
"inline",
"[",
"2",
"]",
")",
"dict_feedback",
".",
"setdefault",
"(",
"user",
",",
"{",
"}",
")",
".",
"update",
"(",
"{",
"item",
":",
"1.0",
"if",
"self",
".",
"as_binary",
"else",
"value",
"}",
")",
"items_seen_by_user",
".",
"setdefault",
"(",
"user",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"item",
")",
"users_viewed_item",
".",
"setdefault",
"(",
"item",
",",
"set",
"(",
")",
")",
".",
"add",
"(",
"user",
")",
"list_users",
".",
"add",
"(",
"user",
")",
"list_items",
".",
"add",
"(",
"item",
")",
"mean_value",
"+=",
"1.0",
"if",
"self",
".",
"as_binary",
"else",
"value",
"list_feedback",
".",
"append",
"(",
"1.0",
"if",
"self",
".",
"as_binary",
"else",
"value",
")",
"number_interactions",
"+=",
"1",
"mean_value",
"/=",
"float",
"(",
"number_interactions",
")",
"list_users",
"=",
"sorted",
"(",
"list",
"(",
"list_users",
")",
")",
"list_items",
"=",
"sorted",
"(",
"list",
"(",
"list_items",
")",
")",
"# Create a dictionary with unobserved items for each user / Map user with its respective id",
"for",
"user",
"in",
"list_users",
":",
"items_unobserved",
"[",
"user",
"]",
"=",
"list",
"(",
"set",
"(",
"list_items",
")",
"-",
"set",
"(",
"items_seen_by_user",
"[",
"user",
"]",
")",
")",
"# Calculate the sparsity of the set: N / (nu * ni)",
"sparsity",
"=",
"(",
"1",
"-",
"(",
"number_interactions",
"/",
"float",
"(",
"len",
"(",
"list_users",
")",
"*",
"len",
"(",
"list_items",
")",
")",
")",
")",
"*",
"100",
"dict_file",
"=",
"{",
"'feedback'",
":",
"dict_feedback",
",",
"'users'",
":",
"list_users",
",",
"'items'",
":",
"list_items",
",",
"'sparsity'",
":",
"sparsity",
",",
"'number_interactions'",
":",
"number_interactions",
",",
"'users_viewed_item'",
":",
"users_viewed_item",
",",
"'items_unobserved'",
":",
"items_unobserved",
",",
"'items_seen_by_user'",
":",
"items_seen_by_user",
",",
"'mean_value'",
":",
"mean_value",
",",
"'max_value'",
":",
"max",
"(",
"list_feedback",
")",
",",
"'min_value'",
":",
"min",
"(",
"list_feedback",
")",
",",
"}",
"return",
"dict_file"
] | [
51,
4
] | [
119,
24
] | python | en | ['en', 'error', 'th'] | False |
ReadFile.read_metadata_or_similarity | (self) |
Method to read metadata or similarity files. Expects at least 2 columns for metadata file (item metadata or
item metadata score) and 3 columns for similarity files (item item similarity)
:return: Dictionary with file information
:rtype: dict
|
Method to read metadata or similarity files. Expects at least 2 columns for metadata file (item metadata or
item metadata score) and 3 columns for similarity files (item item similarity) | def read_metadata_or_similarity(self):
"""
Method to read metadata or similarity files. Expects at least 2 columns for metadata file (item metadata or
item metadata score) and 3 columns for similarity files (item item similarity)
:return: Dictionary with file information
:rtype: dict
"""
dict_values = {}
list_col_1 = set()
list_col_2 = set()
mean_value = 0
number_interactions = 0
with open(self.input_file) as infile:
for line in infile:
if line.strip():
inline = line.split(self.sep)
if len(inline) == 1:
raise TypeError("Error: Space type (sep) is invalid!")
if len(inline) == 2:
attr1, attr2 = int(inline[0]), inline[1]
dict_values.setdefault(attr1, {}).update({attr2: 1.0})
list_col_1.add(attr1)
list_col_2.add(attr2)
number_interactions += 1
else:
attr1, attr2, value = int(inline[0]), inline[1], float(inline[2])
dict_values.setdefault(attr1, {}).update({attr2: 1.0 if self.as_binary else value})
list_col_1.add(attr1)
list_col_2.add(attr2)
mean_value += value
number_interactions += 1
dict_file = {
'dict': dict_values,
'col_1': list(list_col_1),
'col_2': list(list_col_2),
'mean_value': mean_value,
'number_interactions': number_interactions
}
return dict_file | [
"def",
"read_metadata_or_similarity",
"(",
"self",
")",
":",
"dict_values",
"=",
"{",
"}",
"list_col_1",
"=",
"set",
"(",
")",
"list_col_2",
"=",
"set",
"(",
")",
"mean_value",
"=",
"0",
"number_interactions",
"=",
"0",
"with",
"open",
"(",
"self",
".",
"input_file",
")",
"as",
"infile",
":",
"for",
"line",
"in",
"infile",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"inline",
"=",
"line",
".",
"split",
"(",
"self",
".",
"sep",
")",
"if",
"len",
"(",
"inline",
")",
"==",
"1",
":",
"raise",
"TypeError",
"(",
"\"Error: Space type (sep) is invalid!\"",
")",
"if",
"len",
"(",
"inline",
")",
"==",
"2",
":",
"attr1",
",",
"attr2",
"=",
"int",
"(",
"inline",
"[",
"0",
"]",
")",
",",
"inline",
"[",
"1",
"]",
"dict_values",
".",
"setdefault",
"(",
"attr1",
",",
"{",
"}",
")",
".",
"update",
"(",
"{",
"attr2",
":",
"1.0",
"}",
")",
"list_col_1",
".",
"add",
"(",
"attr1",
")",
"list_col_2",
".",
"add",
"(",
"attr2",
")",
"number_interactions",
"+=",
"1",
"else",
":",
"attr1",
",",
"attr2",
",",
"value",
"=",
"int",
"(",
"inline",
"[",
"0",
"]",
")",
",",
"inline",
"[",
"1",
"]",
",",
"float",
"(",
"inline",
"[",
"2",
"]",
")",
"dict_values",
".",
"setdefault",
"(",
"attr1",
",",
"{",
"}",
")",
".",
"update",
"(",
"{",
"attr2",
":",
"1.0",
"if",
"self",
".",
"as_binary",
"else",
"value",
"}",
")",
"list_col_1",
".",
"add",
"(",
"attr1",
")",
"list_col_2",
".",
"add",
"(",
"attr2",
")",
"mean_value",
"+=",
"value",
"number_interactions",
"+=",
"1",
"dict_file",
"=",
"{",
"'dict'",
":",
"dict_values",
",",
"'col_1'",
":",
"list",
"(",
"list_col_1",
")",
",",
"'col_2'",
":",
"list",
"(",
"list_col_2",
")",
",",
"'mean_value'",
":",
"mean_value",
",",
"'number_interactions'",
":",
"number_interactions",
"}",
"return",
"dict_file"
] | [
121,
4
] | [
166,
24
] | python | en | ['en', 'error', 'th'] | False |
ReadFile.read_like_triple | (self) |
Method to return information in the file as a triple. eg. (user, item, value)
:return: List with triples in the file
:rtype: list
|
Method to return information in the file as a triple. eg. (user, item, value) | def read_like_triple(self):
"""
Method to return information in the file as a triple. eg. (user, item, value)
:return: List with triples in the file
:rtype: list
"""
triple_list = []
with open(self.input_file) as infile:
for line in infile:
if line.strip():
inline = line.split(self.sep)
if len(inline) == 1:
raise TypeError("Error: Space type (sep) is invalid!")
user, item, value = int(inline[0]), int(inline[1]), float(inline[2])
triple_list.append((user, item, value))
return triple_list | [
"def",
"read_like_triple",
"(",
"self",
")",
":",
"triple_list",
"=",
"[",
"]",
"with",
"open",
"(",
"self",
".",
"input_file",
")",
"as",
"infile",
":",
"for",
"line",
"in",
"infile",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"inline",
"=",
"line",
".",
"split",
"(",
"self",
".",
"sep",
")",
"if",
"len",
"(",
"inline",
")",
"==",
"1",
":",
"raise",
"TypeError",
"(",
"\"Error: Space type (sep) is invalid!\"",
")",
"user",
",",
"item",
",",
"value",
"=",
"int",
"(",
"inline",
"[",
"0",
"]",
")",
",",
"int",
"(",
"inline",
"[",
"1",
"]",
")",
",",
"float",
"(",
"inline",
"[",
"2",
"]",
")",
"triple_list",
".",
"append",
"(",
"(",
"user",
",",
"item",
",",
"value",
")",
")",
"return",
"triple_list"
] | [
168,
4
] | [
189,
26
] | python | en | ['en', 'error', 'th'] | False |
ReadFile.read_with_pandas | (self) |
Method to read file with pandas
:return DataFrame with file lines
|
Method to read file with pandas
:return DataFrame with file lines | def read_with_pandas(self):
"""
Method to read file with pandas
:return DataFrame with file lines
"""
df = pd.read_csv(self.input_file, sep=self.sep, skiprows=self.header, header=None, names=self.names)
if self.header is not None:
df.columns = [i for i in range(len(df.columns))]
if self.as_binary:
df.iloc[:, self.binary_col] = 1
return df.sort_values(by=[0, 1]) | [
"def",
"read_with_pandas",
"(",
"self",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"self",
".",
"input_file",
",",
"sep",
"=",
"self",
".",
"sep",
",",
"skiprows",
"=",
"self",
".",
"header",
",",
"header",
"=",
"None",
",",
"names",
"=",
"self",
".",
"names",
")",
"if",
"self",
".",
"header",
"is",
"not",
"None",
":",
"df",
".",
"columns",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"df",
".",
"columns",
")",
")",
"]",
"if",
"self",
".",
"as_binary",
":",
"df",
".",
"iloc",
"[",
":",
",",
"self",
".",
"binary_col",
"]",
"=",
"1",
"return",
"df",
".",
"sort_values",
"(",
"by",
"=",
"[",
"0",
",",
"1",
"]",
")"
] | [
191,
4
] | [
206,
40
] | python | en | ['en', 'error', 'th'] | False |
WriteFile.__init__ | (self, output_file, data=None, sep="\t", mode='w', as_binary=False) |
Class to write predictions and information
:param output_file: File with dir to write the information
:type output_file: str
:param data: Data to be write
:type data: list, dict, set
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param mode: Method to write file
:type mode: str, default 'w'
:param as_binary: If True, write score equals 1
:type as_binary: bool, default False
|
Class to write predictions and information
:param output_file: File with dir to write the information
:type output_file: str
:param data: Data to be write
:type data: list, dict, set | def __init__(self, output_file, data=None, sep="\t", mode='w', as_binary=False):
"""
Class to write predictions and information
:param output_file: File with dir to write the information
:type output_file: str
:param data: Data to be write
:type data: list, dict, set
:param sep: Delimiter for input files
:type sep: str, default '\t'
:param mode: Method to write file
:type mode: str, default 'w'
:param as_binary: If True, write score equals 1
:type as_binary: bool, default False
"""
self.output_file = output_file
self.data = data
self.sep = sep
self.mode = mode
self.as_binary = as_binary | [
"def",
"__init__",
"(",
"self",
",",
"output_file",
",",
"data",
"=",
"None",
",",
"sep",
"=",
"\"\\t\"",
",",
"mode",
"=",
"'w'",
",",
"as_binary",
"=",
"False",
")",
":",
"self",
".",
"output_file",
"=",
"output_file",
"self",
".",
"data",
"=",
"data",
"self",
".",
"sep",
"=",
"sep",
"self",
".",
"mode",
"=",
"mode",
"self",
".",
"as_binary",
"=",
"as_binary"
] | [
239,
4
] | [
264,
34
] | python | en | ['en', 'error', 'th'] | False |
WriteFile.write | (self) |
Method to write using data as list. e.g.: [user, item, score]
|
Method to write using data as list. e.g.: [user, item, score]
| def write(self):
"""
Method to write using data as list. e.g.: [user, item, score]
"""
with open(self.output_file, self.mode) as infile:
for triple in self.data:
if self.as_binary:
infile.write('%d%s%d%s%f\n' % (triple[0], self.sep, triple[1], self.sep, 1.0))
else:
infile.write('%d%s%d%s%f\n' % (triple[0], self.sep, triple[1], self.sep, triple[2])) | [
"def",
"write",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"output_file",
",",
"self",
".",
"mode",
")",
"as",
"infile",
":",
"for",
"triple",
"in",
"self",
".",
"data",
":",
"if",
"self",
".",
"as_binary",
":",
"infile",
".",
"write",
"(",
"'%d%s%d%s%f\\n'",
"%",
"(",
"triple",
"[",
"0",
"]",
",",
"self",
".",
"sep",
",",
"triple",
"[",
"1",
"]",
",",
"self",
".",
"sep",
",",
"1.0",
")",
")",
"else",
":",
"infile",
".",
"write",
"(",
"'%d%s%d%s%f\\n'",
"%",
"(",
"triple",
"[",
"0",
"]",
",",
"self",
".",
"sep",
",",
"triple",
"[",
"1",
"]",
",",
"self",
".",
"sep",
",",
"triple",
"[",
"2",
"]",
")",
")"
] | [
266,
4
] | [
277,
104
] | python | en | ['en', 'error', 'th'] | False |
WriteFile.write_with_dict | (self) |
Method to write using data as dictionary. e.g.: user: {item : score}
|
Method to write using data as dictionary. e.g.: user: {item : score}
| def write_with_dict(self):
"""
Method to write using data as dictionary. e.g.: user: {item : score}
"""
with open(self.output_file, self.mode) as infile:
for user in self.data:
for pair in self.data[user]:
infile.write('%d%s%d%s%f\n' % (user, self.sep, pair[0], self.sep, pair[1])) | [
"def",
"write_with_dict",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"output_file",
",",
"self",
".",
"mode",
")",
"as",
"infile",
":",
"for",
"user",
"in",
"self",
".",
"data",
":",
"for",
"pair",
"in",
"self",
".",
"data",
"[",
"user",
"]",
":",
"infile",
".",
"write",
"(",
"'%d%s%d%s%f\\n'",
"%",
"(",
"user",
",",
"self",
".",
"sep",
",",
"pair",
"[",
"0",
"]",
",",
"self",
".",
"sep",
",",
"pair",
"[",
"1",
"]",
")",
")"
] | [
279,
4
] | [
288,
95
] | python | en | ['en', 'error', 'th'] | False |
WriteFile.write_with_pandas | (self, df) |
Method to use a pandas DataFrame as data
:param df: Data to write in output file
:type df: DataFrame
|
Method to use a pandas DataFrame as data
:param df: Data to write in output file
:type df: DataFrame
| def write_with_pandas(self, df):
"""
Method to use a pandas DataFrame as data
:param df: Data to write in output file
:type df: DataFrame
"""
df.to_csv(self.output_file, sep=self.sep, mode=self.mode, header=None, index=False) | [
"def",
"write_with_pandas",
"(",
"self",
",",
"df",
")",
":",
"df",
".",
"to_csv",
"(",
"self",
".",
"output_file",
",",
"sep",
"=",
"self",
".",
"sep",
",",
"mode",
"=",
"self",
".",
"mode",
",",
"header",
"=",
"None",
",",
"index",
"=",
"False",
")"
] | [
290,
4
] | [
299,
91
] | python | en | ['en', 'error', 'th'] | False |
format | (value, format_string) | Convenience function | Convenience function | def format(value, format_string):
"Convenience function"
df = DateFormat(value)
return df.format(format_string) | [
"def",
"format",
"(",
"value",
",",
"format_string",
")",
":",
"df",
"=",
"DateFormat",
"(",
"value",
")",
"return",
"df",
".",
"format",
"(",
"format_string",
")"
] | [
323,
0
] | [
326,
35
] | python | en | ['en', 'en', 'en'] | False |
time_format | (value, format_string) | Convenience function | Convenience function | def time_format(value, format_string):
"Convenience function"
tf = TimeFormat(value)
return tf.format(format_string) | [
"def",
"time_format",
"(",
"value",
",",
"format_string",
")",
":",
"tf",
"=",
"TimeFormat",
"(",
"value",
")",
"return",
"tf",
".",
"format",
"(",
"format_string",
")"
] | [
329,
0
] | [
332,
35
] | python | en | ['en', 'en', 'en'] | False |
TimeFormat.a | (self) | a.m.' or 'p.m. | a.m.' or 'p.m. | def a(self):
"'a.m.' or 'p.m.'"
if self.data.hour > 11:
return _('p.m.')
return _('a.m.') | [
"def",
"a",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
".",
"hour",
">",
"11",
":",
"return",
"_",
"(",
"'p.m.'",
")",
"return",
"_",
"(",
"'a.m.'",
")"
] | [
62,
4
] | [
66,
24
] | python | en | ['en', 'en', 'en'] | True |
TimeFormat.e | (self) |
Timezone name.
If timezone information is not available, return an empty string.
|
Timezone name. | def e(self):
"""
Timezone name.
If timezone information is not available, return an empty string.
"""
if not self.timezone:
return ""
try:
if hasattr(self.data, 'tzinfo') and self.data.tzinfo:
return self.data.tzname() or ''
except NotImplementedError:
pass
return "" | [
"def",
"e",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timezone",
":",
"return",
"\"\"",
"try",
":",
"if",
"hasattr",
"(",
"self",
".",
"data",
",",
"'tzinfo'",
")",
"and",
"self",
".",
"data",
".",
"tzinfo",
":",
"return",
"self",
".",
"data",
".",
"tzname",
"(",
")",
"or",
"''",
"except",
"NotImplementedError",
":",
"pass",
"return",
"\"\""
] | [
74,
4
] | [
88,
17
] | python | en | ['en', 'error', 'th'] | False |
TimeFormat.f | (self) |
Time, in 12-hour hours and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
|
Time, in 12-hour hours and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
| def f(self):
"""
Time, in 12-hour hours and minutes, with minutes left off if they're
zero.
Examples: '1', '1:30', '2:05', '2'
Proprietary extension.
"""
if self.data.minute == 0:
return self.g()
return '%s:%s' % (self.g(), self.i()) | [
"def",
"f",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
".",
"minute",
"==",
"0",
":",
"return",
"self",
".",
"g",
"(",
")",
"return",
"'%s:%s'",
"%",
"(",
"self",
".",
"g",
"(",
")",
",",
"self",
".",
"i",
"(",
")",
")"
] | [
90,
4
] | [
99,
45
] | python | en | ['en', 'error', 'th'] | False |
TimeFormat.g | (self) | Hour, 12-hour format without leading zeros; i.e. '1' to '12 | Hour, 12-hour format without leading zeros; i.e. '1' to '12 | def g(self):
"Hour, 12-hour format without leading zeros; i.e. '1' to '12'"
return self.data.hour % 12 or 12 | [
"def",
"g",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"hour",
"%",
"12",
"or",
"12"
] | [
101,
4
] | [
103,
40
] | python | en | ['en', 'en', 'en'] | True |
TimeFormat.G | (self) | Hour, 24-hour format without leading zeros; i.e. '0' to '23 | Hour, 24-hour format without leading zeros; i.e. '0' to '23 | def G(self):
"Hour, 24-hour format without leading zeros; i.e. '0' to '23'"
return self.data.hour | [
"def",
"G",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"hour"
] | [
105,
4
] | [
107,
29
] | python | en | ['en', 'en', 'en'] | True |
TimeFormat.h | (self) | Hour, 12-hour format; i.e. '01' to '12 | Hour, 12-hour format; i.e. '01' to '12 | def h(self):
"Hour, 12-hour format; i.e. '01' to '12'"
return '%02d' % self.g() | [
"def",
"h",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"g",
"(",
")"
] | [
109,
4
] | [
111,
32
] | python | en | ['en', 'pt', 'it'] | False |
TimeFormat.H | (self) | Hour, 24-hour format; i.e. '00' to '23 | Hour, 24-hour format; i.e. '00' to '23 | def H(self):
"Hour, 24-hour format; i.e. '00' to '23'"
return '%02d' % self.G() | [
"def",
"H",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"G",
"(",
")"
] | [
113,
4
] | [
115,
32
] | python | en | ['en', 'pt', 'it'] | False |
TimeFormat.i | (self) | Minutes; i.e. '00' to '59 | Minutes; i.e. '00' to '59 | def i(self):
"Minutes; i.e. '00' to '59'"
return '%02d' % self.data.minute | [
"def",
"i",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"data",
".",
"minute"
] | [
117,
4
] | [
119,
40
] | python | en | ['en', 'mi', 'it'] | False |
TimeFormat.O | (self) |
Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
If timezone information is not available, return an empty string.
|
Difference to Greenwich time in hours; e.g. '+0200', '-0430'. | def O(self): # NOQA: E743, E741
"""
Difference to Greenwich time in hours; e.g. '+0200', '-0430'.
If timezone information is not available, return an empty string.
"""
if not self.timezone:
return ""
seconds = self.Z()
if seconds == "":
return ""
sign = '-' if seconds < 0 else '+'
seconds = abs(seconds)
return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) | [
"def",
"O",
"(",
"self",
")",
":",
"# NOQA: E743, E741",
"if",
"not",
"self",
".",
"timezone",
":",
"return",
"\"\"",
"seconds",
"=",
"self",
".",
"Z",
"(",
")",
"if",
"seconds",
"==",
"\"\"",
":",
"return",
"\"\"",
"sign",
"=",
"'-'",
"if",
"seconds",
"<",
"0",
"else",
"'+'",
"seconds",
"=",
"abs",
"(",
"seconds",
")",
"return",
"\"%s%02d%02d\"",
"%",
"(",
"sign",
",",
"seconds",
"//",
"3600",
",",
"(",
"seconds",
"//",
"60",
")",
"%",
"60",
")"
] | [
121,
4
] | [
135,
75
] | python | en | ['en', 'error', 'th'] | False |
TimeFormat.P | (self) |
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension.
|
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension.
| def P(self):
"""
Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off
if they're zero and the strings 'midnight' and 'noon' if appropriate.
Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
Proprietary extension.
"""
if self.data.minute == 0 and self.data.hour == 0:
return _('midnight')
if self.data.minute == 0 and self.data.hour == 12:
return _('noon')
return '%s %s' % (self.f(), self.a()) | [
"def",
"P",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
".",
"minute",
"==",
"0",
"and",
"self",
".",
"data",
".",
"hour",
"==",
"0",
":",
"return",
"_",
"(",
"'midnight'",
")",
"if",
"self",
".",
"data",
".",
"minute",
"==",
"0",
"and",
"self",
".",
"data",
".",
"hour",
"==",
"12",
":",
"return",
"_",
"(",
"'noon'",
")",
"return",
"'%s %s'",
"%",
"(",
"self",
".",
"f",
"(",
")",
",",
"self",
".",
"a",
"(",
")",
")"
] | [
137,
4
] | [
148,
45
] | python | en | ['en', 'error', 'th'] | False |
TimeFormat.s | (self) | Seconds; i.e. '00' to '59 | Seconds; i.e. '00' to '59 | def s(self):
"Seconds; i.e. '00' to '59'"
return '%02d' % self.data.second | [
"def",
"s",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"data",
".",
"second"
] | [
150,
4
] | [
152,
40
] | python | en | ['en', 'pt', 'it'] | False |
TimeFormat.T | (self) |
Time zone of this machine; e.g. 'EST' or 'MDT'.
If timezone information is not available, return an empty string.
|
Time zone of this machine; e.g. 'EST' or 'MDT'. | def T(self):
"""
Time zone of this machine; e.g. 'EST' or 'MDT'.
If timezone information is not available, return an empty string.
"""
if not self.timezone:
return ""
if not _datetime_ambiguous_or_imaginary(self.data, self.timezone):
name = self.timezone.tzname(self.data)
else:
name = self.format('O')
return str(name) | [
"def",
"T",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timezone",
":",
"return",
"\"\"",
"if",
"not",
"_datetime_ambiguous_or_imaginary",
"(",
"self",
".",
"data",
",",
"self",
".",
"timezone",
")",
":",
"name",
"=",
"self",
".",
"timezone",
".",
"tzname",
"(",
"self",
".",
"data",
")",
"else",
":",
"name",
"=",
"self",
".",
"format",
"(",
"'O'",
")",
"return",
"str",
"(",
"name",
")"
] | [
154,
4
] | [
167,
24
] | python | en | ['en', 'error', 'th'] | False |
TimeFormat.u | (self) | Microseconds; i.e. '000000' to '999999 | Microseconds; i.e. '000000' to '999999 | def u(self):
"Microseconds; i.e. '000000' to '999999'"
return '%06d' % self.data.microsecond | [
"def",
"u",
"(",
"self",
")",
":",
"return",
"'%06d'",
"%",
"self",
".",
"data",
".",
"microsecond"
] | [
169,
4
] | [
171,
45
] | python | en | ['en', 'mk', 'en'] | True |
TimeFormat.Z | (self) |
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
If timezone information is not available, return an empty string.
|
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive. | def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
If timezone information is not available, return an empty string.
"""
if (
not self.timezone or
_datetime_ambiguous_or_imaginary(self.data, self.timezone)
):
return ""
offset = self.timezone.utcoffset(self.data)
# `offset` is a datetime.timedelta. For negative values (to the west of
# UTC) only days can be negative (days=-1) and seconds are always
# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# Positive offsets have days=0
return offset.days * 86400 + offset.seconds | [
"def",
"Z",
"(",
"self",
")",
":",
"if",
"(",
"not",
"self",
".",
"timezone",
"or",
"_datetime_ambiguous_or_imaginary",
"(",
"self",
".",
"data",
",",
"self",
".",
"timezone",
")",
")",
":",
"return",
"\"\"",
"offset",
"=",
"self",
".",
"timezone",
".",
"utcoffset",
"(",
"self",
".",
"data",
")",
"# `offset` is a datetime.timedelta. For negative values (to the west of",
"# UTC) only days can be negative (days=-1) and seconds are always",
"# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)",
"# Positive offsets have days=0",
"return",
"offset",
".",
"days",
"*",
"86400",
"+",
"offset",
".",
"seconds"
] | [
173,
4
] | [
193,
51
] | python | en | ['en', 'error', 'th'] | False |
DateFormat.b | (self) | Month, textual, 3 letters, lowercase; e.g. 'jan | Month, textual, 3 letters, lowercase; e.g. 'jan | def b(self):
"Month, textual, 3 letters, lowercase; e.g. 'jan'"
return MONTHS_3[self.data.month] | [
"def",
"b",
"(",
"self",
")",
":",
"return",
"MONTHS_3",
"[",
"self",
".",
"data",
".",
"month",
"]"
] | [
197,
4
] | [
199,
40
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.c | (self) |
ISO 8601 Format
Example : '2008-01-02T10:30:00.000123'
|
ISO 8601 Format
Example : '2008-01-02T10:30:00.000123'
| def c(self):
"""
ISO 8601 Format
Example : '2008-01-02T10:30:00.000123'
"""
return self.data.isoformat() | [
"def",
"c",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"isoformat",
"(",
")"
] | [
201,
4
] | [
206,
36
] | python | en | ['en', 'error', 'th'] | False |
DateFormat.d | (self) | Day of the month, 2 digits with leading zeros; i.e. '01' to '31 | Day of the month, 2 digits with leading zeros; i.e. '01' to '31 | def d(self):
"Day of the month, 2 digits with leading zeros; i.e. '01' to '31'"
return '%02d' % self.data.day | [
"def",
"d",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"data",
".",
"day"
] | [
208,
4
] | [
210,
37
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.D | (self) | Day of the week, textual, 3 letters; e.g. 'Fri | Day of the week, textual, 3 letters; e.g. 'Fri | def D(self):
"Day of the week, textual, 3 letters; e.g. 'Fri'"
return WEEKDAYS_ABBR[self.data.weekday()] | [
"def",
"D",
"(",
"self",
")",
":",
"return",
"WEEKDAYS_ABBR",
"[",
"self",
".",
"data",
".",
"weekday",
"(",
")",
"]"
] | [
212,
4
] | [
214,
49
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.E | (self) | Alternative month names as required by some locales. Proprietary extension. | Alternative month names as required by some locales. Proprietary extension. | def E(self):
"Alternative month names as required by some locales. Proprietary extension."
return MONTHS_ALT[self.data.month] | [
"def",
"E",
"(",
"self",
")",
":",
"return",
"MONTHS_ALT",
"[",
"self",
".",
"data",
".",
"month",
"]"
] | [
216,
4
] | [
218,
42
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.F | (self) | Month, textual, long; e.g. 'January | Month, textual, long; e.g. 'January | def F(self):
"Month, textual, long; e.g. 'January'"
return MONTHS[self.data.month] | [
"def",
"F",
"(",
"self",
")",
":",
"return",
"MONTHS",
"[",
"self",
".",
"data",
".",
"month",
"]"
] | [
220,
4
] | [
222,
38
] | python | en | ['en', 'en', 'pt'] | True |
DateFormat.I | (self) | 1' if Daylight Savings Time, '0' otherwise. | 1' if Daylight Savings Time, '0' otherwise. | def I(self): # NOQA: E743, E741
"'1' if Daylight Savings Time, '0' otherwise."
if (
not self.timezone or
_datetime_ambiguous_or_imaginary(self.data, self.timezone)
):
return ''
return '1' if self.timezone.dst(self.data) else '0' | [
"def",
"I",
"(",
"self",
")",
":",
"# NOQA: E743, E741",
"if",
"(",
"not",
"self",
".",
"timezone",
"or",
"_datetime_ambiguous_or_imaginary",
"(",
"self",
".",
"data",
",",
"self",
".",
"timezone",
")",
")",
":",
"return",
"''",
"return",
"'1'",
"if",
"self",
".",
"timezone",
".",
"dst",
"(",
"self",
".",
"data",
")",
"else",
"'0'"
] | [
224,
4
] | [
231,
59
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.j | (self) | Day of the month without leading zeros; i.e. '1' to '31 | Day of the month without leading zeros; i.e. '1' to '31 | def j(self):
"Day of the month without leading zeros; i.e. '1' to '31'"
return self.data.day | [
"def",
"j",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"day"
] | [
233,
4
] | [
235,
28
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.l | (self) | Day of the week, textual, long; e.g. 'Friday | Day of the week, textual, long; e.g. 'Friday | def l(self): # NOQA: E743, E741
"Day of the week, textual, long; e.g. 'Friday'"
return WEEKDAYS[self.data.weekday()] | [
"def",
"l",
"(",
"self",
")",
":",
"# NOQA: E743, E741",
"return",
"WEEKDAYS",
"[",
"self",
".",
"data",
".",
"weekday",
"(",
")",
"]"
] | [
237,
4
] | [
239,
44
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.L | (self) | Boolean for whether it is a leap year; i.e. True or False | Boolean for whether it is a leap year; i.e. True or False | def L(self):
"Boolean for whether it is a leap year; i.e. True or False"
return calendar.isleap(self.data.year) | [
"def",
"L",
"(",
"self",
")",
":",
"return",
"calendar",
".",
"isleap",
"(",
"self",
".",
"data",
".",
"year",
")"
] | [
241,
4
] | [
243,
46
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.m | (self) | Month; i.e. '01' to '12 | Month; i.e. '01' to '12 | def m(self):
"Month; i.e. '01' to '12'"
return '%02d' % self.data.month | [
"def",
"m",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"self",
".",
"data",
".",
"month"
] | [
245,
4
] | [
247,
39
] | python | en | ['en', 'pt', 'it'] | False |
DateFormat.M | (self) | Month, textual, 3 letters; e.g. 'Jan | Month, textual, 3 letters; e.g. 'Jan | def M(self):
"Month, textual, 3 letters; e.g. 'Jan'"
return MONTHS_3[self.data.month].title() | [
"def",
"M",
"(",
"self",
")",
":",
"return",
"MONTHS_3",
"[",
"self",
".",
"data",
".",
"month",
"]",
".",
"title",
"(",
")"
] | [
249,
4
] | [
251,
48
] | python | en | ['en', 'fr', 'pt'] | False |
DateFormat.n | (self) | Month without leading zeros; i.e. '1' to '12 | Month without leading zeros; i.e. '1' to '12 | def n(self):
"Month without leading zeros; i.e. '1' to '12'"
return self.data.month | [
"def",
"n",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"month"
] | [
253,
4
] | [
255,
30
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.N | (self) | Month abbreviation in Associated Press style. Proprietary extension. | Month abbreviation in Associated Press style. Proprietary extension. | def N(self):
"Month abbreviation in Associated Press style. Proprietary extension."
return MONTHS_AP[self.data.month] | [
"def",
"N",
"(",
"self",
")",
":",
"return",
"MONTHS_AP",
"[",
"self",
".",
"data",
".",
"month",
"]"
] | [
257,
4
] | [
259,
41
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.o | (self) | ISO 8601 year number matching the ISO week number (W) | ISO 8601 year number matching the ISO week number (W) | def o(self):
"ISO 8601 year number matching the ISO week number (W)"
return self.data.isocalendar()[0] | [
"def",
"o",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"isocalendar",
"(",
")",
"[",
"0",
"]"
] | [
261,
4
] | [
263,
41
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.r | (self) | RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200 | RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200 | def r(self):
"RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
if type(self.data) is datetime.date:
raise TypeError(
"The format for date objects may not contain time-related "
"format specifiers (found 'r')."
)
if is_naive(self.data):
dt = make_aware(self.data, timezone=self.timezone)
else:
dt = self.data
return format_datetime_rfc5322(dt) | [
"def",
"r",
"(",
"self",
")",
":",
"if",
"type",
"(",
"self",
".",
"data",
")",
"is",
"datetime",
".",
"date",
":",
"raise",
"TypeError",
"(",
"\"The format for date objects may not contain time-related \"",
"\"format specifiers (found 'r').\"",
")",
"if",
"is_naive",
"(",
"self",
".",
"data",
")",
":",
"dt",
"=",
"make_aware",
"(",
"self",
".",
"data",
",",
"timezone",
"=",
"self",
".",
"timezone",
")",
"else",
":",
"dt",
"=",
"self",
".",
"data",
"return",
"format_datetime_rfc5322",
"(",
"dt",
")"
] | [
265,
4
] | [
276,
42
] | python | co | ['fr', 'co', 'it'] | False |
DateFormat.S | (self) | English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th | English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th | def S(self):
"English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"
if self.data.day in (11, 12, 13): # Special case
return 'th'
last = self.data.day % 10
if last == 1:
return 'st'
if last == 2:
return 'nd'
if last == 3:
return 'rd'
return 'th' | [
"def",
"S",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
".",
"day",
"in",
"(",
"11",
",",
"12",
",",
"13",
")",
":",
"# Special case",
"return",
"'th'",
"last",
"=",
"self",
".",
"data",
".",
"day",
"%",
"10",
"if",
"last",
"==",
"1",
":",
"return",
"'st'",
"if",
"last",
"==",
"2",
":",
"return",
"'nd'",
"if",
"last",
"==",
"3",
":",
"return",
"'rd'",
"return",
"'th'"
] | [
278,
4
] | [
289,
19
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.t | (self) | Number of days in the given month; i.e. '28' to '31 | Number of days in the given month; i.e. '28' to '31 | def t(self):
"Number of days in the given month; i.e. '28' to '31'"
return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1] | [
"def",
"t",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"calendar",
".",
"monthrange",
"(",
"self",
".",
"data",
".",
"year",
",",
"self",
".",
"data",
".",
"month",
")",
"[",
"1",
"]"
] | [
291,
4
] | [
293,
79
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.U | (self) | Seconds since the Unix epoch (January 1 1970 00:00:00 GMT) | Seconds since the Unix epoch (January 1 1970 00:00:00 GMT) | def U(self):
"Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
if isinstance(self.data, datetime.datetime) and is_aware(self.data):
return int(calendar.timegm(self.data.utctimetuple()))
else:
return int(time.mktime(self.data.timetuple())) | [
"def",
"U",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"data",
",",
"datetime",
".",
"datetime",
")",
"and",
"is_aware",
"(",
"self",
".",
"data",
")",
":",
"return",
"int",
"(",
"calendar",
".",
"timegm",
"(",
"self",
".",
"data",
".",
"utctimetuple",
"(",
")",
")",
")",
"else",
":",
"return",
"int",
"(",
"time",
".",
"mktime",
"(",
"self",
".",
"data",
".",
"timetuple",
"(",
")",
")",
")"
] | [
295,
4
] | [
300,
58
] | python | en | ['en', 'cs', 'en'] | True |
DateFormat.w | (self) | Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday) | Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday) | def w(self):
"Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)"
return (self.data.weekday() + 1) % 7 | [
"def",
"w",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"data",
".",
"weekday",
"(",
")",
"+",
"1",
")",
"%",
"7"
] | [
302,
4
] | [
304,
44
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.W | (self) | ISO-8601 week number of year, weeks starting on Monday | ISO-8601 week number of year, weeks starting on Monday | def W(self):
"ISO-8601 week number of year, weeks starting on Monday"
return self.data.isocalendar()[1] | [
"def",
"W",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"isocalendar",
"(",
")",
"[",
"1",
"]"
] | [
306,
4
] | [
308,
41
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.y | (self) | Year, 2 digits with leading zeros; e.g. '99'. | Year, 2 digits with leading zeros; e.g. '99'. | def y(self):
"""Year, 2 digits with leading zeros; e.g. '99'."""
return '%02d' % (self.data.year % 100) | [
"def",
"y",
"(",
"self",
")",
":",
"return",
"'%02d'",
"%",
"(",
"self",
".",
"data",
".",
"year",
"%",
"100",
")"
] | [
310,
4
] | [
312,
46
] | python | en | ['en', 'en', 'en'] | True |
DateFormat.Y | (self) | Year, 4 digits; e.g. '1999 | Year, 4 digits; e.g. '1999 | def Y(self):
"Year, 4 digits; e.g. '1999'"
return self.data.year | [
"def",
"Y",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"year"
] | [
314,
4
] | [
316,
29
] | python | da | ['da', 'ny', 'en'] | False |
DateFormat.z | (self) | Day of the year, i.e. 1 to 366. | Day of the year, i.e. 1 to 366. | def z(self):
"""Day of the year, i.e. 1 to 366."""
return self.data.timetuple().tm_yday | [
"def",
"z",
"(",
"self",
")",
":",
"return",
"self",
".",
"data",
".",
"timetuple",
"(",
")",
".",
"tm_yday"
] | [
318,
4
] | [
320,
44
] | python | en | ['en', 'en', 'en'] | True |
start_screen | () | A simple welcome screen with some music | A simple welcome screen with some music | def start_screen():
"A simple welcome screen with some music"
# Load music and loop it until the start screen ends.
pygame.mixer.music.load("data/theme.mp3")
pygame.mixer.music.play(-1)
# Draw the start screen with title gif and fonts.
blue, white = (0, 0, 71), (255, 255, 255)
start_font = pygame.font.Font("data/emulogic.ttf", 20)
start_title = pygame.image.load("data/frogger_title.gif")
window.fill(blue)
label1 = start_font.render("Press Enter", 1, white)
label2 = start_font.render("to", 1, white)
label3 = start_font.render("continue", 1, white)
window.blit(label1, (140, 300))
window.blit(label2, (215, 350))
window.blit(label3, (160, 400))
window.blit(start_title, (60, 150))
# Update the screen only once.
pygame.display.flip()
wait_for_input()
pygame.mixer.music.fadeout(2000) | [
"def",
"start_screen",
"(",
")",
":",
"# Load music and loop it until the start screen ends.",
"pygame",
".",
"mixer",
".",
"music",
".",
"load",
"(",
"\"data/theme.mp3\"",
")",
"pygame",
".",
"mixer",
".",
"music",
".",
"play",
"(",
"-",
"1",
")",
"# Draw the start screen with title gif and fonts.",
"blue",
",",
"white",
"=",
"(",
"0",
",",
"0",
",",
"71",
")",
",",
"(",
"255",
",",
"255",
",",
"255",
")",
"start_font",
"=",
"pygame",
".",
"font",
".",
"Font",
"(",
"\"data/emulogic.ttf\"",
",",
"20",
")",
"start_title",
"=",
"pygame",
".",
"image",
".",
"load",
"(",
"\"data/frogger_title.gif\"",
")",
"window",
".",
"fill",
"(",
"blue",
")",
"label1",
"=",
"start_font",
".",
"render",
"(",
"\"Press Enter\"",
",",
"1",
",",
"white",
")",
"label2",
"=",
"start_font",
".",
"render",
"(",
"\"to\"",
",",
"1",
",",
"white",
")",
"label3",
"=",
"start_font",
".",
"render",
"(",
"\"continue\"",
",",
"1",
",",
"white",
")",
"window",
".",
"blit",
"(",
"label1",
",",
"(",
"140",
",",
"300",
")",
")",
"window",
".",
"blit",
"(",
"label2",
",",
"(",
"215",
",",
"350",
")",
")",
"window",
".",
"blit",
"(",
"label3",
",",
"(",
"160",
",",
"400",
")",
")",
"window",
".",
"blit",
"(",
"start_title",
",",
"(",
"60",
",",
"150",
")",
")",
"# Update the screen only once.",
"pygame",
".",
"display",
".",
"flip",
"(",
")",
"wait_for_input",
"(",
")",
"pygame",
".",
"mixer",
".",
"music",
".",
"fadeout",
"(",
"2000",
")"
] | [
224,
0
] | [
247,
36
] | python | en | ['en', 'en', 'en'] | True |
create_floatables | () | Create the Turtle and Log instances | Create the Turtle and Log instances | def create_floatables():
"Create the Turtle and Log instances"
floatables = pygame.sprite.Group()
ys = [128, 160, 208, 248, 280]
x = 0
for _ in range(4):
turtle = Turtle(x, ys[4], "data/turtle_3_full.png", 1)
floatables.add(turtle)
x += 128
x = 20
for _ in range(3):
log = Log(x, ys[3], "data/log_small.png")
floatables.add(log)
x += 192
x = 40
for _ in range(2):
log = Log(x, ys[2], "data/log_big.png")
floatables.add(log)
x += 256
x = 60
for _ in range(4):
turtle = Turtle(x, ys[1], "data/turtle_2_full.png", 1)
floatables.add(turtle)
x += 112
x = 80
for _ in range(3):
log = Log(x, ys[0], "data/log_medium.png")
floatables.add(log)
x += 176
return floatables | [
"def",
"create_floatables",
"(",
")",
":",
"floatables",
"=",
"pygame",
".",
"sprite",
".",
"Group",
"(",
")",
"ys",
"=",
"[",
"128",
",",
"160",
",",
"208",
",",
"248",
",",
"280",
"]",
"x",
"=",
"0",
"for",
"_",
"in",
"range",
"(",
"4",
")",
":",
"turtle",
"=",
"Turtle",
"(",
"x",
",",
"ys",
"[",
"4",
"]",
",",
"\"data/turtle_3_full.png\"",
",",
"1",
")",
"floatables",
".",
"add",
"(",
"turtle",
")",
"x",
"+=",
"128",
"x",
"=",
"20",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"log",
"=",
"Log",
"(",
"x",
",",
"ys",
"[",
"3",
"]",
",",
"\"data/log_small.png\"",
")",
"floatables",
".",
"add",
"(",
"log",
")",
"x",
"+=",
"192",
"x",
"=",
"40",
"for",
"_",
"in",
"range",
"(",
"2",
")",
":",
"log",
"=",
"Log",
"(",
"x",
",",
"ys",
"[",
"2",
"]",
",",
"\"data/log_big.png\"",
")",
"floatables",
".",
"add",
"(",
"log",
")",
"x",
"+=",
"256",
"x",
"=",
"60",
"for",
"_",
"in",
"range",
"(",
"4",
")",
":",
"turtle",
"=",
"Turtle",
"(",
"x",
",",
"ys",
"[",
"1",
"]",
",",
"\"data/turtle_2_full.png\"",
",",
"1",
")",
"floatables",
".",
"add",
"(",
"turtle",
")",
"x",
"+=",
"112",
"x",
"=",
"80",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"log",
"=",
"Log",
"(",
"x",
",",
"ys",
"[",
"0",
"]",
",",
"\"data/log_medium.png\"",
")",
"floatables",
".",
"add",
"(",
"log",
")",
"x",
"+=",
"176",
"return",
"floatables"
] | [
250,
0
] | [
280,
21
] | python | en | ['en', 'en', 'en'] | True |
create_hostiles | () | Create the obstacles that trigger death on collision | Create the obstacles that trigger death on collision | def create_hostiles():
"Create the obstacles that trigger death on collision"
hostiles = pygame.sprite.Group()
ys = [520, 480, 440, 400, 360]
x = randrange(200)
for _ in range(3):
car = Car(x, ys[0], "data/car_1.png", 1)
hostiles.add(car)
x += 144
x = randrange(200)
for _ in range(3):
car = Car(x, ys[1], "data/car_2.png")
hostiles.add(car)
x += 128
x = randrange(200)
for _ in range(3):
car = Car(x, ys[2], "data/car_3.png", 1)
hostiles.add(car)
x += 128
x = randrange(200)
for _ in range(2):
car = Car(x, ys[3], "data/car_4.png")
hostiles.add(car)
x += 128
x = randrange(200)
for _ in range(2):
car = Car(x, ys[4], "data/car_5.png", 1)
hostiles.add(car)
x += 176
return hostiles | [
"def",
"create_hostiles",
"(",
")",
":",
"hostiles",
"=",
"pygame",
".",
"sprite",
".",
"Group",
"(",
")",
"ys",
"=",
"[",
"520",
",",
"480",
",",
"440",
",",
"400",
",",
"360",
"]",
"x",
"=",
"randrange",
"(",
"200",
")",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"car",
"=",
"Car",
"(",
"x",
",",
"ys",
"[",
"0",
"]",
",",
"\"data/car_1.png\"",
",",
"1",
")",
"hostiles",
".",
"add",
"(",
"car",
")",
"x",
"+=",
"144",
"x",
"=",
"randrange",
"(",
"200",
")",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"car",
"=",
"Car",
"(",
"x",
",",
"ys",
"[",
"1",
"]",
",",
"\"data/car_2.png\"",
")",
"hostiles",
".",
"add",
"(",
"car",
")",
"x",
"+=",
"128",
"x",
"=",
"randrange",
"(",
"200",
")",
"for",
"_",
"in",
"range",
"(",
"3",
")",
":",
"car",
"=",
"Car",
"(",
"x",
",",
"ys",
"[",
"2",
"]",
",",
"\"data/car_3.png\"",
",",
"1",
")",
"hostiles",
".",
"add",
"(",
"car",
")",
"x",
"+=",
"128",
"x",
"=",
"randrange",
"(",
"200",
")",
"for",
"_",
"in",
"range",
"(",
"2",
")",
":",
"car",
"=",
"Car",
"(",
"x",
",",
"ys",
"[",
"3",
"]",
",",
"\"data/car_4.png\"",
")",
"hostiles",
".",
"add",
"(",
"car",
")",
"x",
"+=",
"128",
"x",
"=",
"randrange",
"(",
"200",
")",
"for",
"_",
"in",
"range",
"(",
"2",
")",
":",
"car",
"=",
"Car",
"(",
"x",
",",
"ys",
"[",
"4",
"]",
",",
"\"data/car_5.png\"",
",",
"1",
")",
"hostiles",
".",
"add",
"(",
"car",
")",
"x",
"+=",
"176",
"return",
"hostiles"
] | [
283,
0
] | [
313,
19
] | python | en | ['en', 'en', 'en'] | True |
MovingObstacle.draw | (self) | Moves and then draws the obstacle | Moves and then draws the obstacle | def draw(self):
"Moves and then draws the obstacle"
# Adjust the position of the obstacle.
if self.go_left:
self.rect.x -= self.speed
else:
self.rect.x += self.speed
# Reset the object if it moves out of screen.
if isinstance(self, Car):
if self.rect.x > 480:
self.rect.x = -40
elif self.rect.x < -40:
self.rect.x = 480
else:
# To accommodate the big logs and introduce gaps, we use -180 here.
if self.rect.x > 480:
self.rect.x = -180
elif self.rect.x < -180:
self.rect.x = 480
# And finally draw it.
window.blit(self.img, (self.rect.x, self.rect.y)) | [
"def",
"draw",
"(",
"self",
")",
":",
"# Adjust the position of the obstacle.",
"if",
"self",
".",
"go_left",
":",
"self",
".",
"rect",
".",
"x",
"-=",
"self",
".",
"speed",
"else",
":",
"self",
".",
"rect",
".",
"x",
"+=",
"self",
".",
"speed",
"# Reset the object if it moves out of screen.",
"if",
"isinstance",
"(",
"self",
",",
"Car",
")",
":",
"if",
"self",
".",
"rect",
".",
"x",
">",
"480",
":",
"self",
".",
"rect",
".",
"x",
"=",
"-",
"40",
"elif",
"self",
".",
"rect",
".",
"x",
"<",
"-",
"40",
":",
"self",
".",
"rect",
".",
"x",
"=",
"480",
"else",
":",
"# To accommodate the big logs and introduce gaps, we use -180 here.",
"if",
"self",
".",
"rect",
".",
"x",
">",
"480",
":",
"self",
".",
"rect",
".",
"x",
"=",
"-",
"180",
"elif",
"self",
".",
"rect",
".",
"x",
"<",
"-",
"180",
":",
"self",
".",
"rect",
".",
"x",
"=",
"480",
"# And finally draw it.",
"window",
".",
"blit",
"(",
"self",
".",
"img",
",",
"(",
"self",
".",
"rect",
".",
"x",
",",
"self",
".",
"rect",
".",
"y",
")",
")"
] | [
81,
4
] | [
102,
57
] | python | en | ['en', 'en', 'en'] | True |
Frog.display_lives | (self) | Draw the life bar | Draw the life bar | def display_lives(self):
"Draw the life bar"
x, y = 0, 40
for _ in range(self.lives):
window.blit(self.img_life, (x, y))
x += 20 | [
"def",
"display_lives",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"0",
",",
"40",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"lives",
")",
":",
"window",
".",
"blit",
"(",
"self",
".",
"img_life",
",",
"(",
"x",
",",
"y",
")",
")",
"x",
"+=",
"20"
] | [
169,
4
] | [
174,
19
] | python | en | ['en', 'ja', 'en'] | True |
Frog.death | (self) | Update lives, trigger visual clues and reset frog position to default | Update lives, trigger visual clues and reset frog position to default | def death(self):
"Update lives, trigger visual clues and reset frog position to default"
# TODO: Update lives display as soon as death occurs.
self.lives -= 1
self.img = self.img_death
self.draw()
pygame.display.flip()
pygame.time.wait(500)
self.rect.x, self.rect.y = self.startpos
self.img = self.img_forward | [
"def",
"death",
"(",
"self",
")",
":",
"# TODO: Update lives display as soon as death occurs.",
"self",
".",
"lives",
"-=",
"1",
"self",
".",
"img",
"=",
"self",
".",
"img_death",
"self",
".",
"draw",
"(",
")",
"pygame",
".",
"display",
".",
"flip",
"(",
")",
"pygame",
".",
"time",
".",
"wait",
"(",
"500",
")",
"self",
".",
"rect",
".",
"x",
",",
"self",
".",
"rect",
".",
"y",
"=",
"self",
".",
"startpos",
"self",
".",
"img",
"=",
"self",
".",
"img_forward"
] | [
176,
4
] | [
185,
35
] | python | en | ['en', 'en', 'en'] | True |
AutocompleteJsonView.get | (self, request, *args, **kwargs) |
Return a JsonResponse with search results of the form:
{
results: [{id: "123" text: "foo"}],
pagination: {more: true}
}
|
Return a JsonResponse with search results of the form:
{
results: [{id: "123" text: "foo"}],
pagination: {more: true}
}
| def get(self, request, *args, **kwargs):
"""
Return a JsonResponse with search results of the form:
{
results: [{id: "123" text: "foo"}],
pagination: {more: true}
}
"""
self.term, self.model_admin, self.source_field, to_field_name = self.process_request(request)
if not self.has_perm(request):
raise PermissionDenied
self.object_list = self.get_queryset()
context = self.get_context_data()
return JsonResponse({
'results': [
{'id': str(getattr(obj, to_field_name)), 'text': str(obj)}
for obj in context['object_list']
],
'pagination': {'more': context['page_obj'].has_next()},
}) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"term",
",",
"self",
".",
"model_admin",
",",
"self",
".",
"source_field",
",",
"to_field_name",
"=",
"self",
".",
"process_request",
"(",
"request",
")",
"if",
"not",
"self",
".",
"has_perm",
"(",
"request",
")",
":",
"raise",
"PermissionDenied",
"self",
".",
"object_list",
"=",
"self",
".",
"get_queryset",
"(",
")",
"context",
"=",
"self",
".",
"get_context_data",
"(",
")",
"return",
"JsonResponse",
"(",
"{",
"'results'",
":",
"[",
"{",
"'id'",
":",
"str",
"(",
"getattr",
"(",
"obj",
",",
"to_field_name",
")",
")",
",",
"'text'",
":",
"str",
"(",
"obj",
")",
"}",
"for",
"obj",
"in",
"context",
"[",
"'object_list'",
"]",
"]",
",",
"'pagination'",
":",
"{",
"'more'",
":",
"context",
"[",
"'page_obj'",
"]",
".",
"has_next",
"(",
")",
"}",
",",
"}",
")"
] | [
11,
4
] | [
32,
10
] | python | en | ['en', 'error', 'th'] | False |
AutocompleteJsonView.get_paginator | (self, *args, **kwargs) | Use the ModelAdmin's paginator. | Use the ModelAdmin's paginator. | def get_paginator(self, *args, **kwargs):
"""Use the ModelAdmin's paginator."""
return self.model_admin.get_paginator(self.request, *args, **kwargs) | [
"def",
"get_paginator",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"model_admin",
".",
"get_paginator",
"(",
"self",
".",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
34,
4
] | [
36,
76
] | python | en | ['en', 'en', 'en'] | True |
AutocompleteJsonView.get_queryset | (self) | Return queryset based on ModelAdmin.get_search_results(). | Return queryset based on ModelAdmin.get_search_results(). | def get_queryset(self):
"""Return queryset based on ModelAdmin.get_search_results()."""
qs = self.model_admin.get_queryset(self.request)
qs = qs.complex_filter(self.source_field.get_limit_choices_to())
qs, search_use_distinct = self.model_admin.get_search_results(self.request, qs, self.term)
if search_use_distinct:
qs = qs.distinct()
return qs | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"model_admin",
".",
"get_queryset",
"(",
"self",
".",
"request",
")",
"qs",
"=",
"qs",
".",
"complex_filter",
"(",
"self",
".",
"source_field",
".",
"get_limit_choices_to",
"(",
")",
")",
"qs",
",",
"search_use_distinct",
"=",
"self",
".",
"model_admin",
".",
"get_search_results",
"(",
"self",
".",
"request",
",",
"qs",
",",
"self",
".",
"term",
")",
"if",
"search_use_distinct",
":",
"qs",
"=",
"qs",
".",
"distinct",
"(",
")",
"return",
"qs"
] | [
38,
4
] | [
45,
17
] | python | en | ['en', 'en', 'en'] | True |
AutocompleteJsonView.process_request | (self, request) |
Validate request integrity, extract and return request parameters.
Since the subsequent view permission check requires the target model
admin, which is determined here, raise PermissionDenied if the
requested app, model or field are malformed.
Raise Http404 if the target model admin is not configured properly with
search_fields.
|
Validate request integrity, extract and return request parameters. | def process_request(self, request):
"""
Validate request integrity, extract and return request parameters.
Since the subsequent view permission check requires the target model
admin, which is determined here, raise PermissionDenied if the
requested app, model or field are malformed.
Raise Http404 if the target model admin is not configured properly with
search_fields.
"""
term = request.GET.get('term', '')
try:
app_label = request.GET['app_label']
model_name = request.GET['model_name']
field_name = request.GET['field_name']
except KeyError as e:
raise PermissionDenied from e
# Retrieve objects from parameters.
try:
source_model = apps.get_model(app_label, model_name)
except LookupError as e:
raise PermissionDenied from e
try:
source_field = source_model._meta.get_field(field_name)
except FieldDoesNotExist as e:
raise PermissionDenied from e
try:
remote_model = source_field.remote_field.model
except AttributeError as e:
raise PermissionDenied from e
try:
model_admin = self.admin_site._registry[remote_model]
except KeyError as e:
raise PermissionDenied from e
# Validate suitability of objects.
if not model_admin.get_search_fields(request):
raise Http404(
'%s must have search_fields for the autocomplete_view.' %
type(model_admin).__qualname__
)
to_field_name = getattr(source_field.remote_field, 'field_name', remote_model._meta.pk.attname)
to_field_name = remote_model._meta.get_field(to_field_name).attname
if not model_admin.to_field_allowed(request, to_field_name):
raise PermissionDenied
return term, model_admin, source_field, to_field_name | [
"def",
"process_request",
"(",
"self",
",",
"request",
")",
":",
"term",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'term'",
",",
"''",
")",
"try",
":",
"app_label",
"=",
"request",
".",
"GET",
"[",
"'app_label'",
"]",
"model_name",
"=",
"request",
".",
"GET",
"[",
"'model_name'",
"]",
"field_name",
"=",
"request",
".",
"GET",
"[",
"'field_name'",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"PermissionDenied",
"from",
"e",
"# Retrieve objects from parameters.",
"try",
":",
"source_model",
"=",
"apps",
".",
"get_model",
"(",
"app_label",
",",
"model_name",
")",
"except",
"LookupError",
"as",
"e",
":",
"raise",
"PermissionDenied",
"from",
"e",
"try",
":",
"source_field",
"=",
"source_model",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"except",
"FieldDoesNotExist",
"as",
"e",
":",
"raise",
"PermissionDenied",
"from",
"e",
"try",
":",
"remote_model",
"=",
"source_field",
".",
"remote_field",
".",
"model",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"PermissionDenied",
"from",
"e",
"try",
":",
"model_admin",
"=",
"self",
".",
"admin_site",
".",
"_registry",
"[",
"remote_model",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"PermissionDenied",
"from",
"e",
"# Validate suitability of objects.",
"if",
"not",
"model_admin",
".",
"get_search_fields",
"(",
"request",
")",
":",
"raise",
"Http404",
"(",
"'%s must have search_fields for the autocomplete_view.'",
"%",
"type",
"(",
"model_admin",
")",
".",
"__qualname__",
")",
"to_field_name",
"=",
"getattr",
"(",
"source_field",
".",
"remote_field",
",",
"'field_name'",
",",
"remote_model",
".",
"_meta",
".",
"pk",
".",
"attname",
")",
"to_field_name",
"=",
"remote_model",
".",
"_meta",
".",
"get_field",
"(",
"to_field_name",
")",
".",
"attname",
"if",
"not",
"model_admin",
".",
"to_field_allowed",
"(",
"request",
",",
"to_field_name",
")",
":",
"raise",
"PermissionDenied",
"return",
"term",
",",
"model_admin",
",",
"source_field",
",",
"to_field_name"
] | [
47,
4
] | [
97,
61
] | python | en | ['en', 'error', 'th'] | False |
AutocompleteJsonView.has_perm | (self, request, obj=None) | Check if user has permission to access the related model. | Check if user has permission to access the related model. | def has_perm(self, request, obj=None):
"""Check if user has permission to access the related model."""
return self.model_admin.has_view_permission(request, obj=obj) | [
"def",
"has_perm",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
")",
":",
"return",
"self",
".",
"model_admin",
".",
"has_view_permission",
"(",
"request",
",",
"obj",
"=",
"obj",
")"
] | [
99,
4
] | [
101,
69
] | python | en | ['en', 'en', 'en'] | True |
DatabaseSchemaEditor._delete_composed_index | (self, model, fields, *args) |
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
We check here before removing the [unique|index]_together if we have to
recreate a FK index.
|
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
We check here before removing the [unique|index]_together if we have to
recreate a FK index.
| def _delete_composed_index(self, model, fields, *args):
"""
MySQL can remove an implicit FK index on a field when that field is
covered by another index like a unique_together. "covered" here means
that the more complex index starts like the simpler one.
http://bugs.mysql.com/bug.php?id=37910 / Django ticket #24757
We check here before removing the [unique|index]_together if we have to
recreate a FK index.
"""
first_field = model._meta.get_field(fields[0])
if first_field.get_internal_type() == 'ForeignKey':
constraint_names = self._constraint_names(model, [first_field.column], index=True)
if not constraint_names:
self.execute(
self._create_index_sql(model, fields=[first_field], suffix='')
)
return super()._delete_composed_index(model, fields, *args) | [
"def",
"_delete_composed_index",
"(",
"self",
",",
"model",
",",
"fields",
",",
"*",
"args",
")",
":",
"first_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
"(",
"fields",
"[",
"0",
"]",
")",
"if",
"first_field",
".",
"get_internal_type",
"(",
")",
"==",
"'ForeignKey'",
":",
"constraint_names",
"=",
"self",
".",
"_constraint_names",
"(",
"model",
",",
"[",
"first_field",
".",
"column",
"]",
",",
"index",
"=",
"True",
")",
"if",
"not",
"constraint_names",
":",
"self",
".",
"execute",
"(",
"self",
".",
"_create_index_sql",
"(",
"model",
",",
"fields",
"=",
"[",
"first_field",
"]",
",",
"suffix",
"=",
"''",
")",
")",
"return",
"super",
"(",
")",
".",
"_delete_composed_index",
"(",
"model",
",",
"fields",
",",
"*",
"args",
")"
] | [
123,
4
] | [
139,
67
] | python | en | ['en', 'error', 'th'] | False |
DatabaseSchemaEditor._set_field_new_type_null_status | (self, field, new_type) |
Keep the null property of the old field. If it has changed, it will be
handled separately.
|
Keep the null property of the old field. If it has changed, it will be
handled separately.
| def _set_field_new_type_null_status(self, field, new_type):
"""
Keep the null property of the old field. If it has changed, it will be
handled separately.
"""
if field.null:
new_type += " NULL"
else:
new_type += " NOT NULL"
return new_type | [
"def",
"_set_field_new_type_null_status",
"(",
"self",
",",
"field",
",",
"new_type",
")",
":",
"if",
"field",
".",
"null",
":",
"new_type",
"+=",
"\" NULL\"",
"else",
":",
"new_type",
"+=",
"\" NOT NULL\"",
"return",
"new_type"
] | [
141,
4
] | [
150,
23
] | python | en | ['en', 'error', 'th'] | False |
get_static_prefix | (parser, token) |
Populate a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
|
Populate a template variable with the static prefix,
``settings.STATIC_URL``. | def get_static_prefix(parser, token):
"""
Populate a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
"""
return PrefixNode.handle_token(parser, token, "STATIC_URL") | [
"def",
"get_static_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"STATIC_URL\"",
")"
] | [
57,
0
] | [
71,
63
] | python | en | ['en', 'error', 'th'] | False |
get_media_prefix | (parser, token) |
Populate a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
|
Populate a template variable with the media prefix,
``settings.MEDIA_URL``. | def get_media_prefix(parser, token):
"""
Populate a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle_token(parser, token, "MEDIA_URL") | [
"def",
"get_media_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"MEDIA_URL\"",
")"
] | [
75,
0
] | [
89,
62
] | python | en | ['en', 'error', 'th'] | False |
do_static | (parser, token) |
Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
|
Join the given path with the STATIC_URL setting. | def do_static(parser, token):
"""
Join the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
"""
return StaticNode.handle_token(parser, token) | [
"def",
"do_static",
"(",
"parser",
",",
"token",
")",
":",
"return",
"StaticNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
")"
] | [
143,
0
] | [
158,
49
] | python | en | ['en', 'error', 'th'] | False |
static | (path) |
Given a relative path to a static asset, return the absolute path to the
asset.
|
Given a relative path to a static asset, return the absolute path to the
asset.
| def static(path):
"""
Given a relative path to a static asset, return the absolute path to the
asset.
"""
return StaticNode.handle_simple(path) | [
"def",
"static",
"(",
"path",
")",
":",
"return",
"StaticNode",
".",
"handle_simple",
"(",
"path",
")"
] | [
161,
0
] | [
166,
41
] | python | en | ['en', 'error', 'th'] | False |
PrefixNode.handle_token | (cls, parser, token, name) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token, name):
"""
Class method to parse prefix node and return a Node.
"""
# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
tokens = token.contents.split()
if len(tokens) > 1 and tokens[1] != 'as':
raise template.TemplateSyntaxError(
"First argument in '%s' must be 'as'" % tokens[0])
if len(tokens) > 1:
varname = tokens[2]
else:
varname = None
return cls(varname, name) | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
",",
"name",
")",
":",
"# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments",
"tokens",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
"and",
"tokens",
"[",
"1",
"]",
"!=",
"'as'",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"First argument in '%s' must be 'as'\"",
"%",
"tokens",
"[",
"0",
"]",
")",
"if",
"len",
"(",
"tokens",
")",
">",
"1",
":",
"varname",
"=",
"tokens",
"[",
"2",
"]",
"else",
":",
"varname",
"=",
"None",
"return",
"cls",
"(",
"varname",
",",
"name",
")"
] | [
23,
4
] | [
36,
33
] | python | en | ['en', 'error', 'th'] | False |
StaticNode.handle_token | (cls, parser, token) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token):
"""
Class method to parse prefix node and return a Node.
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
"'%s' takes at least one argument (path to file)" % bits[0])
path = parser.compile_filter(bits[1])
if len(bits) >= 2 and bits[-2] == 'as':
varname = bits[3]
else:
varname = None
return cls(varname, path) | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one argument (path to file)\"",
"%",
"bits",
"[",
"0",
"]",
")",
"path",
"=",
"parser",
".",
"compile_filter",
"(",
"bits",
"[",
"1",
"]",
")",
"if",
"len",
"(",
"bits",
")",
">=",
"2",
"and",
"bits",
"[",
"-",
"2",
"]",
"==",
"'as'",
":",
"varname",
"=",
"bits",
"[",
"3",
"]",
"else",
":",
"varname",
"=",
"None",
"return",
"cls",
"(",
"varname",
",",
"path",
")"
] | [
122,
4
] | [
139,
33
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request | (self, method, url, fields=None, headers=None, **urlopen_kw) |
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be used in most situations, while still having the
option to drop down to more specific methods when necessary, such as
:meth:`request_encode_url`, :meth:`request_encode_body`,
or even the lowest level :meth:`urlopen`.
|
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used. | def request(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the appropriate encoding of
``fields`` based on the ``method`` used.
This is a convenience method that requires the least amount of manual
effort. It can be used in most situations, while still having the
option to drop down to more specific methods when necessary, such as
:meth:`request_encode_url`, :meth:`request_encode_body`,
or even the lowest level :meth:`urlopen`.
"""
method = method.upper()
urlopen_kw["request_url"] = url
if method in self._encode_url_methods:
return self.request_encode_url(
method, url, fields=fields, headers=headers, **urlopen_kw
)
else:
return self.request_encode_body(
method, url, fields=fields, headers=headers, **urlopen_kw
) | [
"def",
"request",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"method",
"=",
"method",
".",
"upper",
"(",
")",
"urlopen_kw",
"[",
"\"request_url\"",
"]",
"=",
"url",
"if",
"method",
"in",
"self",
".",
"_encode_url_methods",
":",
"return",
"self",
".",
"request_encode_url",
"(",
"method",
",",
"url",
",",
"fields",
"=",
"fields",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"urlopen_kw",
")",
"else",
":",
"return",
"self",
".",
"request_encode_body",
"(",
"method",
",",
"url",
",",
"fields",
"=",
"fields",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"urlopen_kw",
")"
] | [
57,
4
] | [
79,
13
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request_encode_url | (self, method, url, fields=None, headers=None, **urlopen_kw) |
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
|
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
| def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if headers is None:
headers = self.headers
extra_kw = {"headers": headers}
extra_kw.update(urlopen_kw)
if fields:
url += "?" + urlencode(fields)
return self.urlopen(method, url, **extra_kw) | [
"def",
"request_encode_url",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"self",
".",
"headers",
"extra_kw",
"=",
"{",
"\"headers\"",
":",
"headers",
"}",
"extra_kw",
".",
"update",
"(",
"urlopen_kw",
")",
"if",
"fields",
":",
"url",
"+=",
"\"?\"",
"+",
"urlencode",
"(",
"fields",
")",
"return",
"self",
".",
"urlopen",
"(",
"method",
",",
"url",
",",
"*",
"*",
"extra_kw",
")"
] | [
81,
4
] | [
95,
52
] | python | en | ['en', 'error', 'th'] | False |
RequestMethods.request_encode_body | (
self,
method,
url,
fields=None,
headers=None,
encode_multipart=True,
multipart_boundary=None,
**urlopen_kw
) |
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:func:`urllib3.encode_multipart_formdata` is used to encode
the payload with the appropriate content type. Otherwise
:func:`urllib.parse.urlencode` is used with the
'application/x-www-form-urlencoded' content type.
Multipart encoding must be used when posting files, and it's reasonably
safe to use it in other times too. However, it may break request
signing, such as with OAuth.
Supports an optional ``fields`` parameter of key/value strings AND
key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
the MIME type is optional. For example::
fields = {
'foo': 'bar',
'fakefile': ('foofile.txt', 'contents of foofile'),
'realfile': ('barfile.txt', open('realfile').read()),
'typedfile': ('bazfile.bin', open('bazfile').read(),
'image/jpeg'),
'nonamefile': 'contents of nonamefile field',
}
When uploading a file, providing a filename (the first parameter of the
tuple) is optional but recommended to best mimic behavior of browsers.
Note that if ``headers`` are supplied, the 'Content-Type' header will
be overwritten because it depends on the dynamic random boundary string
which is used to compose the body of the request. The random boundary
string can be explicitly set with the ``multipart_boundary`` parameter.
|
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc. | def request_encode_body(
self,
method,
url,
fields=None,
headers=None,
encode_multipart=True,
multipart_boundary=None,
**urlopen_kw
):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the body. This is useful for request methods like POST, PUT, PATCH, etc.
When ``encode_multipart=True`` (default), then
:func:`urllib3.encode_multipart_formdata` is used to encode
the payload with the appropriate content type. Otherwise
:func:`urllib.parse.urlencode` is used with the
'application/x-www-form-urlencoded' content type.
Multipart encoding must be used when posting files, and it's reasonably
safe to use it in other times too. However, it may break request
signing, such as with OAuth.
Supports an optional ``fields`` parameter of key/value strings AND
key/filetuple. A filetuple is a (filename, data, MIME type) tuple where
the MIME type is optional. For example::
fields = {
'foo': 'bar',
'fakefile': ('foofile.txt', 'contents of foofile'),
'realfile': ('barfile.txt', open('realfile').read()),
'typedfile': ('bazfile.bin', open('bazfile').read(),
'image/jpeg'),
'nonamefile': 'contents of nonamefile field',
}
When uploading a file, providing a filename (the first parameter of the
tuple) is optional but recommended to best mimic behavior of browsers.
Note that if ``headers`` are supplied, the 'Content-Type' header will
be overwritten because it depends on the dynamic random boundary string
which is used to compose the body of the request. The random boundary
string can be explicitly set with the ``multipart_boundary`` parameter.
"""
if headers is None:
headers = self.headers
extra_kw = {"headers": {}}
if fields:
if "body" in urlopen_kw:
raise TypeError(
"request got values for both 'fields' and 'body', can only specify one."
)
if encode_multipart:
body, content_type = encode_multipart_formdata(
fields, boundary=multipart_boundary
)
else:
body, content_type = (
urlencode(fields),
"application/x-www-form-urlencoded",
)
extra_kw["body"] = body
extra_kw["headers"] = {"Content-Type": content_type}
extra_kw["headers"].update(headers)
extra_kw.update(urlopen_kw)
return self.urlopen(method, url, **extra_kw) | [
"def",
"request_encode_body",
"(",
"self",
",",
"method",
",",
"url",
",",
"fields",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"encode_multipart",
"=",
"True",
",",
"multipart_boundary",
"=",
"None",
",",
"*",
"*",
"urlopen_kw",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"self",
".",
"headers",
"extra_kw",
"=",
"{",
"\"headers\"",
":",
"{",
"}",
"}",
"if",
"fields",
":",
"if",
"\"body\"",
"in",
"urlopen_kw",
":",
"raise",
"TypeError",
"(",
"\"request got values for both 'fields' and 'body', can only specify one.\"",
")",
"if",
"encode_multipart",
":",
"body",
",",
"content_type",
"=",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"multipart_boundary",
")",
"else",
":",
"body",
",",
"content_type",
"=",
"(",
"urlencode",
"(",
"fields",
")",
",",
"\"application/x-www-form-urlencoded\"",
",",
")",
"extra_kw",
"[",
"\"body\"",
"]",
"=",
"body",
"extra_kw",
"[",
"\"headers\"",
"]",
"=",
"{",
"\"Content-Type\"",
":",
"content_type",
"}",
"extra_kw",
"[",
"\"headers\"",
"]",
".",
"update",
"(",
"headers",
")",
"extra_kw",
".",
"update",
"(",
"urlopen_kw",
")",
"return",
"self",
".",
"urlopen",
"(",
"method",
",",
"url",
",",
"*",
"*",
"extra_kw",
")"
] | [
97,
4
] | [
169,
52
] | python | en | ['en', 'error', 'th'] | False |
indent_log | (num=2) |
A context manager which will cause the log output to be indented for any
log messages emitted inside it.
|
A context manager which will cause the log output to be indented for any
log messages emitted inside it.
| def indent_log(num=2):
# type: (int) -> Iterator[None]
"""
A context manager which will cause the log output to be indented for any
log messages emitted inside it.
"""
# For thread-safety
_log_state.indentation = get_indentation()
_log_state.indentation += num
try:
yield
finally:
_log_state.indentation -= num | [
"def",
"indent_log",
"(",
"num",
"=",
"2",
")",
":",
"# type: (int) -> Iterator[None]",
"# For thread-safety",
"_log_state",
".",
"indentation",
"=",
"get_indentation",
"(",
")",
"_log_state",
".",
"indentation",
"+=",
"num",
"try",
":",
"yield",
"finally",
":",
"_log_state",
".",
"indentation",
"-=",
"num"
] | [
68,
0
] | [
80,
37
] | python | en | ['en', 'error', 'th'] | False |
setup_logging | (verbosity, no_color, user_log_file) | Configures and sets up all of the logging
Returns the requested logging level, as its integer value.
| Configures and sets up all of the logging | def setup_logging(verbosity, no_color, user_log_file):
# type: (int, bool, Optional[str]) -> int
"""Configures and sets up all of the logging
Returns the requested logging level, as its integer value.
"""
# Determine the level to be logging at.
if verbosity >= 2:
level_number = logging.DEBUG
elif verbosity == 1:
level_number = VERBOSE
elif verbosity == -1:
level_number = logging.WARNING
elif verbosity == -2:
level_number = logging.ERROR
elif verbosity <= -3:
level_number = logging.CRITICAL
else:
level_number = logging.INFO
level = logging.getLevelName(level_number)
# The "root" logger should match the "console" level *unless* we also need
# to log to a user log file.
include_user_log = user_log_file is not None
if include_user_log:
additional_log_file = user_log_file
root_level = "DEBUG"
else:
additional_log_file = "/dev/null"
root_level = level
# Disable any logging besides WARNING unless we have DEBUG level logging
# enabled for vendored libraries.
vendored_log_level = "WARNING" if level in ["INFO", "ERROR"] else "DEBUG"
# Shorthands for clarity
log_streams = {
"stdout": "ext://sys.stdout",
"stderr": "ext://sys.stderr",
}
handler_classes = {
"stream": "pip._internal.utils.logging.ColorizedStreamHandler",
"file": "pip._internal.utils.logging.BetterRotatingFileHandler",
}
handlers = ["console", "console_errors", "console_subprocess"] + (
["user_log"] if include_user_log else []
)
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"filters": {
"exclude_warnings": {
"()": "pip._internal.utils.logging.MaxLevelFilter",
"level": logging.WARNING,
},
"restrict_to_subprocess": {
"()": "logging.Filter",
"name": subprocess_logger.name,
},
"exclude_subprocess": {
"()": "pip._internal.utils.logging.ExcludeLoggerFilter",
"name": subprocess_logger.name,
},
},
"formatters": {
"indent": {
"()": IndentingFormatter,
"format": "%(message)s",
},
"indent_with_timestamp": {
"()": IndentingFormatter,
"format": "%(message)s",
"add_timestamp": True,
},
},
"handlers": {
"console": {
"level": level,
"class": handler_classes["stream"],
"no_color": no_color,
"stream": log_streams["stdout"],
"filters": ["exclude_subprocess", "exclude_warnings"],
"formatter": "indent",
},
"console_errors": {
"level": "WARNING",
"class": handler_classes["stream"],
"no_color": no_color,
"stream": log_streams["stderr"],
"filters": ["exclude_subprocess"],
"formatter": "indent",
},
# A handler responsible for logging to the console messages
# from the "subprocessor" logger.
"console_subprocess": {
"level": level,
"class": handler_classes["stream"],
"no_color": no_color,
"stream": log_streams["stderr"],
"filters": ["restrict_to_subprocess"],
"formatter": "indent",
},
"user_log": {
"level": "DEBUG",
"class": handler_classes["file"],
"filename": additional_log_file,
"encoding": "utf-8",
"delay": True,
"formatter": "indent_with_timestamp",
},
},
"root": {
"level": root_level,
"handlers": handlers,
},
"loggers": {"pip._vendor": {"level": vendored_log_level}},
}
)
return level_number | [
"def",
"setup_logging",
"(",
"verbosity",
",",
"no_color",
",",
"user_log_file",
")",
":",
"# type: (int, bool, Optional[str]) -> int",
"# Determine the level to be logging at.",
"if",
"verbosity",
">=",
"2",
":",
"level_number",
"=",
"logging",
".",
"DEBUG",
"elif",
"verbosity",
"==",
"1",
":",
"level_number",
"=",
"VERBOSE",
"elif",
"verbosity",
"==",
"-",
"1",
":",
"level_number",
"=",
"logging",
".",
"WARNING",
"elif",
"verbosity",
"==",
"-",
"2",
":",
"level_number",
"=",
"logging",
".",
"ERROR",
"elif",
"verbosity",
"<=",
"-",
"3",
":",
"level_number",
"=",
"logging",
".",
"CRITICAL",
"else",
":",
"level_number",
"=",
"logging",
".",
"INFO",
"level",
"=",
"logging",
".",
"getLevelName",
"(",
"level_number",
")",
"# The \"root\" logger should match the \"console\" level *unless* we also need",
"# to log to a user log file.",
"include_user_log",
"=",
"user_log_file",
"is",
"not",
"None",
"if",
"include_user_log",
":",
"additional_log_file",
"=",
"user_log_file",
"root_level",
"=",
"\"DEBUG\"",
"else",
":",
"additional_log_file",
"=",
"\"/dev/null\"",
"root_level",
"=",
"level",
"# Disable any logging besides WARNING unless we have DEBUG level logging",
"# enabled for vendored libraries.",
"vendored_log_level",
"=",
"\"WARNING\"",
"if",
"level",
"in",
"[",
"\"INFO\"",
",",
"\"ERROR\"",
"]",
"else",
"\"DEBUG\"",
"# Shorthands for clarity",
"log_streams",
"=",
"{",
"\"stdout\"",
":",
"\"ext://sys.stdout\"",
",",
"\"stderr\"",
":",
"\"ext://sys.stderr\"",
",",
"}",
"handler_classes",
"=",
"{",
"\"stream\"",
":",
"\"pip._internal.utils.logging.ColorizedStreamHandler\"",
",",
"\"file\"",
":",
"\"pip._internal.utils.logging.BetterRotatingFileHandler\"",
",",
"}",
"handlers",
"=",
"[",
"\"console\"",
",",
"\"console_errors\"",
",",
"\"console_subprocess\"",
"]",
"+",
"(",
"[",
"\"user_log\"",
"]",
"if",
"include_user_log",
"else",
"[",
"]",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"\"version\"",
":",
"1",
",",
"\"disable_existing_loggers\"",
":",
"False",
",",
"\"filters\"",
":",
"{",
"\"exclude_warnings\"",
":",
"{",
"\"()\"",
":",
"\"pip._internal.utils.logging.MaxLevelFilter\"",
",",
"\"level\"",
":",
"logging",
".",
"WARNING",
",",
"}",
",",
"\"restrict_to_subprocess\"",
":",
"{",
"\"()\"",
":",
"\"logging.Filter\"",
",",
"\"name\"",
":",
"subprocess_logger",
".",
"name",
",",
"}",
",",
"\"exclude_subprocess\"",
":",
"{",
"\"()\"",
":",
"\"pip._internal.utils.logging.ExcludeLoggerFilter\"",
",",
"\"name\"",
":",
"subprocess_logger",
".",
"name",
",",
"}",
",",
"}",
",",
"\"formatters\"",
":",
"{",
"\"indent\"",
":",
"{",
"\"()\"",
":",
"IndentingFormatter",
",",
"\"format\"",
":",
"\"%(message)s\"",
",",
"}",
",",
"\"indent_with_timestamp\"",
":",
"{",
"\"()\"",
":",
"IndentingFormatter",
",",
"\"format\"",
":",
"\"%(message)s\"",
",",
"\"add_timestamp\"",
":",
"True",
",",
"}",
",",
"}",
",",
"\"handlers\"",
":",
"{",
"\"console\"",
":",
"{",
"\"level\"",
":",
"level",
",",
"\"class\"",
":",
"handler_classes",
"[",
"\"stream\"",
"]",
",",
"\"no_color\"",
":",
"no_color",
",",
"\"stream\"",
":",
"log_streams",
"[",
"\"stdout\"",
"]",
",",
"\"filters\"",
":",
"[",
"\"exclude_subprocess\"",
",",
"\"exclude_warnings\"",
"]",
",",
"\"formatter\"",
":",
"\"indent\"",
",",
"}",
",",
"\"console_errors\"",
":",
"{",
"\"level\"",
":",
"\"WARNING\"",
",",
"\"class\"",
":",
"handler_classes",
"[",
"\"stream\"",
"]",
",",
"\"no_color\"",
":",
"no_color",
",",
"\"stream\"",
":",
"log_streams",
"[",
"\"stderr\"",
"]",
",",
"\"filters\"",
":",
"[",
"\"exclude_subprocess\"",
"]",
",",
"\"formatter\"",
":",
"\"indent\"",
",",
"}",
",",
"# A handler responsible for logging to the console messages",
"# from the \"subprocessor\" logger.",
"\"console_subprocess\"",
":",
"{",
"\"level\"",
":",
"level",
",",
"\"class\"",
":",
"handler_classes",
"[",
"\"stream\"",
"]",
",",
"\"no_color\"",
":",
"no_color",
",",
"\"stream\"",
":",
"log_streams",
"[",
"\"stderr\"",
"]",
",",
"\"filters\"",
":",
"[",
"\"restrict_to_subprocess\"",
"]",
",",
"\"formatter\"",
":",
"\"indent\"",
",",
"}",
",",
"\"user_log\"",
":",
"{",
"\"level\"",
":",
"\"DEBUG\"",
",",
"\"class\"",
":",
"handler_classes",
"[",
"\"file\"",
"]",
",",
"\"filename\"",
":",
"additional_log_file",
",",
"\"encoding\"",
":",
"\"utf-8\"",
",",
"\"delay\"",
":",
"True",
",",
"\"formatter\"",
":",
"\"indent_with_timestamp\"",
",",
"}",
",",
"}",
",",
"\"root\"",
":",
"{",
"\"level\"",
":",
"root_level",
",",
"\"handlers\"",
":",
"handlers",
",",
"}",
",",
"\"loggers\"",
":",
"{",
"\"pip._vendor\"",
":",
"{",
"\"level\"",
":",
"vendored_log_level",
"}",
"}",
",",
"}",
")",
"return",
"level_number"
] | [
267,
0
] | [
390,
23
] | python | en | ['en', 'en', 'en'] | True |
IndentingFormatter.__init__ | (
self,
*args, # type: Any
add_timestamp=False, # type: bool
**kwargs, # type: Any
) |
A logging.Formatter that obeys the indent_log() context manager.
:param add_timestamp: A bool indicating output lines should be prefixed
with their record's timestamp.
|
A logging.Formatter that obeys the indent_log() context manager. | def __init__(
self,
*args, # type: Any
add_timestamp=False, # type: bool
**kwargs, # type: Any
):
# type: (...) -> None
"""
A logging.Formatter that obeys the indent_log() context manager.
:param add_timestamp: A bool indicating output lines should be prefixed
with their record's timestamp.
"""
self.add_timestamp = add_timestamp
super().__init__(*args, **kwargs) | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"# type: Any",
"add_timestamp",
"=",
"False",
",",
"# type: bool",
"*",
"*",
"kwargs",
",",
"# type: Any",
")",
":",
"# type: (...) -> None",
"self",
".",
"add_timestamp",
"=",
"add_timestamp",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
91,
4
] | [
105,
41
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.