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
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
wordwrap
(value, arg)
Wrap words at `arg` line length.
Wrap words at `arg` line length.
def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg))
[ "def", "wordwrap", "(", "value", ",", "arg", ")", ":", "return", "wrap", "(", "value", ",", "int", "(", "arg", ")", ")" ]
[ 351, 0 ]
[ 353, 32 ]
python
en
['en', 'en', 'en']
True
ljust
(value, arg)
Left-align the value in a field of a given width.
Left-align the value in a field of a given width.
def ljust(value, arg): """Left-align the value in a field of a given width.""" return value.ljust(int(arg))
[ "def", "ljust", "(", "value", ",", "arg", ")", ":", "return", "value", ".", "ljust", "(", "int", "(", "arg", ")", ")" ]
[ 358, 0 ]
[ 360, 32 ]
python
en
['en', 'en', 'en']
True
rjust
(value, arg)
Right-align the value in a field of a given width.
Right-align the value in a field of a given width.
def rjust(value, arg): """Right-align the value in a field of a given width.""" return value.rjust(int(arg))
[ "def", "rjust", "(", "value", ",", "arg", ")", ":", "return", "value", ".", "rjust", "(", "int", "(", "arg", ")", ")" ]
[ 365, 0 ]
[ 367, 32 ]
python
en
['en', 'en', 'en']
True
center
(value, arg)
Center the value in a field of a given width.
Center the value in a field of a given width.
def center(value, arg): """Center the value in a field of a given width.""" return value.center(int(arg))
[ "def", "center", "(", "value", ",", "arg", ")", ":", "return", "value", ".", "center", "(", "int", "(", "arg", ")", ")" ]
[ 372, 0 ]
[ 374, 33 ]
python
en
['en', 'en', 'en']
True
cut
(value, arg)
Remove all values of arg from the given string.
Remove all values of arg from the given string.
def cut(value, arg): """Remove all values of arg from the given string.""" safe = isinstance(value, SafeData) value = value.replace(arg, '') if safe and arg != ';': return mark_safe(value) return value
[ "def", "cut", "(", "value", ",", "arg", ")", ":", "safe", "=", "isinstance", "(", "value", ",", "SafeData", ")", "value", "=", "value", ".", "replace", "(", "arg", ",", "''", ")", "if", "safe", "and", "arg", "!=", "';'", ":", "return", "mark_safe",...
[ 379, 0 ]
[ 385, 16 ]
python
en
['en', 'en', 'en']
True
escape_filter
(value)
Mark the value as a string that should be auto-escaped.
Mark the value as a string that should be auto-escaped.
def escape_filter(value): """Mark the value as a string that should be auto-escaped.""" return conditional_escape(value)
[ "def", "escape_filter", "(", "value", ")", ":", "return", "conditional_escape", "(", "value", ")" ]
[ 394, 0 ]
[ 396, 36 ]
python
en
['en', 'en', 'en']
True
force_escape
(value)
Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping).
Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping).
def force_escape(value): """ Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value)
[ "def", "force_escape", "(", "value", ")", ":", "return", "escape", "(", "value", ")" ]
[ 401, 0 ]
[ 407, 24 ]
python
en
['en', 'error', 'th']
False
linebreaks_filter
(value, autoescape=True)
Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``).
Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``).
def linebreaks_filter(value, autoescape=True): """ Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, S...
[ "def", "linebreaks_filter", "(", "value", ",", "autoescape", "=", "True", ")", ":", "autoescape", "=", "autoescape", "and", "not", "isinstance", "(", "value", ",", "SafeData", ")", "return", "mark_safe", "(", "linebreaks", "(", "value", ",", "autoescape", ")...
[ 412, 0 ]
[ 419, 51 ]
python
en
['en', 'error', 'th']
False
linebreaksbr
(value, autoescape=True)
Convert all newlines in a piece of plain text to HTML line breaks (``<br>``).
Convert all newlines in a piece of plain text to HTML line breaks (``<br>``).
def linebreaksbr(value, autoescape=True): """ Convert all newlines in a piece of plain text to HTML line breaks (``<br>``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(valu...
[ "def", "linebreaksbr", "(", "value", ",", "autoescape", "=", "True", ")", ":", "autoescape", "=", "autoescape", "and", "not", "isinstance", "(", "value", ",", "SafeData", ")", "value", "=", "normalize_newlines", "(", "value", ")", "if", "autoescape", ":", ...
[ 424, 0 ]
[ 433, 49 ]
python
en
['en', 'error', 'th']
False
safe
(value)
Mark the value as a string that should not be auto-escaped.
Mark the value as a string that should not be auto-escaped.
def safe(value): """Mark the value as a string that should not be auto-escaped.""" return mark_safe(value)
[ "def", "safe", "(", "value", ")", ":", "return", "mark_safe", "(", "value", ")" ]
[ 438, 0 ]
[ 440, 27 ]
python
en
['en', 'en', 'en']
True
safeseq
(value)
A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results.
A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results.
def safeseq(value): """ A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. """ return [mark_safe(obj) for obj in value]
[ "def", "safeseq", "(", "value", ")", ":", "return", "[", "mark_safe", "(", "obj", ")", "for", "obj", "in", "value", "]" ]
[ 444, 0 ]
[ 450, 44 ]
python
en
['en', 'error', 'th']
False
striptags
(value)
Strip all [X]HTML tags.
Strip all [X]HTML tags.
def striptags(value): """Strip all [X]HTML tags.""" return strip_tags(value)
[ "def", "striptags", "(", "value", ")", ":", "return", "strip_tags", "(", "value", ")" ]
[ 455, 0 ]
[ 457, 28 ]
python
en
['en', 'mt', 'en']
True
_property_resolver
(arg)
When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Fo...
When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve
def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indic...
[ "def", "_property_resolver", "(", "arg", ")", ":", "try", ":", "float", "(", "arg", ")", "except", "ValueError", ":", "return", "Variable", "(", "arg", ")", ".", "resolve", "else", ":", "return", "itemgetter", "(", "arg", ")" ]
[ 464, 0 ]
[ 487, 30 ]
python
en
['en', 'error', 'th']
False
dictsort
(value, arg)
Given a list of dicts, return that list sorted by the property given in the argument.
Given a list of dicts, return that list sorted by the property given in the argument.
def dictsort(value, arg): """ Given a list of dicts, return that list sorted by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg)) except (TypeError, VariableDoesNotExist): return ''
[ "def", "dictsort", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "sorted", "(", "value", ",", "key", "=", "_property_resolver", "(", "arg", ")", ")", "except", "(", "TypeError", ",", "VariableDoesNotExist", ")", ":", "return", "''" ]
[ 491, 0 ]
[ 499, 17 ]
python
en
['en', 'error', 'th']
False
dictsortreversed
(value, arg)
Given a list of dicts, return that list sorted in reverse order by the property given in the argument.
Given a list of dicts, return that list sorted in reverse order by the property given in the argument.
def dictsortreversed(value, arg): """ Given a list of dicts, return that list sorted in reverse order by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (TypeError, VariableDoesNotExist): return ''
[ "def", "dictsortreversed", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "sorted", "(", "value", ",", "key", "=", "_property_resolver", "(", "arg", ")", ",", "reverse", "=", "True", ")", "except", "(", "TypeError", ",", "VariableDoesNotExist", ...
[ 503, 0 ]
[ 511, 17 ]
python
en
['en', 'error', 'th']
False
first
(value)
Return the first item in a list.
Return the first item in a list.
def first(value): """Return the first item in a list.""" try: return value[0] except IndexError: return ''
[ "def", "first", "(", "value", ")", ":", "try", ":", "return", "value", "[", "0", "]", "except", "IndexError", ":", "return", "''" ]
[ 515, 0 ]
[ 520, 17 ]
python
en
['en', 'en', 'en']
True
join
(value, arg, autoescape=True)
Join a list with a string, like Python's ``str.join(list)``.
Join a list with a string, like Python's ``str.join(list)``.
def join(value, arg, autoescape=True): """Join a list with a string, like Python's ``str.join(list)``.""" try: if autoescape: value = [conditional_escape(v) for v in value] data = conditional_escape(arg).join(value) except TypeError: # Fail silently if arg isn't iterable. ...
[ "def", "join", "(", "value", ",", "arg", ",", "autoescape", "=", "True", ")", ":", "try", ":", "if", "autoescape", ":", "value", "=", "[", "conditional_escape", "(", "v", ")", "for", "v", "in", "value", "]", "data", "=", "conditional_escape", "(", "a...
[ 524, 0 ]
[ 532, 26 ]
python
en
['en', 'en', 'en']
True
last
(value)
Return the last item in a list.
Return the last item in a list.
def last(value): """Return the last item in a list.""" try: return value[-1] except IndexError: return ''
[ "def", "last", "(", "value", ")", ":", "try", ":", "return", "value", "[", "-", "1", "]", "except", "IndexError", ":", "return", "''" ]
[ 536, 0 ]
[ 541, 17 ]
python
en
['en', 'en', 'en']
True
length
(value)
Return the length of the value - useful for lists.
Return the length of the value - useful for lists.
def length(value): """Return the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return 0
[ "def", "length", "(", "value", ")", ":", "try", ":", "return", "len", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "0" ]
[ 545, 0 ]
[ 550, 16 ]
python
en
['en', 'en', 'en']
True
length_is
(value, arg)
Return a boolean of whether the value's length is the argument.
Return a boolean of whether the value's length is the argument.
def length_is(value, arg): """Return a boolean of whether the value's length is the argument.""" try: return len(value) == int(arg) except (ValueError, TypeError): return ''
[ "def", "length_is", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "len", "(", "value", ")", "==", "int", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", "''" ]
[ 554, 0 ]
[ 559, 17 ]
python
en
['en', 'en', 'en']
True
random
(value)
Return a random item from the list.
Return a random item from the list.
def random(value): """Return a random item from the list.""" return random_module.choice(value)
[ "def", "random", "(", "value", ")", ":", "return", "random_module", ".", "choice", "(", "value", ")" ]
[ 563, 0 ]
[ 565, 38 ]
python
en
['en', 'mt', 'en']
True
slice_filter
(value, arg)
Return a slice of the list using the same syntax as Python's list slicing.
Return a slice of the list using the same syntax as Python's list slicing.
def slice_filter(value, arg): """ Return a slice of the list using the same syntax as Python's list slicing. """ try: bits = [] for x in str(arg).split(':'): if not x: bits.append(None) else: bits.append(int(x)) return value...
[ "def", "slice_filter", "(", "value", ",", "arg", ")", ":", "try", ":", "bits", "=", "[", "]", "for", "x", "in", "str", "(", "arg", ")", ".", "split", "(", "':'", ")", ":", "if", "not", "x", ":", "bits", ".", "append", "(", "None", ")", "else"...
[ 569, 0 ]
[ 583, 20 ]
python
en
['en', 'error', 'th']
False
unordered_list
(value, autoescape=True)
Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` returns:: ...
Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags.
def unordered_list(value, autoescape=True): """ Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, ...
[ "def", "unordered_list", "(", "value", ",", "autoescape", "=", "True", ")", ":", "if", "autoescape", ":", "escaper", "=", "conditional_escape", "else", ":", "def", "escaper", "(", "x", ")", ":", "return", "x", "def", "walk_items", "(", "item_list", ")", ...
[ 587, 0 ]
[ 650, 43 ]
python
en
['en', 'error', 'th']
False
add
(value, arg)
Add the arg to the value.
Add the arg to the value.
def add(value, arg): """Add the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except Exception: return ''
[ "def", "add", "(", "value", ",", "arg", ")", ":", "try", ":", "return", "int", "(", "value", ")", "+", "int", "(", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "try", ":", "return", "value", "+", "arg", "except", "Exception"...
[ 658, 0 ]
[ 666, 21 ]
python
en
['en', 'en', 'en']
True
get_digit
(value, arg)
Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer.
Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer.
def get_digit(value, arg): """ Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is alw...
[ "def", "get_digit", "(", "value", ",", "arg", ")", ":", "try", ":", "arg", "=", "int", "(", "arg", ")", "value", "=", "int", "(", "value", ")", "except", "ValueError", ":", "return", "value", "# Fail silently for an invalid argument", "if", "arg", "<", "...
[ 670, 0 ]
[ 687, 16 ]
python
en
['en', 'error', 'th']
False
date
(value, arg=None)
Format a date according to the given format.
Format a date according to the given format.
def date(value, arg=None): """Format a date according to the given format.""" if value in (None, ''): return '' try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return ''
[ "def", "date", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "value", "in", "(", "None", ",", "''", ")", ":", "return", "''", "try", ":", "return", "formats", ".", "date_format", "(", "value", ",", "arg", ")", "except", "AttributeError", "...
[ 695, 0 ]
[ 705, 21 ]
python
en
['en', 'en', 'en']
True
time
(value, arg=None)
Format a time according to the given format.
Format a time according to the given format.
def time(value, arg=None): """Format a time according to the given format.""" if value in (None, ''): return '' try: return formats.time_format(value, arg) except (AttributeError, TypeError): try: return time_format(value, arg) except (AttributeError, TypeErro...
[ "def", "time", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "value", "in", "(", "None", ",", "''", ")", ":", "return", "''", "try", ":", "return", "formats", ".", "time_format", "(", "value", ",", "arg", ")", "except", "(", "AttributeErro...
[ 709, 0 ]
[ 719, 21 ]
python
en
['en', 'en', 'en']
True
timesince_filter
(value, arg=None)
Format a date as the time since that date (i.e. "4 days, 6 hours").
Format a date as the time since that date (i.e. "4 days, 6 hours").
def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return '' try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return ''
[ "def", "timesince_filter", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "not", "value", ":", "return", "''", "try", ":", "if", "arg", ":", "return", "timesince", "(", "value", ",", "arg", ")", "return", "timesince", "(", "value", ")", "exce...
[ 723, 0 ]
[ 732, 17 ]
python
en
['en', 'en', 'en']
True
timeuntil_filter
(value, arg=None)
Format a date as the time until that date (i.e. "4 days, 6 hours").
Format a date as the time until that date (i.e. "4 days, 6 hours").
def timeuntil_filter(value, arg=None): """Format a date as the time until that date (i.e. "4 days, 6 hours").""" if not value: return '' try: return timeuntil(value, arg) except (ValueError, TypeError): return ''
[ "def", "timeuntil_filter", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "not", "value", ":", "return", "''", "try", ":", "return", "timeuntil", "(", "value", ",", "arg", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "return", ...
[ 736, 0 ]
[ 743, 17 ]
python
en
['en', 'en', 'en']
True
default
(value, arg)
If value is unavailable, use given default.
If value is unavailable, use given default.
def default(value, arg): """If value is unavailable, use given default.""" return value or arg
[ "def", "default", "(", "value", ",", "arg", ")", ":", "return", "value", "or", "arg" ]
[ 751, 0 ]
[ 753, 23 ]
python
en
['en', 'en', 'en']
True
default_if_none
(value, arg)
If value is None, use given default.
If value is None, use given default.
def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value
[ "def", "default_if_none", "(", "value", ",", "arg", ")", ":", "if", "value", "is", "None", ":", "return", "arg", "return", "value" ]
[ 757, 0 ]
[ 761, 16 ]
python
en
['en', 'en', 'en']
True
divisibleby
(value, arg)
Return True if the value is divisible by the argument.
Return True if the value is divisible by the argument.
def divisibleby(value, arg): """Return True if the value is divisible by the argument.""" return int(value) % int(arg) == 0
[ "def", "divisibleby", "(", "value", ",", "arg", ")", ":", "return", "int", "(", "value", ")", "%", "int", "(", "arg", ")", "==", "0" ]
[ 765, 0 ]
[ 767, 37 ]
python
en
['en', 'en', 'en']
True
yesno
(value, arg=None)
Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== =========================...
Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value:
def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ==============...
[ "def", "yesno", "(", "value", ",", "arg", "=", "None", ")", ":", "if", "arg", "is", "None", ":", "arg", "=", "gettext", "(", "'yes,no,maybe'", ")", "bits", "=", "arg", ".", "split", "(", "','", ")", "if", "len", "(", "bits", ")", "<", "2", ":",...
[ 771, 0 ]
[ 800, 13 ]
python
en
['en', 'error', 'th']
False
filesizeformat
(bytes_)
Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.).
Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.).
def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = int(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {'size': 0} ...
[ "def", "filesizeformat", "(", "bytes_", ")", ":", "try", ":", "bytes_", "=", "int", "(", "bytes_", ")", "except", "(", "TypeError", ",", "ValueError", ",", "UnicodeDecodeError", ")", ":", "value", "=", "ngettext", "(", "\"%(size)d byte\"", ",", "\"%(size)d b...
[ 808, 0 ]
[ 847, 32 ]
python
en
['en', 'error', 'th']
False
pluralize
(value, arg='s')
Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value|pluralize }} display "votes". If...
Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix:
def pluralize(value, arg='s'): """ Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value...
[ "def", "pluralize", "(", "value", ",", "arg", "=", "'s'", ")", ":", "if", "','", "not", "in", "arg", ":", "arg", "=", "','", "+", "arg", "bits", "=", "arg", ".", "split", "(", "','", ")", "if", "len", "(", "bits", ")", ">", "2", ":", "return"...
[ 851, 0 ]
[ 889, 13 ]
python
en
['en', 'error', 'th']
False
phone2numeric_filter
(value)
Take a phone number and converts it in to its numerical equivalent.
Take a phone number and converts it in to its numerical equivalent.
def phone2numeric_filter(value): """Take a phone number and converts it in to its numerical equivalent.""" return phone2numeric(value)
[ "def", "phone2numeric_filter", "(", "value", ")", ":", "return", "phone2numeric", "(", "value", ")" ]
[ 893, 0 ]
[ 895, 31 ]
python
en
['en', 'en', 'en']
True
pprint
(value)
A wrapper around pprint.pprint -- for debugging, really.
A wrapper around pprint.pprint -- for debugging, really.
def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) except Exception as e: return "Error in formatting: %s: %s" % (e.__class__.__name__, e)
[ "def", "pprint", "(", "value", ")", ":", "try", ":", "return", "pformat", "(", "value", ")", "except", "Exception", "as", "e", ":", "return", "\"Error in formatting: %s: %s\"", "%", "(", "e", ".", "__class__", ".", "__name__", ",", "e", ")" ]
[ 899, 0 ]
[ 904, 72 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.__iter__
(self)
This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested.
This is where the magic happens.
def __iter__(self): """ This is where the magic happens. We do our usually processing through the states and when we have a token to return we yield the token which pauses processing until the next token is requested. """ self.tokenQueue = deque([]) # Start proce...
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "tokenQueue", "=", "deque", "(", "[", "]", ")", "# Start processing. When EOF is reached self.state will return False", "# instead of True and the loop will terminate.", "while", "self", ".", "state", "(", ")", ":",...
[ 48, 4 ]
[ 62, 47 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.consumeNumberEntity
(self, isHex)
This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked.
def consumeNumberEntity(self, isHex): """This function returns either U+FFFD or the character based on the decimal or hexadecimal representation. It also discards ";" if present. If not present self.tokenQueue.append({"type": tokenTypes["ParseError"]}) is invoked. """ allowed = ...
[ "def", "consumeNumberEntity", "(", "self", ",", "isHex", ")", ":", "allowed", "=", "digits", "radix", "=", "10", "if", "isHex", ":", "allowed", "=", "hexDigits", "radix", "=", "16", "charStack", "=", "[", "]", "# Consume all the characters that are in range whil...
[ 64, 4 ]
[ 134, 19 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.processEntityInAttribute
(self, allowedChar)
This method replaces the need for "entityInAttributeValueState".
This method replaces the need for "entityInAttributeValueState".
def processEntityInAttribute(self, allowedChar): """This method replaces the need for "entityInAttributeValueState". """ self.consumeEntity(allowedChar=allowedChar, fromAttribute=True)
[ "def", "processEntityInAttribute", "(", "self", ",", "allowedChar", ")", ":", "self", ".", "consumeEntity", "(", "allowedChar", "=", "allowedChar", ",", "fromAttribute", "=", "True", ")" ]
[ 216, 4 ]
[ 219, 71 ]
python
en
['en', 'en', 'en']
True
HTMLTokenizer.emitCurrentToken
(self)
This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted.
This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted.
def emitCurrentToken(self): """This method is a generic handler for emitting the tags. It also sets the state to "data" because that's what's needed after a token has been emitted. """ token = self.currentToken # Add token to the queue to be yielded if (token["typ...
[ "def", "emitCurrentToken", "(", "self", ")", ":", "token", "=", "self", ".", "currentToken", "# Add token to the queue to be yielded", "if", "(", "token", "[", "\"type\"", "]", "in", "tagTokenTypes", ")", ":", "token", "[", "\"name\"", "]", "=", "token", "[", ...
[ 221, 4 ]
[ 238, 35 ]
python
en
['en', 'en', 'en']
True
MigrationWriter.as_string
(self)
Returns a string of the file contents.
Returns a string of the file contents.
def as_string(self): """ Returns a string of the file contents. """ items = { "replaces_str": "", } imports = set() # Deconstruct operations operations = [] for operation in self.migration.operations: operation_string, ope...
[ "def", "as_string", "(", "self", ")", ":", "items", "=", "{", "\"replaces_str\"", ":", "\"\"", ",", "}", "imports", "=", "set", "(", ")", "# Deconstruct operations", "operations", "=", "[", "]", "for", "operation", "in", "self", ".", "migration", ".", "o...
[ 116, 4 ]
[ 165, 58 ]
python
en
['en', 'error', 'th']
False
MigrationWriter.serialize_datetime
(value)
Returns a serialized version of a datetime object that is valid, executable python code. It converts timezone-aware values to utc with an 'executable' utc representation of tzinfo.
Returns a serialized version of a datetime object that is valid, executable python code. It converts timezone-aware values to utc with an 'executable' utc representation of tzinfo.
def serialize_datetime(value): """ Returns a serialized version of a datetime object that is valid, executable python code. It converts timezone-aware values to utc with an 'executable' utc representation of tzinfo. """ if value.tzinfo is not None and value.tzinfo != utc:...
[ "def", "serialize_datetime", "(", "value", ")", ":", "if", "value", ".", "tzinfo", "is", "not", "None", "and", "value", ".", "tzinfo", "!=", "utc", ":", "value", "=", "value", ".", "astimezone", "(", "utc", ")", "value_repr", "=", "repr", "(", "value",...
[ 168, 4 ]
[ 179, 25 ]
python
en
['en', 'error', 'th']
False
MigrationWriter.serialize
(cls, value)
Serializes the value to a string that's parsable by Python, along with any needed imports to make that string work. More advanced than repr() as it can encode things like datetime.datetime.now.
Serializes the value to a string that's parsable by Python, along with any needed imports to make that string work. More advanced than repr() as it can encode things like datetime.datetime.now.
def serialize(cls, value): """ Serializes the value to a string that's parsable by Python, along with any needed imports to make that string work. More advanced than repr() as it can encode things like datetime.datetime.now. """ # FIXME: Ideally Promise would be r...
[ "def", "serialize", "(", "cls", ",", "value", ")", ":", "# FIXME: Ideally Promise would be reconstructible, but for now we", "# use force_text on them and defer to the normal string serialization", "# process.", "if", "isinstance", "(", "value", ",", "Promise", ")", ":", "value...
[ 241, 4 ]
[ 398, 223 ]
python
en
['en', 'error', 'th']
False
opener_for
(ca_bundle=None)
Get a urlopen() replacement that uses ca_bundle for verification
Get a urlopen() replacement that uses ca_bundle for verification
def opener_for(ca_bundle=None): """Get a urlopen() replacement that uses ca_bundle for verification""" return urllib.request.build_opener( VerifyingHTTPSHandler(ca_bundle or find_ca_bundle()) ).open
[ "def", "opener_for", "(", "ca_bundle", "=", "None", ")", ":", "return", "urllib", ".", "request", ".", "build_opener", "(", "VerifyingHTTPSHandler", "(", "ca_bundle", "or", "find_ca_bundle", "(", ")", ")", ")", ".", "open" ]
[ 209, 0 ]
[ 213, 10 ]
python
en
['en', 'en', 'en']
True
find_ca_bundle
()
Return an existing CA bundle path, or None
Return an existing CA bundle path, or None
def find_ca_bundle(): """Return an existing CA bundle path, or None""" extant_cert_paths = filter(os.path.isfile, cert_paths) return ( get_win_certfile() or next(extant_cert_paths, None) or _certifi_where() )
[ "def", "find_ca_bundle", "(", ")", ":", "extant_cert_paths", "=", "filter", "(", "os", ".", "path", ".", "isfile", ",", "cert_paths", ")", "return", "(", "get_win_certfile", "(", ")", "or", "next", "(", "extant_cert_paths", ",", "None", ")", "or", "_certif...
[ 250, 0 ]
[ 257, 5 ]
python
en
['en', 'en', 'en']
True
timeout
(timeout: float, func: Callable[[], ResultT])
Call the function in a separate thread. Return its return value, or raise an exception, within approximately 'timeout' seconds. The function may receive a TimeoutExpired exception anywhere in its code, which could have arbitrary unsafe effects (resources not released, etc.). It might also fail ...
Call the function in a separate thread. Return its return value, or raise an exception, within approximately 'timeout' seconds.
def timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT: """Call the function in a separate thread. Return its return value, or raise an exception, within approximately 'timeout' seconds. The function may receive a TimeoutExpired exception anywhere in its code, which could have arbitrar...
[ "def", "timeout", "(", "timeout", ":", "float", ",", "func", ":", "Callable", "[", "[", "]", ",", "ResultT", "]", ")", "->", "ResultT", ":", "class", "TimeoutThread", "(", "threading", ".", "Thread", ")", ":", "def", "__init__", "(", "self", ")", "->...
[ 20, 0 ]
[ 95, 24 ]
python
en
['en', 'en', 'en']
True
__deepcopy__
(self, memo)
Don't populate the QuerySet's cache.
Don't populate the QuerySet's cache.
def __deepcopy__(self, memo): """Don't populate the QuerySet's cache.""" obj = self.__class__() for k, v in self.__dict__.items(): if k == '_result_cache': obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return...
[ "def", "__deepcopy__", "(", "self", ",", "memo", ")", ":", "obj", "=", "self", ".", "__class__", "(", ")", "for", "k", ",", "v", "in", "self", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "==", "'_result_cache'", ":", "obj", ".", "__d...
[ 217, 4 ]
[ 225, 18 ]
python
en
['en', 'en', 'en']
True
__iter__
(self)
The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some col...
The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for doing some col...
def __iter__(self): """ The queryset iterator protocol uses three nested iterators in the default case: 1. sql.compiler.execute_sql() - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE) using cursor.fetchmany(). This part is responsible for ...
[ "def", "__iter__", "(", "self", ")", ":", "self", ".", "_fetch_all", "(", ")", "return", "iter", "(", "self", ".", "_result_cache", ")" ]
[ 260, 4 ]
[ 276, 39 ]
python
en
['en', 'error', 'th']
False
__getitem__
(self, k)
Retrieve an item or slice from the set of results.
Retrieve an item or slice from the set of results.
def __getitem__(self, k): """Retrieve an item or slice from the set of results.""" if not isinstance(k, (int, slice)): raise TypeError( 'QuerySet indices must be integers or slices, not %s.' % type(k).__name__ ) assert ((not isinstance(k, s...
[ "def", "__getitem__", "(", "self", ",", "k", ")", ":", "if", "not", "isinstance", "(", "k", ",", "(", "int", ",", "slice", ")", ")", ":", "raise", "TypeError", "(", "'QuerySet indices must be integers or slices, not %s.'", "%", "type", "(", "k", ")", ".", ...
[ 282, 4 ]
[ 313, 34 ]
python
en
['en', 'en', 'en']
True
iterator
(self, chunk_size=2000)
An iterator over the results from applying this QuerySet to the database.
An iterator over the results from applying this QuerySet to the database.
def iterator(self, chunk_size=2000): """ An iterator over the results from applying this QuerySet to the database. """ if chunk_size <= 0: raise ValueError('Chunk size must be strictly positive.') use_chunked_fetch = not connections[self.db].settings_dict.get(...
[ "def", "iterator", "(", "self", ",", "chunk_size", "=", "2000", ")", ":", "if", "chunk_size", "<=", "0", ":", "raise", "ValueError", "(", "'Chunk size must be strictly positive.'", ")", "use_chunked_fetch", "=", "not", "connections", "[", "self", ".", "db", "]...
[ 347, 4 ]
[ 355, 60 ]
python
en
['en', 'error', 'th']
False
main
(argv=None)
Make a confidence report and save it to disk.
Make a confidence report and save it to disk.
def main(argv=None): """ Make a confidence report and save it to disk. """ assert len(argv) >= 3 _name_of_script = argv[0] model_filepath = argv[1] adv_x_filepaths = argv[2:] sess = tf.Session() with sess.as_default(): model = serial.load(model_filepath) factory = model...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "assert", "len", "(", "argv", ")", ">=", "3", "_name_of_script", "=", "argv", "[", "0", "]", "model_filepath", "=", "argv", "[", "1", "]", "adv_x_filepaths", "=", "argv", "[", "2", ":", "]", "sess"...
[ 48, 0 ]
[ 98, 5 ]
python
en
['en', 'error', 'th']
False
RelativeLinksHelpExtension.extendMarkdown
(self, md: Markdown)
Add RelativeLinksHelpExtension to the Markdown instance.
Add RelativeLinksHelpExtension to the Markdown instance.
def extendMarkdown(self, md: Markdown) -> None: """ Add RelativeLinksHelpExtension to the Markdown instance. """ md.registerExtension(self) md.preprocessors.register(RelativeLinks(), "help_relative_links", 520)
[ "def", "extendMarkdown", "(", "self", ",", "md", ":", "Markdown", ")", "->", "None", ":", "md", ".", "registerExtension", "(", "self", ")", "md", ".", "preprocessors", ".", "register", "(", "RelativeLinks", "(", ")", ",", "\"help_relative_links\"", ",", "5...
[ 72, 4 ]
[ 75, 78 ]
python
en
['en', 'en', 'en']
True
check_password
(password, encoded, setter=None, preferred='default')
Returns a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password.
Returns a boolean of whether the raw password matches the three part encoded digest.
def check_password(password, encoded, setter=None, preferred='default'): """ Returns a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None or not is_password_usab...
[ "def", "check_password", "(", "password", ",", "encoded", ",", "setter", "=", "None", ",", "preferred", "=", "'default'", ")", ":", "if", "password", "is", "None", "or", "not", "is_password_usable", "(", "encoded", ")", ":", "return", "False", "preferred", ...
[ 43, 0 ]
[ 63, 21 ]
python
en
['en', 'error', 'th']
False
make_password
(password, salt=None, hasher='default')
Turn a plain-text password into a hash for database storage Same as encode() but generates a new random salt. If password is None then a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string will be returned which disallows logins. Additional random string reduces chances of gaining ac...
Turn a plain-text password into a hash for database storage
def make_password(password, salt=None, hasher='default'): """ Turn a plain-text password into a hash for database storage Same as encode() but generates a new random salt. If password is None then a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string will be returned which disallows l...
[ "def", "make_password", "(", "password", ",", "salt", "=", "None", ",", "hasher", "=", "'default'", ")", ":", "if", "password", "is", "None", ":", "return", "UNUSABLE_PASSWORD_PREFIX", "+", "get_random_string", "(", "UNUSABLE_PASSWORD_SUFFIX_LENGTH", ")", "hasher"...
[ 66, 0 ]
[ 84, 40 ]
python
en
['en', 'error', 'th']
False
get_hasher
(algorithm='default')
Returns an instance of a loaded password hasher. If algorithm is 'default', the default hasher will be returned. This function will also lazy import hashers specified in your settings file if needed.
Returns an instance of a loaded password hasher.
def get_hasher(algorithm='default'): """ Returns an instance of a loaded password hasher. If algorithm is 'default', the default hasher will be returned. This function will also lazy import hashers specified in your settings file if needed. """ if hasattr(algorithm, 'algorithm'): re...
[ "def", "get_hasher", "(", "algorithm", "=", "'default'", ")", ":", "if", "hasattr", "(", "algorithm", ",", "'algorithm'", ")", ":", "return", "algorithm", "elif", "algorithm", "==", "'default'", ":", "if", "PREFERRED_HASHER", "is", "None", ":", "load_hashers",...
[ 103, 0 ]
[ 125, 33 ]
python
en
['en', 'error', 'th']
False
identify_hasher
(encoded)
Returns an instance of a loaded password hasher. Identifies hasher algorithm by examining encoded hash, and calls get_hasher() to return hasher. Raises ValueError if algorithm cannot be identified, or if hasher is not loaded.
Returns an instance of a loaded password hasher.
def identify_hasher(encoded): """ Returns an instance of a loaded password hasher. Identifies hasher algorithm by examining encoded hash, and calls get_hasher() to return hasher. Raises ValueError if algorithm cannot be identified, or if hasher is not loaded. """ # Ancient versions of Djang...
[ "def", "identify_hasher", "(", "encoded", ")", ":", "# Ancient versions of Django created plain MD5 passwords and accepted", "# MD5 passwords with an empty salt.", "if", "(", "(", "len", "(", "encoded", ")", "==", "32", "and", "'$'", "not", "in", "encoded", ")", "or", ...
[ 128, 0 ]
[ 146, 32 ]
python
en
['en', 'error', 'th']
False
mask_hash
(hash, show=6, char="*")
Returns the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons.
Returns the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons.
def mask_hash(hash, show=6, char="*"): """ Returns the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked
[ "def", "mask_hash", "(", "hash", ",", "show", "=", "6", ",", "char", "=", "\"*\"", ")", ":", "masked", "=", "hash", "[", ":", "show", "]", "masked", "+=", "char", "*", "len", "(", "hash", "[", "show", ":", "]", ")", "return", "masked" ]
[ 149, 0 ]
[ 156, 17 ]
python
en
['en', 'error', 'th']
False
BasePasswordHasher.salt
(self)
Generates a cryptographically secure nonce salt in ASCII
Generates a cryptographically secure nonce salt in ASCII
def salt(self): """ Generates a cryptographically secure nonce salt in ASCII """ return get_random_string()
[ "def", "salt", "(", "self", ")", ":", "return", "get_random_string", "(", ")" ]
[ 186, 4 ]
[ 190, 34 ]
python
en
['en', 'error', 'th']
False
BasePasswordHasher.verify
(self, password, encoded)
Checks if the given password is correct
Checks if the given password is correct
def verify(self, password, encoded): """ Checks if the given password is correct """ raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')
[ "def", "verify", "(", "self", ",", "password", ",", "encoded", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BasePasswordHasher must provide a verify() method'", ")" ]
[ 192, 4 ]
[ 196, 100 ]
python
en
['en', 'error', 'th']
False
BasePasswordHasher.encode
(self, password, salt)
Creates an encoded database value The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters.
Creates an encoded database value
def encode(self, password, salt): """ Creates an encoded database value The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError('subclasses of BasePasswordHasher must provide an encode() method')
[ "def", "encode", "(", "self", ",", "password", ",", "salt", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BasePasswordHasher must provide an encode() method'", ")" ]
[ 198, 4 ]
[ 205, 101 ]
python
en
['en', 'error', 'th']
False
BasePasswordHasher.safe_summary
(self, encoded)
Returns a summary of safe values The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password.
Returns a summary of safe values
def safe_summary(self, encoded): """ Returns a summary of safe values The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password. """ raise NotImplementedError('subclasses of BasePasswordHashe...
[ "def", "safe_summary", "(", "self", ",", "encoded", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of BasePasswordHasher must provide a safe_summary() method'", ")" ]
[ 207, 4 ]
[ 214, 106 ]
python
en
['en', 'error', 'th']
False
setup_bash_profile
()
Select a bash profile file to add setup code to.
Select a bash profile file to add setup code to.
def setup_bash_profile() -> None: """Select a bash profile file to add setup code to.""" BASH_PROFILES = [ os.path.expanduser(p) for p in ("~/.bash_profile", "~/.bash_login", "~/.profile") ] def clear_old_profile() -> None: # An earlier version of this script would output a fresh .bash...
[ "def", "setup_bash_profile", "(", ")", "->", "None", ":", "BASH_PROFILES", "=", "[", "os", ".", "path", ".", "expanduser", "(", "p", ")", "for", "p", "in", "(", "\"~/.bash_profile\"", ",", "\"~/.bash_login\"", ",", "\"~/.profile\"", ")", "]", "def", "clear...
[ 103, 0 ]
[ 138, 45 ]
python
en
['en', 'sm', 'en']
True
DictConfigSource.__init__
(self, config: dict = {})
Dict Config Source. Args: config (dict, optional): Initial Config. Defaults to {}.
Dict Config Source.
def __init__(self, config: dict = {}): """Dict Config Source. Args: config (dict, optional): Initial Config. Defaults to {}. """ super().__init__(initial_config=config)
[ "def", "__init__", "(", "self", ",", "config", ":", "dict", "=", "{", "}", ")", ":", "super", "(", ")", ".", "__init__", "(", "initial_config", "=", "config", ")" ]
[ 6, 4 ]
[ 14, 47 ]
python
en
['de', 'en', 'en']
True
RenameMethodsTests.test_class_definition_warnings
(self)
Ensure a warning is raised upon class definition to suggest renaming the faulty method.
Ensure a warning is raised upon class definition to suggest renaming the faulty method.
def test_class_definition_warnings(self): """ Ensure a warning is raised upon class definition to suggest renaming the faulty method. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') class Manager(six.with_metacla...
[ "def", "test_class_definition_warnings", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'always'", ")", "class", "Manager", "(", "six", ".", "wi...
[ 25, 4 ]
[ 39, 64 ]
python
en
['en', 'error', 'th']
False
RenameMethodsTests.test_get_new_defined
(self)
Ensure `old` complains and not `new` when only `new` is defined.
Ensure `old` complains and not `new` when only `new` is defined.
def test_get_new_defined(self): """ Ensure `old` complains and not `new` when only `new` is defined. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Manager(six.with_metaclass(RenameManagerMethods)): ...
[ "def", "test_get_new_defined", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "class", "Manager", "(", "six", ".", "with_metacla...
[ 41, 4 ]
[ 59, 66 ]
python
en
['en', 'error', 'th']
False
RenameMethodsTests.test_get_old_defined
(self)
Ensure `old` complains when only `old` is defined.
Ensure `old` complains when only `old` is defined.
def test_get_old_defined(self): """ Ensure `old` complains when only `old` is defined. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Manager(six.with_metaclass(RenameManagerMethods)): def old(self...
[ "def", "test_get_old_defined", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "class", "Manager", "(", "six", ".", "with_metacla...
[ 61, 4 ]
[ 79, 66 ]
python
en
['en', 'error', 'th']
False
RenameMethodsTests.test_deprecated_subclass_renamed
(self)
Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did.
Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did.
def test_deprecated_subclass_renamed(self): """ Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Renamed(si...
[ "def", "test_deprecated_subclass_renamed", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "class", "Renamed", "(", "six", ".", "...
[ 81, 4 ]
[ 110, 14 ]
python
en
['en', 'error', 'th']
False
RenameMethodsTests.test_renamed_subclass_deprecated
(self)
Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't.
Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't.
def test_renamed_subclass_deprecated(self): """ Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('ignore') class Deprecated(si...
[ "def", "test_renamed_subclass_deprecated", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "class", "Deprecated", "(", "six", ".", ...
[ 112, 4 ]
[ 135, 66 ]
python
en
['en', 'error', 'th']
False
RenameMethodsTests.test_deprecated_subclass_renamed_and_mixins
(self)
Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`.
Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`.
def test_deprecated_subclass_renamed_and_mixins(self): """ Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`. """ with warnings.catch_warnings(record=True) as recorded: ...
[ "def", "test_deprecated_subclass_renamed_and_mixins", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ")", "class", "Renamed", "(", "six",...
[ 137, 4 ]
[ 173, 14 ]
python
en
['en', 'error', 'th']
False
DeprecatingRequestMergeDictTest.test_deprecated_request
(self)
Ensure the correct warning is raised when WSGIRequest.REQUEST is accessed.
Ensure the correct warning is raised when WSGIRequest.REQUEST is accessed.
def test_deprecated_request(self): """ Ensure the correct warning is raised when WSGIRequest.REQUEST is accessed. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') request = RequestFactory().get('/') req...
[ "def", "test_deprecated_request", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'always'", ")", "request", "=", "RequestFactory", "(", ")", "."...
[ 177, 4 ]
[ 192, 14 ]
python
en
['en', 'error', 'th']
False
DeprecatingMemoizeTest.test_deprecated_memoize
(self)
Ensure the correct warning is raised when memoize is used.
Ensure the correct warning is raised when memoize is used.
def test_deprecated_memoize(self): """ Ensure the correct warning is raised when memoize is used. """ with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') memoize(lambda x: x, {}, 1) msg = str(recorded.pop().message) ...
[ "def", "test_deprecated_memoize", "(", "self", ")", ":", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")", "as", "recorded", ":", "warnings", ".", "simplefilter", "(", "'always'", ")", "memoize", "(", "lambda", "x", ":", "x", ",",...
[ 214, 4 ]
[ 224, 59 ]
python
en
['en', 'error', 'th']
False
DeprecatingSimpleTestCaseUrls.test_deprecation
(self)
Ensure the correct warning is raised when SimpleTestCase.urls is used.
Ensure the correct warning is raised when SimpleTestCase.urls is used.
def test_deprecation(self): """ Ensure the correct warning is raised when SimpleTestCase.urls is used. """ class TempTestCase(SimpleTestCase): urls = 'tests.urls' def test(self): pass with warnings.catch_warnings(record=True) as recorded:...
[ "def", "test_deprecation", "(", "self", ")", ":", "class", "TempTestCase", "(", "SimpleTestCase", ")", ":", "urls", "=", "'tests.urls'", "def", "test", "(", "self", ")", ":", "pass", "with", "warnings", ".", "catch_warnings", "(", "record", "=", "True", ")...
[ 229, 4 ]
[ 247, 47 ]
python
en
['en', 'error', 'th']
False
finder
(package)
Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package.
Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package.
def finder(package): """ Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package. """ if package in _finder_cache: result = _finder_cache[package] else: if package not in sys.modules: ...
[ "def", "finder", "(", "package", ")", ":", "if", "package", "in", "_finder_cache", ":", "result", "=", "_finder_cache", "[", "package", "]", "else", ":", "if", "package", "not", "in", "sys", ".", "modules", ":", "__import__", "(", "package", ")", "module...
[ 309, 0 ]
[ 331, 17 ]
python
en
['en', 'error', 'th']
False
finder_for_path
(path)
Return a resource finder for a path, which should represent a container. :param path: The path. :return: A :class:`ResourceFinder` instance for the path.
Return a resource finder for a path, which should represent a container.
def finder_for_path(path): """ Return a resource finder for a path, which should represent a container. :param path: The path. :return: A :class:`ResourceFinder` instance for the path. """ result = None # calls any path hooks, gets importer into cache pkgutil.get_importer(path) load...
[ "def", "finder_for_path", "(", "path", ")", ":", "result", "=", "None", "# calls any path hooks, gets importer into cache", "pkgutil", ".", "get_importer", "(", "path", ")", "loader", "=", "sys", ".", "path_importer_cache", ".", "get", "(", "path", ")", "finder", ...
[ 337, 0 ]
[ 354, 17 ]
python
en
['en', 'error', 'th']
False
ResourceCache.is_stale
(self, resource, path)
Is the cache stale for the given resource? :param resource: The :class:`Resource` being cached. :param path: The path of the resource in the cache. :return: True if the cache is stale.
Is the cache stale for the given resource?
def is_stale(self, resource, path): """ Is the cache stale for the given resource? :param resource: The :class:`Resource` being cached. :param path: The path of the resource in the cache. :return: True if the cache is stale. """ # Cache invalidation is a hard pro...
[ "def", "is_stale", "(", "self", ",", "resource", ",", "path", ")", ":", "# Cache invalidation is a hard problem :-)", "return", "True" ]
[ 34, 4 ]
[ 43, 19 ]
python
en
['en', 'error', 'th']
False
ResourceCache.get
(self, resource)
Get a resource into the cache, :param resource: A :class:`Resource` instance. :return: The pathname of the resource in the cache.
Get a resource into the cache,
def get(self, resource): """ Get a resource into the cache, :param resource: A :class:`Resource` instance. :return: The pathname of the resource in the cache. """ prefix, path = resource.finder.get_cache_info(resource) if prefix is None: result = path...
[ "def", "get", "(", "self", ",", "resource", ")", ":", "prefix", ",", "path", "=", "resource", ".", "finder", ".", "get_cache_info", "(", "resource", ")", "if", "prefix", "is", "None", ":", "result", "=", "path", "else", ":", "result", "=", "os", ".",...
[ 45, 4 ]
[ 68, 21 ]
python
en
['en', 'error', 'th']
False
Resource.as_stream
(self)
Get the resource as a stream. This is not a property to make it obvious that it returns a new stream each time.
Get the resource as a stream.
def as_stream(self): """ Get the resource as a stream. This is not a property to make it obvious that it returns a new stream each time. """ return self.finder.get_stream(self)
[ "def", "as_stream", "(", "self", ")", ":", "return", "self", ".", "finder", ".", "get_stream", "(", "self", ")" ]
[ 85, 4 ]
[ 92, 43 ]
python
en
['en', 'error', 'th']
False
further_validated_draft_dict
( draft_dict: Dict[str, Any], user_profile: UserProfile )
Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a slightly different set of keys the values for which can be used to directly create a Draft object.
Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a slightly different set of keys the values for which can be used to directly create a Draft object.
def further_validated_draft_dict( draft_dict: Dict[str, Any], user_profile: UserProfile ) -> Dict[str, Any]: """Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a sl...
[ "def", "further_validated_draft_dict", "(", "draft_dict", ":", "Dict", "[", "str", ",", "Any", "]", ",", "user_profile", ":", "UserProfile", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "content", "=", "normalize_body", "(", "draft_dict", "[", "\"c...
[ 44, 0 ]
[ 85, 5 ]
python
en
['en', 'en', 'en']
True
_get_all_permissions
(opts, ctype)
Returns (codename, name) for all permissions in the given opts.
Returns (codename, name) for all permissions in the given opts.
def _get_all_permissions(opts, ctype): """ Returns (codename, name) for all permissions in the given opts. """ builtin = _get_builtin_permissions(opts) custom = list(opts.permissions) _check_permission_clashing(custom, builtin, ctype) return builtin + custom
[ "def", "_get_all_permissions", "(", "opts", ",", "ctype", ")", ":", "builtin", "=", "_get_builtin_permissions", "(", "opts", ")", "custom", "=", "list", "(", "opts", ".", "permissions", ")", "_check_permission_clashing", "(", "custom", ",", "builtin", ",", "ct...
[ 18, 0 ]
[ 25, 27 ]
python
en
['en', 'error', 'th']
False
_get_builtin_permissions
(opts)
Returns (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete')
Returns (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete')
def _get_builtin_permissions(opts): """ Returns (codename, name) for all autogenerated permissions. By default, this is ('add', 'change', 'delete') """ perms = [] for action in opts.default_permissions: perms.append((get_permission_codename(action, opts), 'Can %s %s' % (actio...
[ "def", "_get_builtin_permissions", "(", "opts", ")", ":", "perms", "=", "[", "]", "for", "action", "in", "opts", ".", "default_permissions", ":", "perms", ".", "append", "(", "(", "get_permission_codename", "(", "action", ",", "opts", ")", ",", "'Can %s %s'"...
[ 28, 0 ]
[ 37, 16 ]
python
en
['en', 'error', 'th']
False
_check_permission_clashing
(custom, builtin, ctype)
Check that permissions for a model do not clash. Raises CommandError if there are duplicate permissions.
Check that permissions for a model do not clash. Raises CommandError if there are duplicate permissions.
def _check_permission_clashing(custom, builtin, ctype): """ Check that permissions for a model do not clash. Raises CommandError if there are duplicate permissions. """ pool = set() builtin_codenames = set(p[0] for p in builtin) for codename, _name in custom: if codename in pool: ...
[ "def", "_check_permission_clashing", "(", "custom", ",", "builtin", ",", "ctype", ")", ":", "pool", "=", "set", "(", ")", "builtin_codenames", "=", "set", "(", "p", "[", "0", "]", "for", "p", "in", "builtin", ")", "for", "codename", ",", "_name", "in",...
[ 40, 0 ]
[ 57, 26 ]
python
en
['en', 'error', 'th']
False
get_system_username
()
Try to determine the current system user's username. :returns: The username as a unicode string, or an empty string if the username could not be determined.
Try to determine the current system user's username.
def get_system_username(): """ Try to determine the current system user's username. :returns: The username as a unicode string, or an empty string if the username could not be determined. """ try: result = getpass.getuser() except (ImportError, KeyError): # KeyError will...
[ "def", "get_system_username", "(", ")", ":", "try", ":", "result", "=", "getpass", ".", "getuser", "(", ")", "except", "(", "ImportError", ",", "KeyError", ")", ":", "# KeyError will be raised by os.getpwuid() (called by getuser())", "# if there is no corresponding entry ...
[ 119, 0 ]
[ 139, 17 ]
python
en
['en', 'error', 'th']
False
get_default_username
(check_db=True)
Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :returns: The username, or an empty string if no username can be determined.
Try to determine the current system user's username to use as a default.
def get_default_username(check_db=True): """ Try to determine the current system user's username to use as a default. :param check_db: If ``True``, requires that the username does not match an existing ``auth.User`` (otherwise returns an empty string). :returns: The username, or an empty string...
[ "def", "get_default_username", "(", "check_db", "=", "True", ")", ":", "# If the User model has been swapped out, we can't make any assumptions", "# about the default user name.", "if", "auth_app", ".", "User", ".", "_meta", ".", "swapped", ":", "return", "''", "default_use...
[ 142, 0 ]
[ 178, 27 ]
python
en
['en', 'error', 'th']
False
_add_doc
(func, doc)
Add documentation to a function.
Add documentation to a function.
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
[ "def", "_add_doc", "(", "func", ",", "doc", ")", ":", "func", ".", "__doc__", "=", "doc" ]
[ 74, 0 ]
[ 76, 22 ]
python
en
['en', 'en', 'en']
True
_import_module
(name)
Import module, returning the module after the last dot.
Import module, returning the module after the last dot.
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
[ "def", "_import_module", "(", "name", ")", ":", "__import__", "(", "name", ")", "return", "sys", ".", "modules", "[", "name", "]" ]
[ 79, 0 ]
[ 82, 28 ]
python
en
['en', 'en', 'en']
True
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
[ 485, 0 ]
[ 487, 41 ]
python
en
['en', 'en', 'en']
True
remove_move
(name)
Remove item from six.moves.
Remove item from six.moves.
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
[ "def", "remove_move", "(", "name", ")", ":", "try", ":", "delattr", "(", "_MovedItems", ",", "name", ")", "except", "AttributeError", ":", "try", ":", "del", "moves", ".", "__dict__", "[", "name", "]", "except", "KeyError", ":", "raise", "AttributeError", ...
[ 490, 0 ]
[ 498, 62 ]
python
en
['en', 'en', 'en']
True
with_metaclass
(meta, *bases)
Create a base class with a metaclass.
Create a base class with a metaclass.
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, na...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "meta", ")...
[ 799, 0 ]
[ 808, 61 ]
python
en
['en', 'en', 'en']
True
add_metaclass
(metaclass)
Class decorator for creating a class with a metaclass.
Class decorator for creating a class with a metaclass.
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get('__slots__') if slots is not None: if isinstance(slots, str): slots = [slots] for slo...
[ "def", "add_metaclass", "(", "metaclass", ")", ":", "def", "wrapper", "(", "cls", ")", ":", "orig_vars", "=", "cls", ".", "__dict__", ".", "copy", "(", ")", "slots", "=", "orig_vars", ".", "get", "(", "'__slots__'", ")", "if", "slots", "is", "not", "...
[ 811, 0 ]
[ 824, 18 ]
python
en
['en', 'en', 'en']
True
python_2_unicode_compatible
(klass)
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class.
A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing.
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: ...
[ "def", "python_2_unicode_compatible", "(", "klass", ")", ":", "if", "PY2", ":", "if", "'__str__'", "not", "in", "klass", ".", "__dict__", ":", "raise", "ValueError", "(", "\"@python_2_unicode_compatible cannot be applied \"", "\"to %s because it doesn't define __str__().\""...
[ 827, 0 ]
[ 842, 16 ]
python
en
['en', 'error', 'th']
False
_SixMetaPathImporter.is_package
(self, fullname)
Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)
Return true, if the named module is a package.
def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__")
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "return", "hasattr", "(", "self", ".", "__get_module", "(", "fullname", ")", ",", "\"__path__\"", ")" ]
[ 208, 4 ]
[ 215, 63 ]
python
en
['en', 'error', 'th']
False
_SixMetaPathImporter.get_code
(self, fullname)
Return None Required, if is_package is implemented
Return None
def get_code(self, fullname): """Return None Required, if is_package is implemented""" self.__get_module(fullname) # eventually raises ImportError return None
[ "def", "get_code", "(", "self", ",", "fullname", ")", ":", "self", ".", "__get_module", "(", "fullname", ")", "# eventually raises ImportError", "return", "None" ]
[ 217, 4 ]
[ 222, 19 ]
python
en
['en', 'co', 'en']
False
SingleObjectMixin.get_object
(self, queryset=None)
Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object.
Return the object the view is displaying.
def get_object(self, queryset=None): """ Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subcl...
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "# Use a custom queryset if provided; this is required for subclasses", "# like DateDetailView", "if", "queryset", "is", "None", ":", "queryset", "=", "self", ".", "get_queryset", "(", ")", "# N...
[ 19, 4 ]
[ 55, 18 ]
python
en
['en', 'error', 'th']
False
SingleObjectMixin.get_queryset
(self)
Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and may not be called if get_object() is overridden.
Return the `QuerySet` that will be used to look up the object.
def get_queryset(self): """ Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and may not be called if get_object() is overridden. """ if self.queryset is None: if self.model: ...
[ "def", "get_queryset", "(", "self", ")", ":", "if", "self", ".", "queryset", "is", "None", ":", "if", "self", ".", "model", ":", "return", "self", ".", "model", ".", "_default_manager", ".", "all", "(", ")", "else", ":", "raise", "ImproperlyConfigured", ...
[ 57, 4 ]
[ 75, 34 ]
python
en
['en', 'error', 'th']
False
SingleObjectMixin.get_slug_field
(self)
Get the name of a slug field to be used to look up by slug.
Get the name of a slug field to be used to look up by slug.
def get_slug_field(self): """Get the name of a slug field to be used to look up by slug.""" return self.slug_field
[ "def", "get_slug_field", "(", "self", ")", ":", "return", "self", ".", "slug_field" ]
[ 77, 4 ]
[ 79, 30 ]
python
en
['en', 'en', 'en']
True
SingleObjectMixin.get_context_object_name
(self, obj)
Get the name to use for the object.
Get the name to use for the object.
def get_context_object_name(self, obj): """Get the name to use for the object.""" if self.context_object_name: return self.context_object_name elif isinstance(obj, models.Model): return obj._meta.model_name else: return None
[ "def", "get_context_object_name", "(", "self", ",", "obj", ")", ":", "if", "self", ".", "context_object_name", ":", "return", "self", ".", "context_object_name", "elif", "isinstance", "(", "obj", ",", "models", ".", "Model", ")", ":", "return", "obj", ".", ...
[ 81, 4 ]
[ 88, 23 ]
python
en
['en', 'en', 'en']
True
SingleObjectMixin.get_context_data
(self, **kwargs)
Insert the single object into the context dict.
Insert the single object into the context dict.
def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context['object'] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: con...
[ "def", "get_context_data", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "{", "}", "if", "self", ".", "object", ":", "context", "[", "'object'", "]", "=", "self", ".", "object", "context_object_name", "=", "self", ".", "get_context_obje...
[ 90, 4 ]
[ 99, 50 ]
python
en
['en', 'en', 'en']
True
SingleObjectTemplateResponseMixin.get_template_names
(self)
Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_field`` field on the object instanc...
Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list:
def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return the following list: * the value of ``template_name`` on the view (if provided) * the contents of the ``template_name_fiel...
[ "def", "get_template_names", "(", "self", ")", ":", "try", ":", "names", "=", "super", "(", ")", ".", "get_template_names", "(", ")", "except", "ImproperlyConfigured", ":", "# If template_name isn't specified, it's not a problem --", "# we just start with an empty list.", ...
[ 114, 4 ]
[ 160, 20 ]
python
en
['en', 'error', 'th']
False
YoHookTests.test_yo_message
(self)
Yo App sends notification whenever user receives a new Yo from another user.
Yo App sends notification whenever user receives a new Yo from another user.
def test_yo_message(self) -> None: """ Yo App sends notification whenever user receives a new Yo from another user. """ cordelia = self.example_user("cordelia") self.url = self.build_webhook_url( email=cordelia.email, username="IAGO", user_ip="...
[ "def", "test_yo_message", "(", "self", ")", "->", "None", ":", "cordelia", "=", "self", ".", "example_user", "(", "\"cordelia\"", ")", "self", ".", "url", "=", "self", ".", "build_webhook_url", "(", "email", "=", "cordelia", ".", "email", ",", "username", ...
[ 10, 4 ]
[ 23, 9 ]
python
en
['en', 'error', 'th']
False