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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
SimpleTemplateResponse.render | (self) | Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Return the baked response instance.
| Render (thereby finalizing) the content of the response. | def render(self):
"""Render (thereby finalizing) the content of the response.
If the content has already been rendered, this is a no-op.
Return the baked response instance.
"""
retval = self
if not self._is_rendered:
self.content = self.rendered_content
... | [
"def",
"render",
"(",
"self",
")",
":",
"retval",
"=",
"self",
"if",
"not",
"self",
".",
"_is_rendered",
":",
"self",
".",
"content",
"=",
"self",
".",
"rendered_content",
"for",
"post_callback",
"in",
"self",
".",
"_post_render_callbacks",
":",
"newretval",... | [
95,
4
] | [
109,
21
] | python | en | ['en', 'en', 'en'] | True |
SimpleTemplateResponse.content | (self, value) | Set the content for the response. | Set the content for the response. | def content(self, value):
"""Set the content for the response."""
HttpResponse.content.fset(self, value)
self._is_rendered = True | [
"def",
"content",
"(",
"self",
",",
"value",
")",
":",
"HttpResponse",
".",
"content",
".",
"fset",
"(",
"self",
",",
"value",
")",
"self",
".",
"_is_rendered",
"=",
"True"
] | [
131,
4
] | [
134,
32
] | python | en | ['en', 'en', 'en'] | True |
Envelope.__init__ | (self, *args) |
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
|
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
| def __init__(self, *args):
"""
The initialization function may take an OGREnvelope structure, 4-element
tuple or list, or 4 individual arguments.
"""
if len(args) == 1:
if isinstance(args[0], OGREnvelope):
# OGREnvelope (a ctypes Structure) was passed... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"OGREnvelope",
")",
":",
"# OGREnvelope (a ctypes Structure) was passed in.",
"self",
".",
"_e... | [
35,
4
] | [
64,
65
] | python | en | ['en', 'error', 'th'] | False |
Envelope.__eq__ | (self, other) |
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
|
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
| def __eq__(self, other):
"""
Returns True if the envelopes are equivalent; can compare against
other Envelopes and 4-tuples.
"""
if isinstance(other, Envelope):
return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \
(self.max_x == ... | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"Envelope",
")",
":",
"return",
"(",
"self",
".",
"min_x",
"==",
"other",
".",
"min_x",
")",
"and",
"(",
"self",
".",
"min_y",
"==",
"other",
".",
"min_y",... | [
66,
4
] | [
78,
86
] | python | en | ['en', 'error', 'th'] | False |
Envelope.__str__ | (self) | Returns a string representation of the tuple. | Returns a string representation of the tuple. | def __str__(self):
"Returns a string representation of the tuple."
return str(self.tuple) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"tuple",
")"
] | [
80,
4
] | [
82,
30
] | python | en | ['en', 'en', 'en'] | True |
Envelope._from_sequence | (self, seq) | Initializes the C OGR Envelope structure from the given sequence. | Initializes the C OGR Envelope structure from the given sequence. | def _from_sequence(self, seq):
"Initializes the C OGR Envelope structure from the given sequence."
self._envelope = OGREnvelope()
self._envelope.MinX = seq[0]
self._envelope.MinY = seq[1]
self._envelope.MaxX = seq[2]
self._envelope.MaxY = seq[3] | [
"def",
"_from_sequence",
"(",
"self",
",",
"seq",
")",
":",
"self",
".",
"_envelope",
"=",
"OGREnvelope",
"(",
")",
"self",
".",
"_envelope",
".",
"MinX",
"=",
"seq",
"[",
"0",
"]",
"self",
".",
"_envelope",
".",
"MinY",
"=",
"seq",
"[",
"1",
"]",
... | [
84,
4
] | [
90,
36
] | python | en | ['en', 'en', 'en'] | True |
Envelope.expand_to_include | (self, *args) |
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
|
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
| def expand_to_include(self, *args):
"""
Modifies the envelope to expand to include the boundaries of
the passed-in 2-tuple (a point), 4-tuple (an extent) or
envelope.
"""
# We provide a number of different signatures for this method,
# and the logic here is all ab... | [
"def",
"expand_to_include",
"(",
"self",
",",
"*",
"args",
")",
":",
"# We provide a number of different signatures for this method,",
"# and the logic here is all about converting them into a",
"# 4-tuple single parameter which does the actual work of",
"# expanding the envelope.",
"if",
... | [
92,
4
] | [
132,
84
] | python | en | ['en', 'error', 'th'] | False |
Envelope.min_x | (self) | Returns the value of the minimum X coordinate. | Returns the value of the minimum X coordinate. | def min_x(self):
"Returns the value of the minimum X coordinate."
return self._envelope.MinX | [
"def",
"min_x",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MinX"
] | [
135,
4
] | [
137,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.min_y | (self) | Returns the value of the minimum Y coordinate. | Returns the value of the minimum Y coordinate. | def min_y(self):
"Returns the value of the minimum Y coordinate."
return self._envelope.MinY | [
"def",
"min_y",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MinY"
] | [
140,
4
] | [
142,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.max_x | (self) | Returns the value of the maximum X coordinate. | Returns the value of the maximum X coordinate. | def max_x(self):
"Returns the value of the maximum X coordinate."
return self._envelope.MaxX | [
"def",
"max_x",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MaxX"
] | [
145,
4
] | [
147,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.max_y | (self) | Returns the value of the maximum Y coordinate. | Returns the value of the maximum Y coordinate. | def max_y(self):
"Returns the value of the maximum Y coordinate."
return self._envelope.MaxY | [
"def",
"max_y",
"(",
"self",
")",
":",
"return",
"self",
".",
"_envelope",
".",
"MaxY"
] | [
150,
4
] | [
152,
34
] | python | en | ['en', 'la', 'en'] | True |
Envelope.ur | (self) | Returns the upper-right coordinate. | Returns the upper-right coordinate. | def ur(self):
"Returns the upper-right coordinate."
return (self.max_x, self.max_y) | [
"def",
"ur",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
")"
] | [
155,
4
] | [
157,
39
] | python | en | ['en', 'en', 'en'] | True |
Envelope.ll | (self) | Returns the lower-left coordinate. | Returns the lower-left coordinate. | def ll(self):
"Returns the lower-left coordinate."
return (self.min_x, self.min_y) | [
"def",
"ll",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
")"
] | [
160,
4
] | [
162,
39
] | python | en | ['en', 'en', 'en'] | True |
Envelope.tuple | (self) | Returns a tuple representing the envelope. | Returns a tuple representing the envelope. | def tuple(self):
"Returns a tuple representing the envelope."
return (self.min_x, self.min_y, self.max_x, self.max_y) | [
"def",
"tuple",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
")"
] | [
165,
4
] | [
167,
63
] | python | en | ['en', 'en', 'en'] | True |
Envelope.wkt | (self) | Returns WKT representing a Polygon for this envelope. | Returns WKT representing a Polygon for this envelope. | def wkt(self):
"Returns WKT representing a Polygon for this envelope."
# TODO: Fix significant figures.
return 'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))' % \
(self.min_x, self.min_y, self.min_x, self.max_y,
self.max_x, self.max_y, self.max_x, self.min_y,
... | [
"def",
"wkt",
"(",
"self",
")",
":",
"# TODO: Fix significant figures.",
"return",
"'POLYGON((%s %s,%s %s,%s %s,%s %s,%s %s))'",
"%",
"(",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"min_x",
",",
"self",
".",
"max_y",
",",
"self",
".",
... | [
170,
4
] | [
176,
39
] | python | en | ['en', 'en', 'en'] | True |
contains_partial | (haystack, needle, ignore_needle_children=False) | Search for a html element with at least the corresponding elements
(other elements may be present in the matched element from the haystack)
| Search for a html element with at least the corresponding elements
(other elements may be present in the matched element from the haystack)
| def contains_partial(haystack, needle, ignore_needle_children=False):
"""Search for a html element with at least the corresponding elements
(other elements may be present in the matched element from the haystack)
"""
if not isinstance(haystack, Element):
haystack = parse_html(haystack)
... | [
"def",
"contains_partial",
"(",
"haystack",
",",
"needle",
",",
"ignore_needle_children",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"haystack",
",",
"Element",
")",
":",
"haystack",
"=",
"parse_html",
"(",
"haystack",
")",
"if",
"not",
"isinsta... | [
3,
0
] | [
21,
5
] | python | en | ['en', 'en', 'en'] | True |
_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",
")"
] | [
515,
0
] | [
517,
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",
... | [
520,
0
] | [
528,
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(type):
def __new__(cls, nam... | [
"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",
"(",
"type",
")... | [
883,
0
] | [
896,
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 sl... | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"\"__slots__\"",
")",
"if",
"slots",
"is",
"not",
... | [
899,
0
] | [
916,
18
] | python | en | ['en', 'en', 'en'] | True |
ensure_binary | (s, encoding="utf-8", errors="strict") | Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
| Coerce **s** to six.binary_type. | def ensure_binary(s, encoding="utf-8", errors="strict"):
"""Coerce **s** to six.binary_type.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> encoded to `bytes`
- `bytes` -> `bytes`
"""
if isinstance(s, text_type):
return s.enc... | [
"def",
"ensure_binary",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"text_type",
")",
":",
"return",
"s",
".",
"encode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isins... | [
919,
0
] | [
935,
60
] | python | en | ['en', 'sn', 'en'] | True |
ensure_str | (s, encoding="utf-8", errors="strict") | Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
| Coerce *s* to `str`. | def ensure_str(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (text_type, binary_type)):
raise TypeEr... | [
"def",
"ensure_str",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"s",
",",
"(",
"text_type",
",",
"binary_type",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"not expecting type '%... | [
938,
0
] | [
955,
12
] | python | en | ['en', 'sl', 'en'] | True |
ensure_text | (s, encoding="utf-8", errors="strict") | Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
| Coerce *s* to six.text_type. | def ensure_text(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encodin... | [
"def",
"ensure_text",
"(",
"s",
",",
"encoding",
"=",
"\"utf-8\"",
",",
"errors",
"=",
"\"strict\"",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isins... | [
958,
0
] | [
974,
60
] | python | en | ['en', 'sr', '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__().\... | [
977,
0
] | [
993,
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__\"",
")"
] | [
204,
4
] | [
211,
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"
] | [
213,
4
] | [
218,
19
] | python | en | ['en', 'co', 'en'] | False |
LayoutObject.__getattr__ | (self, name) |
This allows us to access self.fields list methods like append or insert, without
having to declare them one by one
|
This allows us to access self.fields list methods like append or insert, without
having to declare them one by one
| def __getattr__(self, name):
"""
This allows us to access self.fields list methods like append or insert, without
having to declare them one by one
"""
# Check necessary for unpickling, see #107
if "fields" in self.__dict__ and hasattr(self.fields, name):
... | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"# Check necessary for unpickling, see #107\r",
"if",
"\"fields\"",
"in",
"self",
".",
"__dict__",
"and",
"hasattr",
"(",
"self",
".",
"fields",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"self",
... | [
30,
4
] | [
39,
54
] | python | en | ['en', 'ja', 'th'] | False |
LayoutObject.get_field_names | (self, index=None) |
Returns a list of lists, those lists are named pointers. First parameter
is the location of the field, second one the name of the field. Example::
[
[[0,1,2], 'field_name1'],
[[0,3], 'field_name2']
]
|
Returns a list of lists, those lists are named pointers. First parameter
is the location of the field, second one the name of the field. Example::
[
[[0,1,2], 'field_name1'],
[[0,3], 'field_name2']
]
| def get_field_names(self, index=None):
"""
Returns a list of lists, those lists are named pointers. First parameter
is the location of the field, second one the name of the field. Example::
[
[[0,1,2], 'field_name1'],
[[0,3], 'field_name2']
... | [
"def",
"get_field_names",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_layout_objects",
"(",
"str",
",",
"index",
"=",
"None",
",",
"greedy",
"=",
"True",
")"
] | [
41,
4
] | [
51,
68
] | python | en | ['en', 'ja', 'th'] | False |
LayoutObject.get_layout_objects | (self, *LayoutClasses, **kwargs) |
Returns a list of lists pointing to layout objects of any type matching
`LayoutClasses`::
[
[[0,1,2], 'div'],
[[0,3], 'field_name']
]
:param max_level: An integer that indicates max level depth to reach when
traversing ... |
Returns a list of lists pointing to layout objects of any type matching
`LayoutClasses`::
[
[[0,1,2], 'div'],
[[0,3], 'field_name']
]
:param max_level: An integer that indicates max level depth to reach when
traversing ... | def get_layout_objects(self, *LayoutClasses, **kwargs):
"""
Returns a list of lists pointing to layout objects of any type matching
`LayoutClasses`::
[
[[0,1,2], 'div'],
[[0,3], 'field_name']
]
:param max_level: An integ... | [
"def",
"get_layout_objects",
"(",
"self",
",",
"*",
"LayoutClasses",
",",
"*",
"*",
"kwargs",
")",
":",
"index",
"=",
"kwargs",
".",
"pop",
"(",
"\"index\"",
",",
"None",
")",
"max_level",
"=",
"kwargs",
".",
"pop",
"(",
"\"max_level\"",
",",
"0",
")",... | [
53,
4
] | [
92,
23
] | python | en | ['en', 'ja', 'th'] | False |
BaseInput.render | (self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs) |
Renders an `<input />` if container is used as a Layout object.
Input button value can be a variable in context.
|
Renders an `<input />` if container is used as a Layout object.
Input button value can be a variable in context.
| def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
"""
Renders an `<input />` if container is used as a Layout object.
Input button value can be a variable in context.
"""
self.value = Template(str(self.value)).render(context)
templa... | [
"def",
"render",
"(",
"self",
",",
"form",
",",
"form_style",
",",
"context",
",",
"template_pack",
"=",
"TEMPLATE_PACK",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"value",
"=",
"Template",
"(",
"str",
"(",
"self",
".",
"value",
")",
")",
".",
... | [
188,
4
] | [
197,
60
] | python | en | ['en', 'ja', 'th'] | False |
trim_docstring | (docstring) |
Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation
|
Uniformly trims leading/trailing whitespace from docstrings. | def trim_docstring(docstring):
"""
Uniformly trims leading/trailing whitespace from docstrings.
Based on http://www.python.org/peps/pep-0257.html#handling-docstring-indentation
"""
if not docstring or not docstring.strip():
return ''
# Convert tabs to spaces and split into lines
lin... | [
"def",
"trim_docstring",
"(",
"docstring",
")",
":",
"if",
"not",
"docstring",
"or",
"not",
"docstring",
".",
"strip",
"(",
")",
":",
"return",
"''",
"# Convert tabs to spaces and split into lines",
"lines",
"=",
"docstring",
".",
"expandtabs",
"(",
")",
".",
... | [
19,
0
] | [
31,
37
] | python | en | ['en', 'error', 'th'] | False |
parse_docstring | (docstring) |
Parse out the parts of a docstring. Returns (title, body, metadata).
|
Parse out the parts of a docstring. Returns (title, body, metadata).
| def parse_docstring(docstring):
"""
Parse out the parts of a docstring. Returns (title, body, metadata).
"""
docstring = trim_docstring(docstring)
parts = re.split(r'\n{2,}', docstring)
title = parts[0]
if len(parts) == 1:
body = ''
metadata = {}
else:
parser = H... | [
"def",
"parse_docstring",
"(",
"docstring",
")",
":",
"docstring",
"=",
"trim_docstring",
"(",
"docstring",
")",
"parts",
"=",
"re",
".",
"split",
"(",
"r'\\n{2,}'",
",",
"docstring",
")",
"title",
"=",
"parts",
"[",
"0",
"]",
"if",
"len",
"(",
"parts",
... | [
34,
0
] | [
57,
32
] | python | en | ['en', 'error', 'th'] | False |
parse_rst | (text, default_reference_context, thing_being_parsed=None) |
Convert the string from reST to an XHTML fragment.
|
Convert the string from reST to an XHTML fragment.
| def parse_rst(text, default_reference_context, thing_being_parsed=None):
"""
Convert the string from reST to an XHTML fragment.
"""
overrides = {
'doctitle_xform': True,
'inital_header_level': 3,
"default_reference_context": default_reference_context,
"link_base": reverse... | [
"def",
"parse_rst",
"(",
"text",
",",
"default_reference_context",
",",
"thing_being_parsed",
"=",
"None",
")",
":",
"overrides",
"=",
"{",
"'doctitle_xform'",
":",
"True",
",",
"'inital_header_level'",
":",
"3",
",",
"\"default_reference_context\"",
":",
"default_r... | [
60,
0
] | [
84,
39
] | python | en | ['en', 'error', 'th'] | False |
profiled | (func: FuncT) |
This decorator should obviously be used only in a dev environment.
It works best when surrounding a function that you expect to be
called once. One strategy is to write a backend test and wrap the
test case with the profiled decorator.
You can run a single test case like this:
# edit zer... |
This decorator should obviously be used only in a dev environment.
It works best when surrounding a function that you expect to be
called once. One strategy is to write a backend test and wrap the
test case with the profiled decorator. | def profiled(func: FuncT) -> FuncT:
"""
This decorator should obviously be used only in a dev environment.
It works best when surrounding a function that you expect to be
called once. One strategy is to write a backend test and wrap the
test case with the profiled decorator.
You can run a sing... | [
"def",
"profiled",
"(",
"func",
":",
"FuncT",
")",
"->",
"FuncT",
":",
"func_",
":",
"Callable",
"[",
"...",
",",
"object",
"]",
"=",
"func",
"# work around https://github.com/python/mypy/issues/9075",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped_func",
"("... | [
7,
0
] | [
34,
36
] | python | en | ['en', 'error', 'th'] | False |
sensitive_variables | (*variables) |
Indicates which variables used in the decorated function are sensitive, so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Two forms are accepted:
* with specified variable names:
@sensitive_variables('user', 'pass... |
Indicates which variables used in the decorated function are sensitive, so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_variables(*variables):
"""
Indicates which variables used in the decorated function are sensitive, so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Two forms are accepted:
* with specified variable names:... | [
"def",
"sensitive_variables",
"(",
"*",
"variables",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"sensitive_variables_wrapper",
"(",
"*",
"func_args",
",",
"*",
"*",
"func_kwargs",
")",
":",... | [
5,
0
] | [
37,
20
] | python | en | ['en', 'error', 'th'] | False |
sensitive_post_parameters | (*parameters) |
Indicates which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Two forms are accepted:
* with specified parameters:
@sensitive_post_parameters('passwor... |
Indicates which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_post_parameters(*parameters):
"""
Indicates which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Two forms are accepted:
* with specified param... | [
"def",
"sensitive_post_parameters",
"(",
"*",
"parameters",
")",
":",
"def",
"decorator",
"(",
"view",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"view",
")",
"def",
"sensitive_post_parameters_wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
... | [
40,
0
] | [
77,
20
] | python | en | ['en', 'error', 'th'] | False |
ordinal | (value) |
Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
3 is '3rd', etc. Works for any integer.
|
Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
3 is '3rd', etc. Works for any integer.
| def ordinal(value):
"""
Convert an integer to its ordinal as a string. 1 is '1st', 2 is '2nd',
3 is '3rd', etc. Works for any integer.
"""
try:
value = int(value)
except (TypeError, ValueError):
return value
if value % 100 in (11, 12, 13):
# Translators: Ordinal forma... | [
"def",
"ordinal",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"value",
"if",
"value",
"%",
"100",
"in",
"(",
"11",
",",
"12",
",",
"13",
")",
":",
... | [
19,
0
] | [
56,
27
] | python | en | ['en', 'error', 'th'] | False |
intcomma | (value, use_l10n=True) |
Convert an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
|
Convert an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
| def intcomma(value, use_l10n=True):
"""
Convert an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
if settings.USE_L10N and use_l10n:
try:
if not isinstance(value, (float, Decimal)):
value... | [
"def",
"intcomma",
"(",
"value",
",",
"use_l10n",
"=",
"True",
")",
":",
"if",
"settings",
".",
"USE_L10N",
"and",
"use_l10n",
":",
"try",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"float",
",",
"Decimal",
")",
")",
":",
"value",
"=",
... | [
60,
0
] | [
78,
38
] | python | en | ['en', 'error', 'th'] | False |
intword | (value) |
Convert a large integer to a friendly text representation. Works best
for numbers over 1 million. For example, 1000000 becomes '1.0 million',
1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
|
Convert a large integer to a friendly text representation. Works best
for numbers over 1 million. For example, 1000000 becomes '1.0 million',
1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
| def intword(value):
"""
Convert a large integer to a friendly text representation. Works best
for numbers over 1 million. For example, 1000000 becomes '1.0 million',
1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'.
"""
try:
value = int(value)
except (TypeError, V... | [
"def",
"intword",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"value",
"if",
"value",
"<",
"1000000",
":",
"return",
"value",
"def",
"_check_for_i18n",
"... | [
131,
0
] | [
162,
16
] | python | en | ['en', 'error', 'th'] | False |
apnumber | (value) |
For numbers 1-9, return the number spelled out. Otherwise, return the
number. This follows Associated Press style.
|
For numbers 1-9, return the number spelled out. Otherwise, return the
number. This follows Associated Press style.
| def apnumber(value):
"""
For numbers 1-9, return the number spelled out. Otherwise, return the
number. This follows Associated Press style.
"""
try:
value = int(value)
except (TypeError, ValueError):
return value
if not 0 < value < 10:
return value
return (_('one'... | [
"def",
"apnumber",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"value",
"if",
"not",
"0",
"<",
"value",
"<",
"10",
":",
"return",
"value",
"return",
... | [
166,
0
] | [
178,
67
] | python | en | ['en', 'error', 'th'] | False |
naturalday | (value, arg=None) |
For date values that are tomorrow, today or yesterday compared to
present day return representing string. Otherwise, return a string
formatted according to settings.DATE_FORMAT.
|
For date values that are tomorrow, today or yesterday compared to
present day return representing string. Otherwise, return a string
formatted according to settings.DATE_FORMAT.
| def naturalday(value, arg=None):
"""
For date values that are tomorrow, today or yesterday compared to
present day return representing string. Otherwise, return a string
formatted according to settings.DATE_FORMAT.
"""
tzinfo = getattr(value, 'tzinfo', None)
try:
value = date(value.y... | [
"def",
"naturalday",
"(",
"value",
",",
"arg",
"=",
"None",
")",
":",
"tzinfo",
"=",
"getattr",
"(",
"value",
",",
"'tzinfo'",
",",
"None",
")",
"try",
":",
"value",
"=",
"date",
"(",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
... | [
184,
0
] | [
204,
42
] | python | en | ['en', 'error', 'th'] | False |
naturaltime | (value) |
For date and time values show how many seconds, minutes, or hours ago
compared to current timestamp return representing string.
|
For date and time values show how many seconds, minutes, or hours ago
compared to current timestamp return representing string.
| def naturaltime(value):
"""
For date and time values show how many seconds, minutes, or hours ago
compared to current timestamp return representing string.
"""
return NaturalTimeFormatter.string_for(value) | [
"def",
"naturaltime",
"(",
"value",
")",
":",
"return",
"NaturalTimeFormatter",
".",
"string_for",
"(",
"value",
")"
] | [
210,
0
] | [
215,
49
] | python | en | ['en', 'error', 'th'] | False |
localize | (value) |
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
|
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
| def localize(value):
"""
Forces a value to be rendered as a localized value,
regardless of the value of ``settings.USE_L10N``.
"""
return force_text(formats.localize(value, use_l10n=True)) | [
"def",
"localize",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"formats",
".",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"True",
")",
")"
] | [
9,
0
] | [
14,
61
] | python | en | ['en', 'error', 'th'] | False |
unlocalize | (value) |
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
|
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
| def unlocalize(value):
"""
Forces a value to be rendered as a non-localized value,
regardless of the value of ``settings.USE_L10N``.
"""
return force_text(value) | [
"def",
"unlocalize",
"(",
"value",
")",
":",
"return",
"force_text",
"(",
"value",
")"
] | [
18,
0
] | [
23,
28
] | python | en | ['en', 'error', 'th'] | False |
localize_tag | (parser, token) |
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`.
Sample usage::
{% localize off %}
var pi = {{ 3.1415 }};
{% endlocalize %}
|
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`. | def localize_tag(parser, token):
"""
Forces or prevents localization of values, regardless of the value of
`settings.USE_L10N`.
Sample usage::
{% localize off %}
var pi = {{ 3.1415 }};
{% endlocalize %}
"""
use_l10n = None
bits = list(token.split_contents())
... | [
"def",
"localize_tag",
"(",
"parser",
",",
"token",
")",
":",
"use_l10n",
"=",
"None",
"bits",
"=",
"list",
"(",
"token",
".",
"split_contents",
"(",
")",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"use_l10n",
"=",
"True",
"elif",
"len",
"... | [
43,
0
] | [
65,
43
] | python | en | ['en', 'error', 'th'] | False |
get_image | (path) |
(string) -> numpy.ndarray
returns image for given path
|
(string) -> numpy.ndarray
returns image for given path
| def get_image(path):
"""
(string) -> numpy.ndarray
returns image for given path
"""
return cv2.imread(path) | [
"def",
"get_image",
"(",
"path",
")",
":",
"return",
"cv2",
".",
"imread",
"(",
"path",
")"
] | [
28,
0
] | [
33,
27
] | python | en | ['en', 'error', 'th'] | False |
extract_information | (image) |
(numpy.ndarray) -> list
returns list of text extracted from given image
|
(numpy.ndarray) -> list
returns list of text extracted from given image
| def extract_information(image):
"""
(numpy.ndarray) -> list
returns list of text extracted from given image
"""
extracted_info = pytesseract.image_to_string(image).strip().replace("\n\n", "\n")
extracted_info_list = list(extracted_info.split("\n"))
extracted_info_list = list(filter(lambda it... | [
"def",
"extract_information",
"(",
"image",
")",
":",
"extracted_info",
"=",
"pytesseract",
".",
"image_to_string",
"(",
"image",
")",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\"\\n\\n\"",
",",
"\"\\n\"",
")",
"extracted_info_list",
"=",
"list",
"(",
"e... | [
35,
0
] | [
44,
30
] | python | en | ['en', 'error', 'th'] | False |
helper_capitalize | (text) |
(string) -> string
proprely capitalize course titles
|
(string) -> string
proprely capitalize course titles
| def helper_capitalize(text):
"""
(string) -> string
proprely capitalize course titles
"""
capitalized = ''
for char in text:
if char.isalpha():
capitalized += char.upper()
else:
capitalized += char
return capitalized | [
"def",
"helper_capitalize",
"(",
"text",
")",
":",
"capitalized",
"=",
"''",
"for",
"char",
"in",
"text",
":",
"if",
"char",
".",
"isalpha",
"(",
")",
":",
"capitalized",
"+=",
"char",
".",
"upper",
"(",
")",
"else",
":",
"capitalized",
"+=",
"char",
... | [
46,
0
] | [
58,
22
] | python | en | ['en', 'error', 'th'] | False |
get_courses | (info_list) |
(list) -> list
returns list of courses of type Course from given list of raw extracted text
|
(list) -> list
returns list of courses of type Course from given list of raw extracted text
| def get_courses(info_list):
"""
(list) -> list
returns list of courses of type Course from given list of raw extracted text
"""
WEEKDAYS = set(["monday", "tuesday", "wednesday", "thursday", "friday"])
courses = []
day = 'Monday'
i = 0
while i < len(info_list):
current = info... | [
"def",
"get_courses",
"(",
"info_list",
")",
":",
"WEEKDAYS",
"=",
"set",
"(",
"[",
"\"monday\"",
",",
"\"tuesday\"",
",",
"\"wednesday\"",
",",
"\"thursday\"",
",",
"\"friday\"",
"]",
")",
"courses",
"=",
"[",
"]",
"day",
"=",
"'Monday'",
"i",
"=",
"0",... | [
60,
0
] | [
99,
18
] | python | en | ['en', 'error', 'th'] | False |
get_schedule | (path) |
(string) -> list
returns list of courses given the path to an image
|
(string) -> list
returns list of courses given the path to an image
| def get_schedule(path):
"""
(string) -> list
returns list of courses given the path to an image
"""
img = get_image(path)
info_list = extract_information(img)
courses = get_courses(info_list)
return courses | [
"def",
"get_schedule",
"(",
"path",
")",
":",
"img",
"=",
"get_image",
"(",
"path",
")",
"info_list",
"=",
"extract_information",
"(",
"img",
")",
"courses",
"=",
"get_courses",
"(",
"info_list",
")",
"return",
"courses"
] | [
101,
0
] | [
110,
18
] | python | en | ['en', 'error', 'th'] | False |
get_academic_term | (academic_term) |
(string) -> tuple
returns the start and end dates of the given academic term
|
(string) -> tuple
returns the start and end dates of the given academic term
| def get_academic_term(academic_term):
"""
(string) -> tuple
returns the start and end dates of the given academic term
"""
term = ACADEMIC_TERMS[academic_term]
start = term[0:5]
end = term[8:]
return start, end | [
"def",
"get_academic_term",
"(",
"academic_term",
")",
":",
"term",
"=",
"ACADEMIC_TERMS",
"[",
"academic_term",
"]",
"start",
"=",
"term",
"[",
"0",
":",
"5",
"]",
"end",
"=",
"term",
"[",
"8",
":",
"]",
"return",
"start",
",",
"end"
] | [
115,
0
] | [
124,
21
] | python | en | ['en', 'error', 'th'] | False |
next_weekday | (d, weekday) |
(datetime, string) -> datetime
returns the first ocurrence of the given weekday after the initial datetime d
|
(datetime, string) -> datetime
returns the first ocurrence of the given weekday after the initial datetime d
| def next_weekday(d, weekday):
"""
(datetime, string) -> datetime
returns the first ocurrence of the given weekday after the initial datetime d
"""
days_ahead = weekday - d.weekday()
if days_ahead <= 0:
days_ahead += 7
return d + datetime.timedelta(days_ahead) | [
"def",
"next_weekday",
"(",
"d",
",",
"weekday",
")",
":",
"days_ahead",
"=",
"weekday",
"-",
"d",
".",
"weekday",
"(",
")",
"if",
"days_ahead",
"<=",
"0",
":",
"days_ahead",
"+=",
"7",
"return",
"d",
"+",
"datetime",
".",
"timedelta",
"(",
"days_ahead... | [
126,
0
] | [
134,
45
] | python | en | ['en', 'error', 'th'] | False |
create_event | (course, academic_term, year) |
(course, string) -> event
returns an event created from the course contents, complying with the dates of the academic_term
|
(course, string) -> event
returns an event created from the course contents, complying with the dates of the academic_term
| def create_event(course, academic_term, year):
"""
(course, string) -> event
returns an event created from the course contents, complying with the dates of the academic_term
"""
event = Event()
event.add('summary', f"{course.title} - {course.type}".strip().replace(" ", " "))
event['location... | [
"def",
"create_event",
"(",
"course",
",",
"academic_term",
",",
"year",
")",
":",
"event",
"=",
"Event",
"(",
")",
"event",
".",
"add",
"(",
"'summary'",
",",
"f\"{course.title} - {course.type}\"",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\" \"",
",... | [
136,
0
] | [
171,
16
] | python | en | ['en', 'error', 'th'] | False |
write_calendar | (calendar, academic_term) |
(icalendar, string) -> writes the given icalendar to an .ics file
|
(icalendar, string) -> writes the given icalendar to an .ics file
| def write_calendar(calendar, academic_term):
"""
(icalendar, string) -> writes the given icalendar to an .ics file
"""
path = join(dirname(realpath(__file__)), '../image/uploads/timetable.ics')
with open(path, 'wb') as ics:
ics.write(calendar.to_ical()) | [
"def",
"write_calendar",
"(",
"calendar",
",",
"academic_term",
")",
":",
"path",
"=",
"join",
"(",
"dirname",
"(",
"realpath",
"(",
"__file__",
")",
")",
",",
"'../image/uploads/timetable.ics'",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"i... | [
173,
0
] | [
179,
37
] | python | en | ['en', 'error', 'th'] | False |
create_calendar | (academic_term, year, path) |
(string, integer, list) -> creates calendar based on all events created from list of courses
|
(string, integer, list) -> creates calendar based on all events created from list of courses
| def create_calendar(academic_term, year, path):
"""
(string, integer, list) -> creates calendar based on all events created from list of courses
"""
cal = Calendar()
classes = get_schedule(path)
for course in classes:
event = create_event(course, academic_term, year)
cal.add_com... | [
"def",
"create_calendar",
"(",
"academic_term",
",",
"year",
",",
"path",
")",
":",
"cal",
"=",
"Calendar",
"(",
")",
"classes",
"=",
"get_schedule",
"(",
"path",
")",
"for",
"course",
"in",
"classes",
":",
"event",
"=",
"create_event",
"(",
"course",
",... | [
181,
0
] | [
192,
38
] | python | en | ['en', 'error', 'th'] | False |
main | (args=None) | This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
| This is preserved for old console scripts that may still be referencing
it. | def main(args=None):
# type: (Optional[List[str]]) -> int
"""This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args) | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"# type: (Optional[List[str]]) -> int",
"from",
"pip",
".",
"_internal",
".",
"utils",
".",
"entrypoints",
"import",
"_wrapper",
"return",
"_wrapper",
"(",
"args",
")"
] | [
6,
0
] | [
15,
25
] | python | en | ['en', 'en', 'en'] | True |
CommandTests.test_explode | (self) | Test that an unknown command raises CommandError | Test that an unknown command raises CommandError | def test_explode(self):
""" Test that an unknown command raises CommandError """
self.assertRaises(CommandError, management.call_command, ('explode',)) | [
"def",
"test_explode",
"(",
"self",
")",
":",
"self",
".",
"assertRaises",
"(",
"CommandError",
",",
"management",
".",
"call_command",
",",
"(",
"'explode'",
",",
")",
")"
] | [
34,
4
] | [
36,
78
] | python | en | ['en', 'fr', 'en'] | True |
CommandTests.test_system_exit | (self) | Exception raised in a command should raise CommandError with
call_command, but SystemExit when run from command line
| Exception raised in a command should raise CommandError with
call_command, but SystemExit when run from command line
| def test_system_exit(self):
""" Exception raised in a command should raise CommandError with
call_command, but SystemExit when run from command line
"""
with self.assertRaises(CommandError):
management.call_command('dance', example="raise")
old_stderr = sys.stderr... | [
"def",
"test_system_exit",
"(",
"self",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"CommandError",
")",
":",
"management",
".",
"call_command",
"(",
"'dance'",
",",
"example",
"=",
"\"raise\"",
")",
"old_stderr",
"=",
"sys",
".",
"stderr",
"sys",
... | [
38,
4
] | [
51,
53
] | python | en | ['en', 'en', 'en'] | True |
CommandTests.test_find_command_without_PATH | (self) |
find_command should still work when the PATH environment variable
doesn't exist (#22256).
|
find_command should still work when the PATH environment variable
doesn't exist (#22256).
| def test_find_command_without_PATH(self):
"""
find_command should still work when the PATH environment variable
doesn't exist (#22256).
"""
current_path = os.environ.pop('PATH', None)
try:
self.assertIsNone(find_command('_missing_'))
finally:
... | [
"def",
"test_find_command_without_PATH",
"(",
"self",
")",
":",
"current_path",
"=",
"os",
".",
"environ",
".",
"pop",
"(",
"'PATH'",
",",
"None",
")",
"try",
":",
"self",
".",
"assertIsNone",
"(",
"find_command",
"(",
"'_missing_'",
")",
")",
"finally",
"... | [
67,
4
] | [
78,
49
] | python | en | ['en', 'error', 'th'] | False |
CommandTests.test_call_command_option_parsing | (self) |
When passing the long option name to call_command, the available option
key is the option dest name (#22985).
|
When passing the long option name to call_command, the available option
key is the option dest name (#22985).
| def test_call_command_option_parsing(self):
"""
When passing the long option name to call_command, the available option
key is the option dest name (#22985).
"""
out = StringIO()
management.call_command('dance', stdout=out, opt_3=True)
self.assertIn("option3", out... | [
"def",
"test_call_command_option_parsing",
"(",
"self",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"management",
".",
"call_command",
"(",
"'dance'",
",",
"stdout",
"=",
"out",
",",
"opt_3",
"=",
"True",
")",
"self",
".",
"assertIn",
"(",
"\"option3\"",
"... | [
80,
4
] | [
89,
49
] | python | en | ['en', 'error', 'th'] | False |
CommandTests.test_optparse_compatibility | (self) |
optparse should be supported during Django 1.8/1.9 releases.
|
optparse should be supported during Django 1.8/1.9 releases.
| def test_optparse_compatibility(self):
"""
optparse should be supported during Django 1.8/1.9 releases.
"""
out = StringIO()
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
management.call_command('optpa... | [
"def",
"test_optparse_compatibility",
"(",
"self",
")",
":",
"out",
"=",
"StringIO",
"(",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"RemovedInDjango20Warning",
")",
... | [
91,
4
] | [
109,
73
] | python | en | ['en', 'error', 'th'] | False |
shortcut | (request, content_type_id, object_id) |
Redirect to an object's page based on a content-type ID and an object ID.
|
Redirect to an object's page based on a content-type ID and an object ID.
| def shortcut(request, content_type_id, object_id):
"""
Redirect to an object's page based on a content-type ID and an object ID.
"""
# Look up the object, making sure it's got a get_absolute_url() function.
try:
content_type = ContentType.objects.get(pk=content_type_id)
if not conten... | [
"def",
"shortcut",
"(",
"request",
",",
"content_type_id",
",",
"object_id",
")",
":",
"# Look up the object, making sure it's got a get_absolute_url() function.",
"try",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"content_type_... | [
8,
0
] | [
87,
43
] | python | en | ['en', 'error', 'th'] | False |
ogrinfo | (data_source, num_features=10) |
Walk the available layers in the supplied `data_source`, displaying
the fields for the first `num_features` features.
|
Walk the available layers in the supplied `data_source`, displaying
the fields for the first `num_features` features.
| def ogrinfo(data_source, num_features=10):
"""
Walk the available layers in the supplied `data_source`, displaying
the fields for the first `num_features` features.
"""
# Checking the parameters.
if isinstance(data_source, str):
data_source = DataSource(data_source)
elif isinstance(... | [
"def",
"ogrinfo",
"(",
"data_source",
",",
"num_features",
"=",
"10",
")",
":",
"# Checking the parameters.",
"if",
"isinstance",
"(",
"data_source",
",",
"str",
")",
":",
"data_source",
"=",
"DataSource",
"(",
"data_source",
")",
"elif",
"isinstance",
"(",
"d... | [
10,
0
] | [
50,
29
] | python | en | ['en', 'error', 'th'] | False |
get_abi3_suffix | () | Return the file extension for an abi3-compliant Extension() | Return the file extension for an abi3-compliant Extension() | def get_abi3_suffix():
"""Return the file extension for an abi3-compliant Extension()"""
for suffix in EXTENSION_SUFFIXES:
if '.abi3' in suffix: # Unix
return suffix
elif suffix == '.pyd': # Windows
return suffix | [
"def",
"get_abi3_suffix",
"(",
")",
":",
"for",
"suffix",
"in",
"EXTENSION_SUFFIXES",
":",
"if",
"'.abi3'",
"in",
"suffix",
":",
"# Unix",
"return",
"suffix",
"elif",
"suffix",
"==",
"'.pyd'",
":",
"# Windows",
"return",
"suffix"
] | [
73,
0
] | [
79,
25
] | python | en | ['en', 'en', 'en'] | True |
build_ext.run | (self) | Build extensions in build directory, then copy if --inplace | Build extensions in build directory, then copy if --inplace | def run(self):
"""Build extensions in build directory, then copy if --inplace"""
old_inplace, self.inplace = self.inplace, 0
_build_ext.run(self)
self.inplace = old_inplace
if old_inplace:
self.copy_extensions_to_source() | [
"def",
"run",
"(",
"self",
")",
":",
"old_inplace",
",",
"self",
".",
"inplace",
"=",
"self",
".",
"inplace",
",",
"0",
"_build_ext",
".",
"run",
"(",
"self",
")",
"self",
".",
"inplace",
"=",
"old_inplace",
"if",
"old_inplace",
":",
"self",
".",
"co... | [
83,
4
] | [
89,
44
] | python | en | ['en', 'en', 'en'] | True |
build_ext.links_to_dynamic | (self, ext) | Return true if 'ext' links to a dynamic lib in the same package | Return true if 'ext' links to a dynamic lib in the same package | def links_to_dynamic(self, ext):
"""Return true if 'ext' links to a dynamic lib in the same package"""
# XXX this should check to ensure the lib is actually being built
# XXX as dynamic, and not just using a locally-found version or a
# XXX static-compiled version
libnames = dict... | [
"def",
"links_to_dynamic",
"(",
"self",
",",
"ext",
")",
":",
"# XXX this should check to ensure the lib is actually being built",
"# XXX as dynamic, and not just using a locally-found version or a",
"# XXX static-compiled version",
"libnames",
"=",
"dict",
".",
"fromkeys",
"(",
"[... | [
214,
4
] | [
221,
74
] | python | en | ['en', 'en', 'en'] | True |
split_unquoted_newlines | (stmt) | Split a string on all unquoted newlines.
Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite
character is inside of a string. | Split a string on all unquoted newlines. | def split_unquoted_newlines(stmt):
"""Split a string on all unquoted newlines.
Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite
character is inside of a string."""
text = text_type(stmt)
lines = SPLIT_REGEX.split(text)
outputlines = ['']
for line in lines:
if n... | [
"def",
"split_unquoted_newlines",
"(",
"stmt",
")",
":",
"text",
"=",
"text_type",
"(",
"stmt",
")",
"lines",
"=",
"SPLIT_REGEX",
".",
"split",
"(",
"text",
")",
"outputlines",
"=",
"[",
"''",
"]",
"for",
"line",
"in",
"lines",
":",
"if",
"not",
"line"... | [
37,
0
] | [
52,
22
] | python | en | ['en', 'en', 'en'] | True |
remove_quotes | (val) | Helper that removes surrounding quotes from strings. | Helper that removes surrounding quotes from strings. | def remove_quotes(val):
"""Helper that removes surrounding quotes from strings."""
if val is None:
return
if val[0] in ('"', "'") and val[0] == val[-1]:
val = val[1:-1]
return val | [
"def",
"remove_quotes",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"if",
"val",
"[",
"0",
"]",
"in",
"(",
"'\"'",
",",
"\"'\"",
")",
"and",
"val",
"[",
"0",
"]",
"==",
"val",
"[",
"-",
"1",
"]",
":",
"val",
"=",
"val",
... | [
55,
0
] | [
61,
14
] | python | en | ['en', 'en', 'en'] | True |
recurse | (*cls) | Function decorator to help with recursion
:param cls: Classes to not recurse over
:return: function
| Function decorator to help with recursion | def recurse(*cls):
"""Function decorator to help with recursion
:param cls: Classes to not recurse over
:return: function
"""
def wrap(f):
def wrapped_f(tlist):
for sgroup in tlist.get_sublists():
if not isinstance(sgroup, cls):
wrapped_f(sgro... | [
"def",
"recurse",
"(",
"*",
"cls",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"wrapped_f",
"(",
"tlist",
")",
":",
"for",
"sgroup",
"in",
"tlist",
".",
"get_sublists",
"(",
")",
":",
"if",
"not",
"isinstance",
"(",
"sgroup",
",",
"cls",
... | [
64,
0
] | [
79,
15
] | python | en | ['en', 'en', 'en'] | True |
imt | (token, i=None, m=None, t=None) | Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param t: TokenType or Tuple/List of TokenTypes
:return: bool
| Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param t: TokenType or Tuple/List of TokenTypes
:return: bool
| def imt(token, i=None, m=None, t=None):
"""Helper function to simplify comparisons Instance, Match and TokenType
:param token:
:param i: Class or Tuple/List of Classes
:param m: Tuple of TokenType & Value. Can be list of Tuple for multiple
:param t: TokenType or Tuple/List of TokenTypes
:return:... | [
"def",
"imt",
"(",
"token",
",",
"i",
"=",
"None",
",",
"m",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"clss",
"=",
"i",
"types",
"=",
"[",
"t",
",",
"]",
"if",
"t",
"and",
"not",
"isinstance",
"(",
"t",
",",
"list",
")",
"else",
"t",
... | [
82,
0
] | [
103,
20
] | python | en | ['en', 'en', 'en'] | True |
consume | (iterator, n) | Advance the iterator n-steps ahead. If n is none, consume entirely. | Advance the iterator n-steps ahead. If n is none, consume entirely. | def consume(iterator, n):
"""Advance the iterator n-steps ahead. If n is none, consume entirely."""
deque(itertools.islice(iterator, n), maxlen=0) | [
"def",
"consume",
"(",
"iterator",
",",
"n",
")",
":",
"deque",
"(",
"itertools",
".",
"islice",
"(",
"iterator",
",",
"n",
")",
",",
"maxlen",
"=",
"0",
")"
] | [
106,
0
] | [
108,
50
] | python | en | ['en', 'en', 'en'] | True |
autocomplete | () | Entry Point for completion of main and subcommand options.
| Entry Point for completion of main and subcommand options.
| def autocomplete():
# type: () -> None
"""Entry Point for completion of main and subcommand options.
"""
# Don't complete if user hasn't sourced bash_completion file.
if 'PIP_AUTO_COMPLETE' not in os.environ:
return
cwords = os.environ['COMP_WORDS'].split()[1:]
cword = int(os.environ... | [
"def",
"autocomplete",
"(",
")",
":",
"# type: () -> None",
"# Don't complete if user hasn't sourced bash_completion file.",
"if",
"'PIP_AUTO_COMPLETE'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"cwords",
"=",
"os",
".",
"environ",
"[",
"'COMP_WORDS'",
"]",
"... | [
17,
0
] | [
109,
15
] | python | en | ['en', 'en', 'en'] | True |
get_path_completion_type | (cwords, cword, opts) | Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_CWORD``
:param opts: The available options to check
:return: path completion type (``file``, ``dir``, ``path`` o... | Get the type of path completion (``file``, ``dir``, ``path`` or None) | def get_path_completion_type(cwords, cword, opts):
# type: (List[str], int, Iterable[Any]) -> Optional[str]
"""Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_C... | [
"def",
"get_path_completion_type",
"(",
"cwords",
",",
"cword",
",",
"opts",
")",
":",
"# type: (List[str], int, Iterable[Any]) -> Optional[str]",
"if",
"cword",
"<",
"2",
"or",
"not",
"cwords",
"[",
"cword",
"-",
"2",
"]",
".",
"startswith",
"(",
"'-'",
")",
... | [
112,
0
] | [
132,
15
] | python | en | ['en', 'en', 'en'] | True |
auto_complete_paths | (current, completion_type) | If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(`file`, `path` or `dir`)i
:return: A gen... | If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``. | def auto_complete_paths(current, completion_type):
# type: (str, str) -> Iterable[str]
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be compl... | [
"def",
"auto_complete_paths",
"(",
"current",
",",
"completion_type",
")",
":",
"# type: (str, str) -> Iterable[str]",
"directory",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"current",
")",
"current_path",
"=",
"os",
".",
"path",
".",
"abspath"... | [
135,
0
] | [
163,
45
] | python | en | ['en', 'en', 'en'] | True |
config | (env=DEFAULT_ENV, default=None, engine=None, conn_max_age=0, ssl_require=False) | Returns configured DATABASE dictionary from DATABASE_URL. | Returns configured DATABASE dictionary from DATABASE_URL. | def config(env=DEFAULT_ENV, default=None, engine=None, conn_max_age=0, ssl_require=False):
"""Returns configured DATABASE dictionary from DATABASE_URL."""
config = {}
s = os.environ.get(env, default)
if s:
config = parse(s, engine, conn_max_age, ssl_require)
return config | [
"def",
"config",
"(",
"env",
"=",
"DEFAULT_ENV",
",",
"default",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"conn_max_age",
"=",
"0",
",",
"ssl_require",
"=",
"False",
")",
":",
"config",
"=",
"{",
"}",
"s",
"=",
"os",
".",
"environ",
".",
"get"... | [
46,
0
] | [
56,
17
] | python | en | ['en', 'en', 'en'] | True |
parse | (url, engine=None, conn_max_age=0, ssl_require=False) | Parses a database URL. | Parses a database URL. | def parse(url, engine=None, conn_max_age=0, ssl_require=False):
"""Parses a database URL."""
if url == 'sqlite://:memory:':
# this is a special case, because if we pass this URL into
# urlparse, urlparse will choke trying to interpret "memory"
# as a port number
return {
... | [
"def",
"parse",
"(",
"url",
",",
"engine",
"=",
"None",
",",
"conn_max_age",
"=",
"0",
",",
"ssl_require",
"=",
"False",
")",
":",
"if",
"url",
"==",
"'sqlite://:memory:'",
":",
"# this is a special case, because if we pass this URL into",
"# urlparse, urlparse will c... | [
59,
0
] | [
143,
17
] | python | en | ['en', 'en', 'en'] | True |
MigrationExecutor.migration_plan | (self, targets) |
Given a set of targets, returns a list of (Migration instance, backwards?).
|
Given a set of targets, returns a list of (Migration instance, backwards?).
| def migration_plan(self, targets):
"""
Given a set of targets, returns a list of (Migration instance, backwards?).
"""
plan = []
applied = set(self.loader.applied_migrations)
for target in targets:
# If the target is (app_label, None), that means unmigrate eve... | [
"def",
"migration_plan",
"(",
"self",
",",
"targets",
")",
":",
"plan",
"=",
"[",
"]",
"applied",
"=",
"set",
"(",
"self",
".",
"loader",
".",
"applied_migrations",
")",
"for",
"target",
"in",
"targets",
":",
"# If the target is (app_label, None), that means unm... | [
20,
4
] | [
52,
19
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.migrate | (self, targets, plan=None, fake=False) |
Migrates the database up to the given targets.
|
Migrates the database up to the given targets.
| def migrate(self, targets, plan=None, fake=False):
"""
Migrates the database up to the given targets.
"""
if plan is None:
plan = self.migration_plan(targets)
for migration, backwards in plan:
if not backwards:
self.apply_migration(migratio... | [
"def",
"migrate",
"(",
"self",
",",
"targets",
",",
"plan",
"=",
"None",
",",
"fake",
"=",
"False",
")",
":",
"if",
"plan",
"is",
"None",
":",
"plan",
"=",
"self",
".",
"migration_plan",
"(",
"targets",
")",
"for",
"migration",
",",
"backwards",
"in"... | [
54,
4
] | [
64,
60
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.collect_sql | (self, plan) |
Takes a migration plan and returns a list of collected SQL
statements that represent the best-efforts version of that plan.
|
Takes a migration plan and returns a list of collected SQL
statements that represent the best-efforts version of that plan.
| def collect_sql(self, plan):
"""
Takes a migration plan and returns a list of collected SQL
statements that represent the best-efforts version of that plan.
"""
statements = []
for migration, backwards in plan:
with self.connection.schema_editor(collect_sql=Tr... | [
"def",
"collect_sql",
"(",
"self",
",",
"plan",
")",
":",
"statements",
"=",
"[",
"]",
"for",
"migration",
",",
"backwards",
"in",
"plan",
":",
"with",
"self",
".",
"connection",
".",
"schema_editor",
"(",
"collect_sql",
"=",
"True",
")",
"as",
"schema_e... | [
66,
4
] | [
80,
25
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.apply_migration | (self, migration, fake=False) |
Runs a migration forwards.
|
Runs a migration forwards.
| def apply_migration(self, migration, fake=False):
"""
Runs a migration forwards.
"""
if self.progress_callback:
self.progress_callback("apply_start", migration, fake)
if not fake:
# Test to see if this is an already-applied initial migration
if... | [
"def",
"apply_migration",
"(",
"self",
",",
"migration",
",",
"fake",
"=",
"False",
")",
":",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"apply_start\"",
",",
"migration",
",",
"fake",
")",
"if",
"not",
"fake",
":... | [
82,
4
] | [
105,
68
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.unapply_migration | (self, migration, fake=False) |
Runs a migration backwards.
|
Runs a migration backwards.
| def unapply_migration(self, migration, fake=False):
"""
Runs a migration backwards.
"""
if self.progress_callback:
self.progress_callback("unapply_start", migration, fake)
if not fake:
with self.connection.schema_editor() as schema_editor:
... | [
"def",
"unapply_migration",
"(",
"self",
",",
"migration",
",",
"fake",
"=",
"False",
")",
":",
"if",
"self",
".",
"progress_callback",
":",
"self",
".",
"progress_callback",
"(",
"\"unapply_start\"",
",",
"migration",
",",
"fake",
")",
"if",
"not",
"fake",
... | [
107,
4
] | [
125,
70
] | python | en | ['en', 'error', 'th'] | False |
MigrationExecutor.detect_soft_applied | (self, migration) |
Tests whether a migration has been implicitly applied - that the
tables it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel).
|
Tests whether a migration has been implicitly applied - that the
tables it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel).
| def detect_soft_applied(self, migration):
"""
Tests whether a migration has been implicitly applied - that the
tables it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel).
"""
project_state = self.loader.project_sta... | [
"def",
"detect_soft_applied",
"(",
"self",
",",
"migration",
")",
":",
"project_state",
"=",
"self",
".",
"loader",
".",
"project_state",
"(",
"(",
"migration",
".",
"app_label",
",",
"migration",
".",
"name",
")",
",",
"at_end",
"=",
"True",
")",
"apps",
... | [
127,
4
] | [
152,
37
] | python | en | ['en', 'error', 'th'] | False |
ReadFromWav | (data, batch_size) |
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
trans: a numpy array includes the targeted transcriptions (batch_size, )
max_length: the max length of the batch of audios
sample_rate_np: a numpy array
masks: a numpy array of size (batch_size, max_... |
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
trans: a numpy array includes the targeted transcriptions (batch_size, )
max_length: the max length of the batch of audios
sample_rate_np: a numpy array
masks: a numpy array of size (batch_size, max_... | def ReadFromWav(data, batch_size):
"""
Returns:
audios_np: a numpy array of size (batch_size, max_length) in float
trans: a numpy array includes the targeted transcriptions (batch_size, )
max_length: the max length of the batch of audios
sample_rate_np: a numpy array
mask... | [
"def",
"ReadFromWav",
"(",
"data",
",",
"batch_size",
")",
":",
"audios",
"=",
"[",
"]",
"lengths",
"=",
"[",
"]",
"# read the .wav file",
"for",
"i",
"in",
"range",
"(",
"batch_size",
")",
":",
"sample_rate_np",
",",
"audio_temp",
"=",
"wav",
".",
"read... | [
59,
0
] | [
105,
83
] | python | en | ['en', 'error', 'th'] | False |
Readrir | () |
Return:
rir: a numpy array of the room reverberation
|
Return:
rir: a numpy array of the room reverberation | def Readrir():
"""
Return:
rir: a numpy array of the room reverberation
"""
index = random.randint(1, FLAGS.num_rir)
_, rir = wav.read(FLAGS.root_dir + FLAGS.rir_dir + "_rir_" + str(index) + ".wav")
return rir | [
"def",
"Readrir",
"(",
")",
":",
"index",
"=",
"random",
".",
"randint",
"(",
"1",
",",
"FLAGS",
".",
"num_rir",
")",
"_",
",",
"rir",
"=",
"wav",
".",
"read",
"(",
"FLAGS",
".",
"root_dir",
"+",
"FLAGS",
".",
"rir_dir",
"+",
"\"_rir_\"",
"+",
"s... | [
108,
0
] | [
116,
14
] | python | en | ['en', 'error', 'th'] | False |
Attack.attack_stage1 | (
self,
audios,
trans,
maxlen,
sample_rate,
masks,
masks_freq,
num_loop,
data,
lengths,
) |
The first stage saves the adversarial examples that can successfully attack one room
|
The first stage saves the adversarial examples that can successfully attack one room
| def attack_stage1(
self,
audios,
trans,
maxlen,
sample_rate,
masks,
masks_freq,
num_loop,
data,
lengths,
):
"""
The first stage saves the adversarial examples that can successfully attack one room
"""
se... | [
"def",
"attack_stage1",
"(",
"self",
",",
"audios",
",",
"trans",
",",
"maxlen",
",",
"sample_rate",
",",
"masks",
",",
"masks_freq",
",",
"num_loop",
",",
"data",
",",
"lengths",
",",
")",
":",
"sess",
"=",
"self",
".",
"sess",
"# initialize and load the ... | [
227,
4
] | [
375,
39
] | python | en | ['en', 'error', 'th'] | False |
XViewMiddleware.process_view | (self, request, view_func, view_args, view_kwargs) |
If the request method is HEAD and either the IP is internal or the
user is a logged-in staff member, quickly return with an x-header
indicating the view function. This is used by the documentation module
to lookup the view function for an arbitrary page.
|
If the request method is HEAD and either the IP is internal or the
user is a logged-in staff member, quickly return with an x-header
indicating the view function. This is used by the documentation module
to lookup the view function for an arbitrary page.
| def process_view(self, request, view_func, view_args, view_kwargs):
"""
If the request method is HEAD and either the IP is internal or the
user is a logged-in staff member, quickly return with an x-header
indicating the view function. This is used by the documentation module
to ... | [
"def",
"process_view",
"(",
"self",
",",
"request",
",",
"view_func",
",",
"view_args",
",",
"view_kwargs",
")",
":",
"assert",
"hasattr",
"(",
"request",
",",
"'user'",
")",
",",
"(",
"\"The XView middleware requires authentication middleware to be \"",
"\"installed.... | [
8,
4
] | [
23,
27
] | python | en | ['en', 'error', 'th'] | False |
validate_tensor_spec | (spec) |
Validates a tensor spec
|
Validates a tensor spec
| def validate_tensor_spec(spec):
"""
Validates a tensor spec
"""
for item in spec:
name = item["name"]
dtype = item["dtype"]
shape = item["shape"]
if dtype not in ALLOWED_DTYPES:
raise ValueError("{} is not an allowed data type!".format(dtype))
if not... | [
"def",
"validate_tensor_spec",
"(",
"spec",
")",
":",
"for",
"item",
"in",
"spec",
":",
"name",
"=",
"item",
"[",
"\"name\"",
"]",
"dtype",
"=",
"item",
"[",
"\"dtype\"",
"]",
"shape",
"=",
"item",
"[",
"\"shape\"",
"]",
"if",
"dtype",
"not",
"in",
"... | [
35,
0
] | [
76,
17
] | python | en | ['en', 'error', 'th'] | False |
validate_neuropod_config | (config) |
Validates a neuropod config
|
Validates a neuropod config
| def validate_neuropod_config(config):
"""
Validates a neuropod config
"""
name = config["name"]
platform = config["platform"]
device_mapping = config["input_tensor_device"]
if not isinstance(name, string_types):
raise ValueError(
"Field 'name' in config must be a string!... | [
"def",
"validate_neuropod_config",
"(",
"config",
")",
":",
"name",
"=",
"config",
"[",
"\"name\"",
"]",
"platform",
"=",
"config",
"[",
"\"platform\"",
"]",
"device_mapping",
"=",
"config",
"[",
"\"input_tensor_device\"",
"]",
"if",
"not",
"isinstance",
"(",
... | [
79,
0
] | [
149,
13
] | python | en | ['en', 'error', 'th'] | False |
canonicalize_tensor_spec | (spec) |
Converts the datatypes in a tensor spec to canonical versions
(e.g. converts double to float64)
|
Converts the datatypes in a tensor spec to canonical versions
(e.g. converts double to float64)
| def canonicalize_tensor_spec(spec):
"""
Converts the datatypes in a tensor spec to canonical versions
(e.g. converts double to float64)
"""
transformed = []
for item in spec:
transformed.append(
{
"name": item["name"],
"dtype": get_dtype_name(i... | [
"def",
"canonicalize_tensor_spec",
"(",
"spec",
")",
":",
"transformed",
"=",
"[",
"]",
"for",
"item",
"in",
"spec",
":",
"transformed",
".",
"append",
"(",
"{",
"\"name\"",
":",
"item",
"[",
"\"name\"",
"]",
",",
"\"dtype\"",
":",
"get_dtype_name",
"(",
... | [
152,
0
] | [
166,
22
] | python | en | ['en', 'error', 'th'] | False |
write_neuropod_config | (
neuropod_path,
model_name,
platform,
input_spec,
output_spec,
platform_version_semver="*",
custom_ops=None,
input_tensor_device=None,
default_input_tensor_device="GPU",
**kwargs
) |
Creates the neuropod config file
:param neuropod_path: The path to a neuropod package
:param model_name: The name of the model (e.g. "my_addition_model")
:param platform: The model type (e.g. "python", "pytorch", "tensorflow", etc.)
:param platform_version_semver: The required plat... |
Creates the neuropod config file | def write_neuropod_config(
neuropod_path,
model_name,
platform,
input_spec,
output_spec,
platform_version_semver="*",
custom_ops=None,
input_tensor_device=None,
default_input_tensor_device="GPU",
**kwargs
):
"""
Creates the neuropod config file
:param neuropod_path:... | [
"def",
"write_neuropod_config",
"(",
"neuropod_path",
",",
"model_name",
",",
"platform",
",",
"input_spec",
",",
"output_spec",
",",
"platform_version_semver",
"=",
"\"*\"",
",",
"custom_ops",
"=",
"None",
",",
"input_tensor_device",
"=",
"None",
",",
"default_inpu... | [
169,
0
] | [
257,
48
] | python | en | ['en', 'error', 'th'] | False |
read_neuropod_config | (neuropod_path) |
Reads a neuropod config
:param neuropod_path: The path to a neuropod package
|
Reads a neuropod config | def read_neuropod_config(neuropod_path):
"""
Reads a neuropod config
:param neuropod_path: The path to a neuropod package
"""
with open(os.path.join(neuropod_path, "config.json"), "r") as config_file:
config = json.load(config_file)
# For backwards compatibility
# TODO(vi... | [
"def",
"read_neuropod_config",
"(",
"neuropod_path",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"neuropod_path",
",",
"\"config.json\"",
")",
",",
"\"r\"",
")",
"as",
"config_file",
":",
"config",
"=",
"json",
".",
"load",
"(",
"... | [
260,
0
] | [
281,
21
] | python | en | ['en', 'error', 'th'] | False |
method_decorator | (decorator) |
Converts a function decorator into a method decorator
|
Converts a function decorator into a method decorator
| def method_decorator(decorator):
"""
Converts a function decorator into a method decorator
"""
# 'func' is a function at the time it is passed to _dec, but will eventually
# be a method of the class it is defined it.
def _dec(func):
def _wrapper(self, *args, **kwargs):
@decor... | [
"def",
"method_decorator",
"(",
"decorator",
")",
":",
"# 'func' is a function at the time it is passed to _dec, but will eventually",
"# be a method of the class it is defined it.",
"def",
"_dec",
"(",
"func",
")",
":",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
","... | [
19,
0
] | [
53,
15
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware_with_args | (middleware_class) |
Like decorator_from_middleware, but returns a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_page(3600)
def my_view(request):
# ...
|
Like decorator_from_middleware, but returns a function
that accepts the arguments to be passed to the middleware_class.
Use like:: | def decorator_from_middleware_with_args(middleware_class):
"""
Like decorator_from_middleware, but returns a function
that accepts the arguments to be passed to the middleware_class.
Use like::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
# ...
@cache_pa... | [
"def",
"decorator_from_middleware_with_args",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")"
] | [
56,
0
] | [
69,
54
] | python | en | ['en', 'error', 'th'] | False |
decorator_from_middleware | (middleware_class) |
Given a middleware class (not an instance), returns a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
|
Given a middleware class (not an instance), returns a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
| def decorator_from_middleware(middleware_class):
"""
Given a middleware class (not an instance), returns a view decorator. This
lets you use middleware functionality on a per-view basis. The middleware
is created with no params passed.
"""
return make_middleware_decorator(middleware_class)() | [
"def",
"decorator_from_middleware",
"(",
"middleware_class",
")",
":",
"return",
"make_middleware_decorator",
"(",
"middleware_class",
")",
"(",
")"
] | [
72,
0
] | [
78,
56
] | python | en | ['en', 'error', 'th'] | False |
available_attrs | (fn) |
Return the list of functools-wrappable attributes on a callable.
This is required as a workaround for http://bugs.python.org/issue3445
under Python 2.
|
Return the list of functools-wrappable attributes on a callable.
This is required as a workaround for http://bugs.python.org/issue3445
under Python 2.
| def available_attrs(fn):
"""
Return the list of functools-wrappable attributes on a callable.
This is required as a workaround for http://bugs.python.org/issue3445
under Python 2.
"""
if six.PY3:
return WRAPPER_ASSIGNMENTS
else:
return tuple(a for a in WRAPPER_ASSIGNMENTS if ... | [
"def",
"available_attrs",
"(",
"fn",
")",
":",
"if",
"six",
".",
"PY3",
":",
"return",
"WRAPPER_ASSIGNMENTS",
"else",
":",
"return",
"tuple",
"(",
"a",
"for",
"a",
"in",
"WRAPPER_ASSIGNMENTS",
"if",
"hasattr",
"(",
"fn",
",",
"a",
")",
")"
] | [
81,
0
] | [
90,
70
] | python | en | ['en', 'error', 'th'] | False |
LazySettings._setup | (self, name=None) |
Load the settings module pointed to by the environment variable. This
is used the first time settings are needed, if the user hasn't
configured settings manually.
|
Load the settings module pointed to by the environment variable. This
is used the first time settings are needed, if the user hasn't
configured settings manually.
| def _setup(self, name=None):
"""
Load the settings module pointed to by the environment variable. This
is used the first time settings are needed, if the user hasn't
configured settings manually.
"""
settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
if not se... | [
"def",
"_setup",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"settings_module",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"ENVIRONMENT_VARIABLE",
")",
"if",
"not",
"settings_module",
":",
"desc",
"=",
"(",
"\"setting %s\"",
"%",
"name",
")",
"if",... | [
47,
4
] | [
62,
49
] | python | en | ['en', 'error', 'th'] | False |
LazySettings.__getattr__ | (self, name) | Return the value of a setting and cache it in self.__dict__. | Return the value of a setting and cache it in self.__dict__. | def __getattr__(self, name):
"""Return the value of a setting and cache it in self.__dict__."""
if self._wrapped is empty:
self._setup(name)
val = getattr(self._wrapped, name)
self.__dict__[name] = val
return val | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"_wrapped",
"is",
"empty",
":",
"self",
".",
"_setup",
"(",
"name",
")",
"val",
"=",
"getattr",
"(",
"self",
".",
"_wrapped",
",",
"name",
")",
"self",
".",
"__dict__",
"[... | [
72,
4
] | [
78,
18
] | python | en | ['en', 'en', 'en'] | True |
LazySettings.__setattr__ | (self, name, value) |
Set the value of setting. Clear all cached values if _wrapped changes
(@override_settings does this) or clear single values when set.
|
Set the value of setting. Clear all cached values if _wrapped changes
( | def __setattr__(self, name, value):
"""
Set the value of setting. Clear all cached values if _wrapped changes
(@override_settings does this) or clear single values when set.
"""
if name == '_wrapped':
self.__dict__.clear()
else:
self.__dict__.pop(n... | [
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"name",
"==",
"'_wrapped'",
":",
"self",
".",
"__dict__",
".",
"clear",
"(",
")",
"else",
":",
"self",
".",
"__dict__",
".",
"pop",
"(",
"name",
",",
"None",
")",
"super"... | [
80,
4
] | [
89,
40
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.