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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test_bad_stub | (tmp_path) | should raise exception on invalid stub | should raise exception on invalid stub | def test_bad_stub(tmp_path):
"""should raise exception on invalid stub"""
with pytest.raises(FileNotFoundError):
stubs.stubs.DeviceStub(tmp_path) | [
"def",
"test_bad_stub",
"(",
"tmp_path",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"FileNotFoundError",
")",
":",
"stubs",
".",
"stubs",
".",
"DeviceStub",
"(",
"tmp_path",
")"
] | [
41,
0
] | [
44,
40
] | python | en | ['en', 'en', 'en'] | True |
test_valid_stub | (shared_datadir) | should have all attributes | should have all attributes | def test_valid_stub(shared_datadir):
"""should have all attributes"""
stub_path = shared_datadir / "esp8266_test_stub"
stub = stubs.stubs.DeviceStub(stub_path)
stub_2 = stubs.stubs.DeviceStub(stub_path)
fware = stubs.stubs.FirmwareStub((shared_datadir / "fware_test_stub"))
assert stub == stub_2
... | [
"def",
"test_valid_stub",
"(",
"shared_datadir",
")",
":",
"stub_path",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"stub",
"=",
"stubs",
".",
"stubs",
".",
"DeviceStub",
"(",
"stub_path",
")",
"stub_2",
"=",
"stubs",
".",
"stubs",
".",
"DeviceStub",
... | [
47,
0
] | [
78,
51
] | python | en | ['en', 'en', 'en'] | True |
test_resolve_stub | (shared_datadir) | should resolve correct stub type | should resolve correct stub type | def test_resolve_stub(shared_datadir):
"""should resolve correct stub type"""
device_stub = shared_datadir / "esp8266_test_stub"
fware_stub = shared_datadir / "fware_test_stub"
invalid_stub = shared_datadir / "esp8266_invalid_stub"
manager = stubs.StubManager()
stub_type = manager._get_stubtype(... | [
"def",
"test_resolve_stub",
"(",
"shared_datadir",
")",
":",
"device_stub",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"fware_stub",
"=",
"shared_datadir",
"/",
"\"fware_test_stub\"",
"invalid_stub",
"=",
"shared_datadir",
"/",
"\"esp8266_invalid_stub\"",
"manager... | [
89,
0
] | [
102,
43
] | python | en | ['en', 'zu', 'en'] | True |
test_resolve_firmware | (tmp_path, shared_datadir) | should resolve firmware | should resolve firmware | def test_resolve_firmware(tmp_path, shared_datadir):
"""should resolve firmware"""
device_stub = shared_datadir / "esp8266_test_stub"
fware_stub_path = shared_datadir / "fware_test_stub"
manager = stubs.StubManager(resource=tmp_path)
fware_stub = manager.add(fware_stub_path)
dev_stub = stubs.stu... | [
"def",
"test_resolve_firmware",
"(",
"tmp_path",
",",
"shared_datadir",
")",
":",
"device_stub",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"fware_stub_path",
"=",
"shared_datadir",
"/",
"\"fware_test_stub\"",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
... | [
105,
0
] | [
113,
33
] | python | en | ['en', 'en', 'en'] | True |
test_add_single_stub | (shared_datadir, tmp_path) | should add a single stub | should add a single stub | def test_add_single_stub(shared_datadir, tmp_path):
"""should add a single stub"""
stub_path = shared_datadir / "esp8266_test_stub"
manager = stubs.StubManager()
manager.add(stub_path, dest=tmp_path)
assert len(manager) == 1
assert stub_path.name in [d.name for d in tmp_path.iterdir()] | [
"def",
"test_add_single_stub",
"(",
"shared_datadir",
",",
"tmp_path",
")",
":",
"stub_path",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
")",
"manager",
".",
"add",
"(",
"stub_path",
",",
"dest",
"=",
... | [
116,
0
] | [
122,
65
] | python | en | ['en', 'cy', 'en'] | True |
test_add_stubs_from_dir | (datadir, tmp_path) | should add all valid stubs in directory | should add all valid stubs in directory | def test_add_stubs_from_dir(datadir, tmp_path):
"""should add all valid stubs in directory"""
manager = stubs.StubManager()
manager.add(datadir, dest=tmp_path)
assert len(manager) == 2
assert len(list(tmp_path.iterdir())) - 1 == len(manager)
assert manager._should_recurse(datadir)
with pytes... | [
"def",
"test_add_stubs_from_dir",
"(",
"datadir",
",",
"tmp_path",
")",
":",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
")",
"manager",
".",
"add",
"(",
"datadir",
",",
"dest",
"=",
"tmp_path",
")",
"assert",
"len",
"(",
"manager",
")",
"==",
"2",... | [
125,
0
] | [
135,
43
] | python | en | ['en', 'en', 'en'] | True |
test_add_with_resource | (datadir, mock_fware, tmp_path, mocker) | should not require dest kwarg | should not require dest kwarg | def test_add_with_resource(datadir, mock_fware, tmp_path, mocker):
"""should not require dest kwarg"""
resource = tmp_path / "tmp_resource"
resource.mkdir()
load_spy = mocker.spy(stubs.StubManager, "_load")
manager = stubs.StubManager(resource=resource)
manager.add(datadir)
assert len(manage... | [
"def",
"test_add_with_resource",
"(",
"datadir",
",",
"mock_fware",
",",
"tmp_path",
",",
"mocker",
")",
":",
"resource",
"=",
"tmp_path",
"/",
"\"tmp_resource\"",
"resource",
".",
"mkdir",
"(",
")",
"load_spy",
"=",
"mocker",
".",
"spy",
"(",
"stubs",
".",
... | [
138,
0
] | [
153,
35
] | python | en | ['en', 'fr', 'sw'] | False |
test_add_no_resource_no_dest | (datadir, mock_fware) | should fail with typeerror | should fail with typeerror | def test_add_no_resource_no_dest(datadir, mock_fware):
"""should fail with typeerror"""
manager = stubs.StubManager()
with pytest.raises(TypeError):
manager.add(datadir) | [
"def",
"test_add_no_resource_no_dest",
"(",
"datadir",
",",
"mock_fware",
")",
":",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
")",
"with",
"pytest",
".",
"raises",
"(",
"TypeError",
")",
":",
"manager",
".",
"add",
"(",
"datadir",
")"
] | [
156,
0
] | [
160,
28
] | python | en | ['en', 'en', 'en'] | True |
test_loads_from_resource | (datadir, mock_fware) | should load from resource if provided | should load from resource if provided | def test_loads_from_resource(datadir, mock_fware):
"""should load from resource if provided"""
manager = stubs.StubManager(resource=datadir)
assert len(manager) == 2 | [
"def",
"test_loads_from_resource",
"(",
"datadir",
",",
"mock_fware",
")",
":",
"manager",
"=",
"stubs",
".",
"StubManager",
"(",
"resource",
"=",
"datadir",
")",
"assert",
"len",
"(",
"manager",
")",
"==",
"2"
] | [
163,
0
] | [
166,
28
] | python | en | ['en', 'en', 'en'] | True |
test_name_property | (shared_datadir) | should raise error if name is not overriden | should raise error if name is not overriden | def test_name_property(shared_datadir):
"""should raise error if name is not overriden"""
test_stub = shared_datadir / "esp8266_test_stub"
class ErrorStub(stubs.stubs.Stub):
def __init__(self, path, copy_to=None, **kwargs):
return super().__init__(path, copy_to=copy_to, **kwargs)
w... | [
"def",
"test_name_property",
"(",
"shared_datadir",
")",
":",
"test_stub",
"=",
"shared_datadir",
"/",
"\"esp8266_test_stub\"",
"class",
"ErrorStub",
"(",
"stubs",
".",
"stubs",
".",
"Stub",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"copy_to"... | [
169,
0
] | [
179,
14
] | python | en | ['en', 'nl', 'en'] | True |
test_stub_resolve_link | (mock_mp_stubs, tmp_path) | should create DeviceStub from symlink | should create DeviceStub from symlink | def test_stub_resolve_link(mock_mp_stubs, tmp_path):
"""should create DeviceStub from symlink"""
stub = list(mock_mp_stubs.stubs)[0]
link_path = tmp_path / "stub_symlink"
linked_stub = stubs.stubs.DeviceStub.resolve_link(stub, link_path)
assert stub == linked_stub
assert stub.path != linked_stub... | [
"def",
"test_stub_resolve_link",
"(",
"mock_mp_stubs",
",",
"tmp_path",
")",
":",
"stub",
"=",
"list",
"(",
"mock_mp_stubs",
".",
"stubs",
")",
"[",
"0",
"]",
"link_path",
"=",
"tmp_path",
"/",
"\"stub_symlink\"",
"linked_stub",
"=",
"stubs",
".",
"stubs",
"... | [
203,
0
] | [
211,
50
] | python | en | ['en', 'da', 'en'] | True |
test_manager_resolve_subresource | (mock_mp_stubs, tmp_path) | should create StubManager from subresource symlinks | should create StubManager from subresource symlinks | def test_manager_resolve_subresource(mock_mp_stubs, tmp_path):
"""should create StubManager from subresource symlinks"""
test_stubs = list(mock_mp_stubs.stubs)[:2]
subresource = tmp_path / "stub_subresource"
subresource.mkdir()
manager = mock_mp_stubs.stubs.resolve_subresource(test_stubs, subresourc... | [
"def",
"test_manager_resolve_subresource",
"(",
"mock_mp_stubs",
",",
"tmp_path",
")",
":",
"test_stubs",
"=",
"list",
"(",
"mock_mp_stubs",
".",
"stubs",
")",
"[",
":",
"2",
"]",
"subresource",
"=",
"tmp_path",
"/",
"\"stub_subresource\"",
"subresource",
".",
"... | [
214,
0
] | [
222,
51
] | python | en | ['en', 'en', 'en'] | True |
test_load_firmware_first | (mocker, tmp_path, shared_datadir) | should always load firmware first | should always load firmware first | def test_load_firmware_first(mocker, tmp_path, shared_datadir):
"""should always load firmware first"""
mock_manager = mocker.patch.object(stubs.StubManager, "_load")
mock_iterdir = mocker.patch.object(stubs.stubs.Path, "iterdir")
# mock_mgr = mock_manager.return_value
tmp_path = tmp_path / "fware_f... | [
"def",
"test_load_firmware_first",
"(",
"mocker",
",",
"tmp_path",
",",
"shared_datadir",
")",
":",
"mock_manager",
"=",
"mocker",
".",
"patch",
".",
"object",
"(",
"stubs",
".",
"StubManager",
",",
"\"_load\"",
")",
"mock_iterdir",
"=",
"mocker",
".",
"patch"... | [
225,
0
] | [
243,
42
] | python | en | ['en', 'en', 'en'] | True |
test_iter_by_firm_stubs | (mocker) | should iter stubs by firmware | should iter stubs by firmware | def test_iter_by_firm_stubs(mocker):
"""should iter stubs by firmware"""
firm_stub = mocker.MagicMock()
dev_stub = mocker.MagicMock()
dev_stub.firmware = firm_stub
unk_stub = mocker.MagicMock()
unk_stub.firmware = None
manager = stubs.StubManager()
manager._loaded = set([firm_stub, dev_s... | [
"def",
"test_iter_by_firm_stubs",
"(",
"mocker",
")",
":",
"firm_stub",
"=",
"mocker",
".",
"MagicMock",
"(",
")",
"dev_stub",
"=",
"mocker",
".",
"MagicMock",
"(",
")",
"dev_stub",
".",
"firmware",
"=",
"firm_stub",
"unk_stub",
"=",
"mocker",
".",
"MagicMoc... | [
246,
0
] | [
257,
74
] | python | en | ['en', 'en', 'en'] | True |
do_block | (parser, token) |
Define a block that can be overridden by child templates.
|
Define a block that can be overridden by child templates.
| def do_block(parser, token):
"""
Define a block that can be overridden by child templates.
"""
# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError("'%s' tag takes only ... | [
"def",
"do_block",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"bits",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":"... | [
191,
0
] | [
216,
42
] | python | en | ['en', 'error', 'th'] | False |
construct_relative_path | (current_template_name, relative_name) |
Convert a relative path (starting with './' or '../') to the full template
name based on the current_template_name.
|
Convert a relative path (starting with './' or '../') to the full template
name based on the current_template_name.
| def construct_relative_path(current_template_name, relative_name):
"""
Convert a relative path (starting with './' or '../') to the full template
name based on the current_template_name.
"""
if not relative_name.startswith(("'./", "'../", '"./', '"../')):
# relative_name is a variable or a l... | [
"def",
"construct_relative_path",
"(",
"current_template_name",
",",
"relative_name",
")",
":",
"if",
"not",
"relative_name",
".",
"startswith",
"(",
"(",
"\"'./\"",
",",
"\"'../\"",
",",
"'\"./'",
",",
"'\"../'",
")",
")",
":",
"# relative_name is a variable or a l... | [
219,
0
] | [
246,
28
] | python | en | ['en', 'error', 'th'] | False |
do_extends | (parser, token) |
Signal that this template extends a parent template.
This tag may be used in two ways: ``{% extends "base" %}`` (with quotes)
uses the literal value "base" as the name of the parent template to extend,
or ``{% extends variable %}`` uses the value of ``variable`` as either the
name of the parent te... |
Signal that this template extends a parent template. | def do_extends(parser, token):
"""
Signal that this template extends a parent template.
This tag may be used in two ways: ``{% extends "base" %}`` (with quotes)
uses the literal value "base" as the name of the parent template to extend,
or ``{% extends variable %}`` uses the value of ``variable`` a... | [
"def",
"do_extends",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes one argument\"",
"%",
"bits",
"[",
"0",
"... | [
250,
0
] | [
268,
45
] | python | en | ['en', 'error', 'th'] | False |
do_include | (parser, token) |
Load a template and render it with the current context. You can pass
additional context using keyword arguments.
Example::
{% include "foo/some_include" %}
{% include "foo/some_include" with bar="BAZZ!" baz="BING!" %}
Use the ``only`` argument to exclude the current context when rend... |
Load a template and render it with the current context. You can pass
additional context using keyword arguments. | def do_include(parser, token):
"""
Load a template and render it with the current context. You can pass
additional context using keyword arguments.
Example::
{% include "foo/some_include" %}
{% include "foo/some_include" with bar="BAZZ!" baz="BING!" %}
Use the ``only`` argument to... | [
"def",
"do_include",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"%r tag takes at least one argument: the name of the template to... | [
272,
0
] | [
316,
57
] | python | en | ['en', 'error', 'th'] | False |
ExtendsNode.find_template | (self, template_name, context) |
This is a wrapper around engine.find_template(). A history is kept in
the render_context attribute between successive extends calls and
passed as the skip argument. This enables extends to work recursively
without extending the same template twice.
|
This is a wrapper around engine.find_template(). A history is kept in
the render_context attribute between successive extends calls and
passed as the skip argument. This enables extends to work recursively
without extending the same template twice.
| def find_template(self, template_name, context):
"""
This is a wrapper around engine.find_template(). A history is kept in
the render_context attribute between successive extends calls and
passed as the skip argument. This enables extends to work recursively
without extending the... | [
"def",
"find_template",
"(",
"self",
",",
"template_name",
",",
"context",
")",
":",
"history",
"=",
"context",
".",
"render_context",
".",
"setdefault",
"(",
"self",
".",
"context_key",
",",
"[",
"self",
".",
"origin",
"]",
",",
")",
"template",
",",
"o... | [
92,
4
] | [
106,
23
] | python | en | ['en', 'error', 'th'] | False |
IncludeNode.render | (self, context) |
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
|
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
| def render(self, context):
"""
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
"""
template = self.template.resolve(context)
# Does this quack like a Template?
i... | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"template",
"=",
"self",
".",
"template",
".",
"resolve",
"(",
"context",
")",
"# Does this quack like a Template?",
"if",
"not",
"callable",
"(",
"getattr",
"(",
"template",
",",
"'render'",
",",
"None... | [
161,
4
] | [
187,
43
] | python | en | ['en', 'error', 'th'] | False |
make_link_collector | (
session, # type: PipSession
options, # type: Values
suppress_no_index=False, # type: bool
) |
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
|
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
| def make_link_collector(
session, # type: PipSession
options, # type: Values
suppress_no_index=False, # type: bool
):
# type: (...) -> LinkCollector
"""
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when cons... | [
"def",
"make_link_collector",
"(",
"session",
",",
"# type: PipSession",
"options",
",",
"# type: Values",
"suppress_no_index",
"=",
"False",
",",
"# type: bool",
")",
":",
"# type: (...) -> LinkCollector",
"index_urls",
"=",
"[",
"options",
".",
"index_url",
"]",
"+"... | [
47,
0
] | [
75,
25
] | python | en | ['en', 'error', 'th'] | False |
was_installed_by_pip | (pkg) | Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora.
| Checks whether pkg was installed by pip | def was_installed_by_pip(pkg):
# type: (str) -> bool
"""Checks whether pkg was installed by pip
This is used not to display the upgrade message when pip is in fact
installed by system package manager, such as dnf on Fedora.
"""
try:
dist = pkg_resources.get_distribution(pkg)
ret... | [
"def",
"was_installed_by_pip",
"(",
"pkg",
")",
":",
"# type: (str) -> bool",
"try",
":",
"dist",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"pkg",
")",
"return",
"\"pip\"",
"==",
"get_installer",
"(",
"dist",
")",
"except",
"pkg_resources",
".",
"Distr... | [
144,
0
] | [
155,
20
] | python | en | ['en', 'en', 'en'] | True |
pip_self_version_check | (session, options) | Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
| Check for an update for pip. | def pip_self_version_check(session, options):
# type: (PipSession, optparse.Values) -> None
"""Check for an update for pip.
Limit the frequency of checks to once per week. State is stored either in
the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix
of the pip script path.
... | [
"def",
"pip_self_version_check",
"(",
"session",
",",
"options",
")",
":",
"# type: (PipSession, optparse.Values) -> None",
"installed_version",
"=",
"get_installed_version",
"(",
"\"pip\"",
")",
"if",
"not",
"installed_version",
":",
"return",
"pip_version",
"=",
"packag... | [
158,
0
] | [
241,
9
] | python | en | ['en', 'en', 'en'] | True |
print_accuracies | (
filepath,
train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START,
test_end=TEST_END,
batch_size=BATCH_SIZE,
which_set=WHICH_SET,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER,
) |
Load a saved model and print out its accuracy on different data distributions
This function works by running a single attack on each example.
This provides a reasonable estimate of the true failure rate quickly, so
long as the model does not suffer from gradient masking.
However, this estimate is ... |
Load a saved model and print out its accuracy on different data distributions | def print_accuracies(
filepath,
train_start=TRAIN_START,
train_end=TRAIN_END,
test_start=TEST_START,
test_end=TEST_END,
batch_size=BATCH_SIZE,
which_set=WHICH_SET,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER,
):
"""
Load a saved model and print out its accuracy on different ... | [
"def",
"print_accuracies",
"(",
"filepath",
",",
"train_start",
"=",
"TRAIN_START",
",",
"train_end",
"=",
"TRAIN_END",
",",
"test_start",
"=",
"TEST_START",
",",
"test_end",
"=",
"TEST_END",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"which_set",
"=",
"WHICH_SE... | [
53,
0
] | [
103,
79
] | python | en | ['en', 'error', 'th'] | False |
impl | (
sess,
model,
dataset,
factory,
x_data,
y_data,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER,
batch_size=BATCH_SIZE,
) |
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param factory: the dataset factory corresponding to `dataset`
:param x_data: numpy array of input examples
:param y_data: numpy array of clas... |
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhans.dataset.Dataset
:param factory: the dataset factory corresponding to `dataset`
:param x_data: numpy array of input examples
:param y_data: numpy array of clas... | def impl(
sess,
model,
dataset,
factory,
x_data,
y_data,
base_eps_iter=BASE_EPS_ITER,
nb_iter=NB_ITER,
batch_size=BATCH_SIZE,
):
"""
The actual implementation of the evaluation.
:param sess: tf.Session
:param model: cleverhans.model.Model
:param dataset: cleverhan... | [
"def",
"impl",
"(",
"sess",
",",
"model",
",",
"dataset",
",",
"factory",
",",
"x_data",
",",
"y_data",
",",
"base_eps_iter",
"=",
"BASE_EPS_ITER",
",",
"nb_iter",
"=",
"NB_ITER",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
")",
":",
"center",
"=",
"datas... | [
106,
0
] | [
185,
14
] | python | en | ['en', 'error', 'th'] | False |
main | (argv=None) |
Print accuracies
|
Print accuracies
| def main(argv=None):
"""
Print accuracies
"""
try:
_name_of_script, filepath = argv
except ValueError:
raise ValueError(argv)
print_accuracies(
filepath=filepath,
test_start=FLAGS.test_start,
test_end=FLAGS.test_end,
which_set=FLAGS.which_set,
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"try",
":",
"_name_of_script",
",",
"filepath",
"=",
"argv",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"argv",
")",
"print_accuracies",
"(",
"filepath",
"=",
"filepath",
",",
"test_start",
"... | [
188,
0
] | [
204,
5
] | python | en | ['en', 'error', 'th'] | False |
get_level_tags | () |
Return the message level tags.
|
Return the message level tags.
| def get_level_tags():
"""
Return the message level tags.
"""
return {
**constants.DEFAULT_TAGS,
**getattr(settings, 'MESSAGE_TAGS', {}),
} | [
"def",
"get_level_tags",
"(",
")",
":",
"return",
"{",
"*",
"*",
"constants",
".",
"DEFAULT_TAGS",
",",
"*",
"*",
"getattr",
"(",
"settings",
",",
"'MESSAGE_TAGS'",
",",
"{",
"}",
")",
",",
"}"
] | [
4,
0
] | [
11,
5
] | python | en | ['en', 'error', 'th'] | False |
file_move_safe | (old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False) |
Moves a file from one location to another in the safest way possible.
First, tries ``os.rename``, which is simple but will break across filesystems.
If that fails, streams manually from one file to another in pure Python.
If the destination file exists and ``allow_overwrite`` is ``False``, this
f... |
Moves a file from one location to another in the safest way possible. | def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False):
"""
Moves a file from one location to another in the safest way possible.
First, tries ``os.rename``, which is simple but will break across filesystems.
If that fails, streams manually from one file to anothe... | [
"def",
"file_move_safe",
"(",
"old_file_name",
",",
"new_file_name",
",",
"chunk_size",
"=",
"1024",
"*",
"64",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"# There's no reason to move if we don't have to.",
"if",
"_samefile",
"(",
"old_file_name",
",",
"new_file_... | [
40,
0
] | [
91,
17
] | python | en | ['en', 'error', 'th'] | False |
HashedFilesMixin.file_hash | (self, name, content=None) |
Returns a hash of the file with the given name and optional content.
|
Returns a hash of the file with the given name and optional content.
| def file_hash(self, name, content=None):
"""
Returns a hash of the file with the given name and optional content.
"""
if content is None:
return None
md5 = hashlib.md5()
for chunk in content.chunks():
md5.update(chunk)
return md5.hexdigest(... | [
"def",
"file_hash",
"(",
"self",
",",
"name",
",",
"content",
"=",
"None",
")",
":",
"if",
"content",
"is",
"None",
":",
"return",
"None",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"chunk",
"in",
"content",
".",
"chunks",
"(",
")",
":",
... | [
72,
4
] | [
81,
35
] | python | en | ['en', 'error', 'th'] | False |
HashedFilesMixin.url | (self, name, force=False) |
Returns the real URL in DEBUG mode.
|
Returns the real URL in DEBUG mode.
| def url(self, name, force=False):
"""
Returns the real URL in DEBUG mode.
"""
if settings.DEBUG and not force:
hashed_name, fragment = name, ''
else:
clean_name, fragment = urldefrag(name)
if urlsplit(clean_name).path.endswith('/'): # don't ha... | [
"def",
"url",
"(",
"self",
",",
"name",
",",
"force",
"=",
"False",
")",
":",
"if",
"settings",
".",
"DEBUG",
"and",
"not",
"force",
":",
"hashed_name",
",",
"fragment",
"=",
"name",
",",
"''",
"else",
":",
"clean_name",
",",
"fragment",
"=",
"urldef... | [
116,
4
] | [
142,
33
] | python | en | ['en', 'error', 'th'] | False |
HashedFilesMixin.url_converter | (self, name, template=None) |
Returns the custom URL converter for the given file name.
|
Returns the custom URL converter for the given file name.
| def url_converter(self, name, template=None):
"""
Returns the custom URL converter for the given file name.
"""
if template is None:
template = self.default_template
def converter(matchobj):
"""
Converts the matched URL depending on the parent... | [
"def",
"url_converter",
"(",
"self",
",",
"name",
",",
"template",
"=",
"None",
")",
":",
"if",
"template",
"is",
"None",
":",
"template",
"=",
"self",
".",
"default_template",
"def",
"converter",
"(",
"matchobj",
")",
":",
"\"\"\"\n Converts the ma... | [
144,
4
] | [
187,
24
] | python | en | ['en', 'error', 'th'] | False |
HashedFilesMixin.post_process | (self, paths, dry_run=False, **options) |
Post process the given OrderedDict of files (called from collectstatic).
Processing is actually two separate operations:
1. renaming files to include a hash of their content for cache-busting,
and copying those files to the target storage.
2. adjusting files which contain r... |
Post process the given OrderedDict of files (called from collectstatic). | def post_process(self, paths, dry_run=False, **options):
"""
Post process the given OrderedDict of files (called from collectstatic).
Processing is actually two separate operations:
1. renaming files to include a hash of their content for cache-busting,
and copying those fil... | [
"def",
"post_process",
"(",
"self",
",",
"paths",
",",
"dry_run",
"=",
"False",
",",
"*",
"*",
"options",
")",
":",
"# don't even dare to process the files if we're in dry run mode",
"if",
"dry_run",
":",
"return",
"# where to store the new paths",
"hashed_files",
"=",
... | [
189,
4
] | [
264,
46
] | python | en | ['en', 'error', 'th'] | False |
detect_narrowed_window | (
request: HttpRequest, user_profile: Optional[UserProfile]
) | This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow | This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow | def detect_narrowed_window(
request: HttpRequest, user_profile: Optional[UserProfile]
) -> Tuple[List[List[str]], Optional[Stream], Optional[str]]:
"""This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow"""
if user_profile is None:
retu... | [
"def",
"detect_narrowed_window",
"(",
"request",
":",
"HttpRequest",
",",
"user_profile",
":",
"Optional",
"[",
"UserProfile",
"]",
")",
"->",
"Tuple",
"[",
"List",
"[",
"List",
"[",
"str",
"]",
"]",
",",
"Optional",
"[",
"Stream",
"]",
",",
"Optional",
... | [
67,
0
] | [
89,
46
] | python | en | ['en', 'en', 'en'] | True |
update_last_reminder | (user_profile: Optional[UserProfile]) | Reset our don't-spam-users-with-email counter since the
user has since logged in
| Reset our don't-spam-users-with-email counter since the
user has since logged in
| def update_last_reminder(user_profile: Optional[UserProfile]) -> None:
"""Reset our don't-spam-users-with-email counter since the
user has since logged in
"""
if user_profile is None:
return
if user_profile.last_reminder is not None: # nocoverage
# TODO: Look into the history of la... | [
"def",
"update_last_reminder",
"(",
"user_profile",
":",
"Optional",
"[",
"UserProfile",
"]",
")",
"->",
"None",
":",
"if",
"user_profile",
"is",
"None",
":",
"return",
"if",
"user_profile",
".",
"last_reminder",
"is",
"not",
"None",
":",
"# nocoverage",
"# TO... | [
92,
0
] | [
103,
58
] | python | en | ['en', 'en', 'en'] | True |
BaseDatabaseCreation._nodb_connection | (self) |
Alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test database is destroyed.
Refs #10868,... |
Alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test database is destroyed.
Refs #10868,... | def _nodb_connection(self):
"""
Alternative connection to be used when there is no need to access
the main database, specifically for test db creation/deletion.
This also prevents the production database from being exposed to
potential child threads while (or after) the test data... | [
"def",
"_nodb_connection",
"(",
"self",
")",
":",
"settings_dict",
"=",
"self",
".",
"connection",
".",
"settings_dict",
".",
"copy",
"(",
")",
"settings_dict",
"[",
"'NAME'",
"]",
"=",
"None",
"backend",
"=",
"load_backend",
"(",
"settings_dict",
"[",
"'ENG... | [
38,
4
] | [
53,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation._digest | (cls, *args) |
Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.
|
Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.
| def _digest(cls, *args):
"""
Generates a 32-bit digest of a set of arguments that can be used to
shorten identifying names.
"""
h = hashlib.md5()
for arg in args:
h.update(force_bytes(arg))
return h.hexdigest()[:8] | [
"def",
"_digest",
"(",
"cls",
",",
"*",
"args",
")",
":",
"h",
"=",
"hashlib",
".",
"md5",
"(",
")",
"for",
"arg",
"in",
"args",
":",
"h",
".",
"update",
"(",
"force_bytes",
"(",
"arg",
")",
")",
"return",
"h",
".",
"hexdigest",
"(",
")",
"[",
... | [
56,
4
] | [
64,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_create_model | (self, model, style, known_models=set()) |
Returns the SQL required to create a single model, as a tuple of:
(list_of_sql, pending_references_dict)
|
Returns the SQL required to create a single model, as a tuple of:
(list_of_sql, pending_references_dict)
| def sql_create_model(self, model, style, known_models=set()):
"""
Returns the SQL required to create a single model, as a tuple of:
(list_of_sql, pending_references_dict)
"""
opts = model._meta
if not opts.managed or opts.proxy or opts.swapped:
return [], ... | [
"def",
"sql_create_model",
"(",
"self",
",",
"model",
",",
"style",
",",
"known_models",
"=",
"set",
"(",
")",
")",
":",
"opts",
"=",
"model",
".",
"_meta",
"if",
"not",
"opts",
".",
"managed",
"or",
"opts",
".",
"proxy",
"or",
"opts",
".",
"swapped"... | [
66,
4
] | [
152,
47
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_for_inline_foreign_key_references | (self, model, field, known_models, style) |
Return the SQL snippet defining the foreign key reference for a field.
|
Return the SQL snippet defining the foreign key reference for a field.
| def sql_for_inline_foreign_key_references(self, model, field, known_models, style):
"""
Return the SQL snippet defining the foreign key reference for a field.
"""
qn = self.connection.ops.quote_name
rel_to = field.rel.to
if rel_to in known_models or rel_to == model:
... | [
"def",
"sql_for_inline_foreign_key_references",
"(",
"self",
",",
"model",
",",
"field",
",",
"known_models",
",",
"style",
")",
":",
"qn",
"=",
"self",
".",
"connection",
".",
"ops",
".",
"quote_name",
"rel_to",
"=",
"field",
".",
"rel",
".",
"to",
"if",
... | [
154,
4
] | [
174,
30
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_for_pending_references | (self, model, style, pending_references) |
Returns any ALTER TABLE statements to add constraints after the fact.
|
Returns any ALTER TABLE statements to add constraints after the fact.
| def sql_for_pending_references(self, model, style, pending_references):
"""
Returns any ALTER TABLE statements to add constraints after the fact.
"""
opts = model._meta
if not opts.managed or opts.swapped:
return []
qn = self.connection.ops.quote_name
... | [
"def",
"sql_for_pending_references",
"(",
"self",
",",
"model",
",",
"style",
",",
"pending_references",
")",
":",
"opts",
"=",
"model",
".",
"_meta",
"if",
"not",
"opts",
".",
"managed",
"or",
"opts",
".",
"swapped",
":",
"return",
"[",
"]",
"qn",
"=",
... | [
176,
4
] | [
203,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_indexes_for_model | (self, model, style) |
Returns the CREATE INDEX SQL statements for a single model.
|
Returns the CREATE INDEX SQL statements for a single model.
| def sql_indexes_for_model(self, model, style):
"""
Returns the CREATE INDEX SQL statements for a single model.
"""
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
return []
output = []
for f in model._meta.local_fields:
outp... | [
"def",
"sql_indexes_for_model",
"(",
"self",
",",
"model",
",",
"style",
")",
":",
"if",
"not",
"model",
".",
"_meta",
".",
"managed",
"or",
"model",
".",
"_meta",
".",
"proxy",
"or",
"model",
".",
"_meta",
".",
"swapped",
":",
"return",
"[",
"]",
"o... | [
205,
4
] | [
217,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_indexes_for_field | (self, model, f, style) |
Return the CREATE INDEX SQL statements for a single model field.
|
Return the CREATE INDEX SQL statements for a single model field.
| def sql_indexes_for_field(self, model, f, style):
"""
Return the CREATE INDEX SQL statements for a single model field.
"""
if f.db_index and not f.unique:
return self.sql_indexes_for_fields(model, [f], style)
else:
return [] | [
"def",
"sql_indexes_for_field",
"(",
"self",
",",
"model",
",",
"f",
",",
"style",
")",
":",
"if",
"f",
".",
"db_index",
"and",
"not",
"f",
".",
"unique",
":",
"return",
"self",
".",
"sql_indexes_for_fields",
"(",
"model",
",",
"[",
"f",
"]",
",",
"s... | [
219,
4
] | [
226,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_destroy_model | (self, model, references_to_delete, style) |
Return the DROP TABLE and restraint dropping statements for a single
model.
|
Return the DROP TABLE and restraint dropping statements for a single
model.
| def sql_destroy_model(self, model, references_to_delete, style):
"""
Return the DROP TABLE and restraint dropping statements for a single
model.
"""
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
return []
# Drop the table now
... | [
"def",
"sql_destroy_model",
"(",
"self",
",",
"model",
",",
"references_to_delete",
",",
"style",
")",
":",
"if",
"not",
"model",
".",
"_meta",
".",
"managed",
"or",
"model",
".",
"_meta",
".",
"proxy",
"or",
"model",
".",
"_meta",
".",
"swapped",
":",
... | [
254,
4
] | [
272,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_destroy_indexes_for_model | (self, model, style) |
Returns the DROP INDEX SQL statements for a single model.
|
Returns the DROP INDEX SQL statements for a single model.
| def sql_destroy_indexes_for_model(self, model, style):
"""
Returns the DROP INDEX SQL statements for a single model.
"""
if not model._meta.managed or model._meta.proxy or model._meta.swapped:
return []
output = []
for f in model._meta.local_fields:
... | [
"def",
"sql_destroy_indexes_for_model",
"(",
"self",
",",
"model",
",",
"style",
")",
":",
"if",
"not",
"model",
".",
"_meta",
".",
"managed",
"or",
"model",
".",
"_meta",
".",
"proxy",
"or",
"model",
".",
"_meta",
".",
"swapped",
":",
"return",
"[",
"... | [
296,
4
] | [
308,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_destroy_indexes_for_field | (self, model, f, style) |
Return the DROP INDEX SQL statements for a single model field.
|
Return the DROP INDEX SQL statements for a single model field.
| def sql_destroy_indexes_for_field(self, model, f, style):
"""
Return the DROP INDEX SQL statements for a single model field.
"""
if f.db_index and not f.unique:
return self.sql_destroy_indexes_for_fields(model, [f], style)
else:
return [] | [
"def",
"sql_destroy_indexes_for_field",
"(",
"self",
",",
"model",
",",
"f",
",",
"style",
")",
":",
"if",
"f",
".",
"db_index",
"and",
"not",
"f",
".",
"unique",
":",
"return",
"self",
".",
"sql_destroy_indexes_for_fields",
"(",
"model",
",",
"[",
"f",
... | [
310,
4
] | [
317,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.create_test_db | (self, verbosity=1, autoclobber=False, serialize=True, keepdb=False) |
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
|
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
| def create_test_db(self, verbosity=1, autoclobber=False, serialize=True, keepdb=False):
"""
Creates a test database, prompting the user for confirmation if the
database already exists. Returns the name of the test database created.
"""
# Don't import django.core.management if it ... | [
"def",
"create_test_db",
"(",
"self",
",",
"verbosity",
"=",
"1",
",",
"autoclobber",
"=",
"False",
",",
"serialize",
"=",
"True",
",",
"keepdb",
"=",
"False",
")",
":",
"# Don't import django.core.management if it isn't needed.",
"from",
"django",
".",
"core",
... | [
342,
4
] | [
399,
33
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation._create_test_db_pre_migrate_sql | (self) |
Hook for databases to load SQL before creating the test DB.
|
Hook for databases to load SQL before creating the test DB.
| def _create_test_db_pre_migrate_sql(self):
"""
Hook for databases to load SQL before creating the test DB.
"""
pass | [
"def",
"_create_test_db_pre_migrate_sql",
"(",
"self",
")",
":",
"pass"
] | [
401,
4
] | [
405,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.serialize_db_to_string | (self) |
Serializes all data in the database into a JSON string.
Designed only for test runner usage; will not handle large
amounts of data.
|
Serializes all data in the database into a JSON string.
Designed only for test runner usage; will not handle large
amounts of data.
| def serialize_db_to_string(self):
"""
Serializes all data in the database into a JSON string.
Designed only for test runner usage; will not handle large
amounts of data.
"""
# Build list of all apps to serialize
from django.db.migrations.loader import MigrationLoa... | [
"def",
"serialize_db_to_string",
"(",
"self",
")",
":",
"# Build list of all apps to serialize",
"from",
"django",
".",
"db",
".",
"migrations",
".",
"loader",
"import",
"MigrationLoader",
"loader",
"=",
"MigrationLoader",
"(",
"self",
".",
"connection",
")",
"app_l... | [
407,
4
] | [
436,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.deserialize_db_from_string | (self, data) |
Reloads the database with data from a string generated by
the serialize_db_to_string method.
|
Reloads the database with data from a string generated by
the serialize_db_to_string method.
| def deserialize_db_from_string(self, data):
"""
Reloads the database with data from a string generated by
the serialize_db_to_string method.
"""
data = StringIO(data)
for obj in serializers.deserialize("json", data, using=self.connection.alias):
obj.save() | [
"def",
"deserialize_db_from_string",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"StringIO",
"(",
"data",
")",
"for",
"obj",
"in",
"serializers",
".",
"deserialize",
"(",
"\"json\"",
",",
"data",
",",
"using",
"=",
"self",
".",
"connection",
".",
"a... | [
438,
4
] | [
445,
22
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation._get_test_db_name | (self) |
Internal implementation - returns the name of the test DB that will be
created. Only useful when called from create_test_db() and
_create_test_db() and when no external munging is done with the 'NAME'
or 'TEST_NAME' settings.
|
Internal implementation - returns the name of the test DB that will be
created. Only useful when called from create_test_db() and
_create_test_db() and when no external munging is done with the 'NAME'
or 'TEST_NAME' settings.
| def _get_test_db_name(self):
"""
Internal implementation - returns the name of the test DB that will be
created. Only useful when called from create_test_db() and
_create_test_db() and when no external munging is done with the 'NAME'
or 'TEST_NAME' settings.
"""
i... | [
"def",
"_get_test_db_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'TEST'",
"]",
"[",
"'NAME'",
"]",
":",
"return",
"self",
".",
"connection",
".",
"settings_dict",
"[",
"'TEST'",
"]",
"[",
"'NAME'",
"]",
"ret... | [
447,
4
] | [
456,
75
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation._create_test_db | (self, verbosity, autoclobber, keepdb=False) |
Internal implementation - creates the test db tables.
|
Internal implementation - creates the test db tables.
| def _create_test_db(self, verbosity, autoclobber, keepdb=False):
"""
Internal implementation - creates the test db tables.
"""
suffix = self.sql_table_creation_suffix()
test_database_name = self._get_test_db_name()
qn = self.connection.ops.quote_name
# Create t... | [
"def",
"_create_test_db",
"(",
"self",
",",
"verbosity",
",",
"autoclobber",
",",
"keepdb",
"=",
"False",
")",
":",
"suffix",
"=",
"self",
".",
"sql_table_creation_suffix",
"(",
")",
"test_database_name",
"=",
"self",
".",
"_get_test_db_name",
"(",
")",
"qn",
... | [
458,
4
] | [
503,
33
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.destroy_test_db | (self, old_database_name, verbosity=1, keepdb=False) |
Destroy a test database, prompting the user for confirmation if the
database already exists.
|
Destroy a test database, prompting the user for confirmation if the
database already exists.
| def destroy_test_db(self, old_database_name, verbosity=1, keepdb=False):
"""
Destroy a test database, prompting the user for confirmation if the
database already exists.
"""
self.connection.close()
test_database_name = self.connection.settings_dict['NAME']
if verb... | [
"def",
"destroy_test_db",
"(",
"self",
",",
"old_database_name",
",",
"verbosity",
"=",
"1",
",",
"keepdb",
"=",
"False",
")",
":",
"self",
".",
"connection",
".",
"close",
"(",
")",
"test_database_name",
"=",
"self",
".",
"connection",
".",
"settings_dict",... | [
505,
4
] | [
525,
64
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation._destroy_test_db | (self, test_database_name, verbosity) |
Internal implementation - remove the test db tables.
|
Internal implementation - remove the test db tables.
| def _destroy_test_db(self, test_database_name, verbosity):
"""
Internal implementation - remove the test db tables.
"""
# Remove the test database to clean up after
# ourselves. Connect to the previous database (not the test database)
# to do so, because it's not allowed ... | [
"def",
"_destroy_test_db",
"(",
"self",
",",
"test_database_name",
",",
"verbosity",
")",
":",
"# Remove the test database to clean up after",
"# ourselves. Connect to the previous database (not the test database)",
"# to do so, because it's not allowed to delete a database while being",
"... | [
527,
4
] | [
539,
80
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.sql_table_creation_suffix | (self) |
SQL to append to the end of the test table creation statements.
|
SQL to append to the end of the test table creation statements.
| def sql_table_creation_suffix(self):
"""
SQL to append to the end of the test table creation statements.
"""
return '' | [
"def",
"sql_table_creation_suffix",
"(",
"self",
")",
":",
"return",
"''"
] | [
541,
4
] | [
545,
17
] | python | en | ['en', 'error', 'th'] | False |
BaseDatabaseCreation.test_db_signature | (self) |
Returns a tuple with elements of self.connection.settings_dict (a
DATABASES setting value) that uniquely identify a database
accordingly to the RDBMS particularities.
|
Returns a tuple with elements of self.connection.settings_dict (a
DATABASES setting value) that uniquely identify a database
accordingly to the RDBMS particularities.
| def test_db_signature(self):
"""
Returns a tuple with elements of self.connection.settings_dict (a
DATABASES setting value) that uniquely identify a database
accordingly to the RDBMS particularities.
"""
settings_dict = self.connection.settings_dict
return (
... | [
"def",
"test_db_signature",
"(",
"self",
")",
":",
"settings_dict",
"=",
"self",
".",
"connection",
".",
"settings_dict",
"return",
"(",
"settings_dict",
"[",
"'HOST'",
"]",
",",
"settings_dict",
"[",
"'PORT'",
"]",
",",
"settings_dict",
"[",
"'ENGINE'",
"]",
... | [
547,
4
] | [
559,
9
] | python | en | ['en', 'error', 'th'] | False |
read_SVHN | (data_folder) | Reads and parses examples from SVHN data files | Reads and parses examples from SVHN data files | def read_SVHN(data_folder):
""" Reads and parses examples from SVHN data files """
train_img = []
train_label = []
test_img = []
test_label = []
train_file_list = ["train_32x32.mat", "extra_32x32.mat"]
test_file_list = ["test_32x32.mat"]
for i in range(len(train_file_list)):
t... | [
"def",
"read_SVHN",
"(",
"data_folder",
")",
":",
"train_img",
"=",
"[",
"]",
"train_label",
"=",
"[",
"]",
"test_img",
"=",
"[",
"]",
"test_label",
"=",
"[",
"]",
"train_file_list",
"=",
"[",
"\"train_32x32.mat\"",
",",
"\"extra_32x32.mat\"",
"]",
"test_fil... | [
46,
0
] | [
85,
55
] | python | en | ['en', 'en', 'en'] | True |
receiver | (signal, **kwargs) |
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_save, post_delete], sender=MyModel)
... |
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect:: | def receiver(signal, **kwargs):
"""
A decorator for connecting receivers to signals. Used by passing in the
signal (or list of signals) and keyword arguments to connect::
@receiver(post_save, sender=MyModel)
def signal_receiver(sender, **kwargs):
...
@receiver([post_sav... | [
"def",
"receiver",
"(",
"signal",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_decorator",
"(",
"func",
")",
":",
"if",
"isinstance",
"(",
"signal",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"s",
"in",
"signal",
":",
"s",
".",
"connect... | [
271,
0
] | [
291,
21
] | python | en | ['en', 'error', 'th'] | False |
Signal.__init__ | (self, providing_args=None, use_caching=False) |
Create a new signal.
providing_args
A list of the arguments this signal can pass along in a send() call.
|
Create a new signal. | def __init__(self, providing_args=None, use_caching=False):
"""
Create a new signal.
providing_args
A list of the arguments this signal can pass along in a send() call.
"""
self.receivers = []
if providing_args is None:
providing_args = []
... | [
"def",
"__init__",
"(",
"self",
",",
"providing_args",
"=",
"None",
",",
"use_caching",
"=",
"False",
")",
":",
"self",
".",
"receivers",
"=",
"[",
"]",
"if",
"providing_args",
"is",
"None",
":",
"providing_args",
"=",
"[",
"]",
"self",
".",
"providing_a... | [
27,
4
] | [
46,
36
] | python | en | ['en', 'error', 'th'] | False |
Signal.connect | (self, receiver, sender=None, weak=True, dispatch_uid=None) |
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
If weak is True, then receiver must be weak referenceable.
Receive... |
Connect receiver to sender for signal. | def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
"""
Connect receiver to sender for signal.
Arguments:
receiver
A function or an instance method which is to receive signals.
Receivers must be hashable objects.
... | [
"def",
"connect",
"(",
"self",
",",
"receiver",
",",
"sender",
"=",
"None",
",",
"weak",
"=",
"True",
",",
"dispatch_uid",
"=",
"None",
")",
":",
"from",
"django",
".",
"conf",
"import",
"settings",
"# If DEBUG is on, check that we got a good receiver",
"if",
... | [
48,
4
] | [
110,
47
] | python | en | ['en', 'error', 'th'] | False |
Signal.disconnect | (self, receiver=None, sender=None, dispatch_uid=None) |
Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be removed from dispatch automatically.
Arguments:
receiver
The registered receiver to disconnect. May be none if
disp... |
Disconnect receiver from sender for signal. | def disconnect(self, receiver=None, sender=None, dispatch_uid=None):
"""
Disconnect receiver from sender for signal.
If weak references are used, disconnect need not be called. The receiver
will be removed from dispatch automatically.
Arguments:
receiver
... | [
"def",
"disconnect",
"(",
"self",
",",
"receiver",
"=",
"None",
",",
"sender",
"=",
"None",
",",
"dispatch_uid",
"=",
"None",
")",
":",
"if",
"dispatch_uid",
":",
"lookup_key",
"=",
"(",
"dispatch_uid",
",",
"_make_id",
"(",
"sender",
")",
")",
"else",
... | [
112,
4
] | [
146,
27
] | python | en | ['en', 'error', 'th'] | False |
Signal.send | (self, sender, **named) |
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
... |
Send signal from sender to all connected receivers. | def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Ar... | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":",
"return",
"[",
"]",
"return",
... | [
151,
4
] | [
175,
9
] | python | en | ['en', 'error', 'th'] | False |
Signal.send_robust | (self, sender, **named) |
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any Python object (normally one
registered with a connect if you actually want something to
occur).
named
... |
Send signal from sender to all connected receivers catching errors. | def send_robust(self, sender, **named):
"""
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any Python object (normally one
registered with a connect if you actually want somethin... | [
"def",
"send_robust",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":",
"return",
"[",
"]",
"# Ca... | [
177,
4
] | [
211,
24
] | python | en | ['en', 'error', 'th'] | False |
Signal._live_receivers | (self, sender) |
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
|
Filter sequence of receivers to get resolved, live receivers. | def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
receivers = None
if self.use_caching and not self._dead_receivers:
... | [
"def",
"_live_receivers",
"(",
"self",
",",
"sender",
")",
":",
"receivers",
"=",
"None",
"if",
"self",
".",
"use_caching",
"and",
"not",
"self",
".",
"_dead_receivers",
":",
"receivers",
"=",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",... | [
222,
4
] | [
259,
33
] | python | en | ['en', 'error', 'th'] | False |
handle_default_options | (options) |
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
|
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands. | def handle_default_options(options):
"""
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
"""
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonp... | [
"def",
"handle_default_options",
"(",
"options",
")",
":",
"if",
"options",
".",
"settings",
":",
"os",
".",
"environ",
"[",
"'DJANGO_SETTINGS_MODULE'",
"]",
"=",
"options",
".",
"settings",
"if",
"options",
".",
"pythonpath",
":",
"sys",
".",
"path",
".",
... | [
64,
0
] | [
74,
46
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.get_version | (self) |
Return the Django version, which should be correct for all
built-in Django commands. User-supplied commands should
override this method.
|
Return the Django version, which should be correct for all
built-in Django commands. User-supplied commands should
override this method. | def get_version(self):
"""
Return the Django version, which should be correct for all
built-in Django commands. User-supplied commands should
override this method.
"""
return django.get_version() | [
"def",
"get_version",
"(",
"self",
")",
":",
"return",
"django",
".",
"get_version",
"(",
")"
] | [
253,
4
] | [
260,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.usage | (self, subcommand) |
Return a brief description of how to use this command, by
default from the attribute ``self.help``.
|
Return a brief description of how to use this command, by
default from the attribute ``self.help``. | def usage(self, subcommand):
"""
Return a brief description of how to use this command, by
default from the attribute ``self.help``.
"""
usage = '%%prog %s [options] %s' % (subcommand, self.args)
if self.help:
return '%s\n\n%s' % (usage, self.help)
el... | [
"def",
"usage",
"(",
"self",
",",
"subcommand",
")",
":",
"usage",
"=",
"'%%prog %s [options] %s'",
"%",
"(",
"subcommand",
",",
"self",
".",
"args",
")",
"if",
"self",
".",
"help",
":",
"return",
"'%s\\n\\n%s'",
"%",
"(",
"usage",
",",
"self",
".",
"h... | [
262,
4
] | [
272,
24
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.create_parser | (self, prog_name, subcommand) |
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
|
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command. | def create_parser(self, prog_name, subcommand):
"""
Create and return the ``ArgumentParser`` which will be used to
parse the arguments to this command.
"""
if not self.use_argparse:
# Backwards compatibility: use deprecated optparse module
warnings.warn("... | [
"def",
"create_parser",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"if",
"not",
"self",
".",
"use_argparse",
":",
"# Backwards compatibility: use deprecated optparse module",
"warnings",
".",
"warn",
"(",
"\"OptionParser usage for Django management commands... | [
274,
4
] | [
330,
21
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.add_arguments | (self, parser) |
Entry point for subclassed commands to add custom arguments.
|
Entry point for subclassed commands to add custom arguments.
| def add_arguments(self, parser):
"""
Entry point for subclassed commands to add custom arguments.
"""
pass | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"pass"
] | [
332,
4
] | [
336,
12
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.print_help | (self, prog_name, subcommand) |
Print the help message for this command, derived from
``self.usage()``.
|
Print the help message for this command, derived from
``self.usage()``. | def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help() | [
"def",
"print_help",
"(",
"self",
",",
"prog_name",
",",
"subcommand",
")",
":",
"parser",
"=",
"self",
".",
"create_parser",
"(",
"prog_name",
",",
"subcommand",
")",
"parser",
".",
"print_help",
"(",
")"
] | [
338,
4
] | [
345,
27
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.run_from_argv | (self, argv) |
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the raised
``Exception`` is not ``CommandE... |
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the raised
``Exception`` is not ``CommandE... | def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the rais... | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"self",
".",
"_called_from_command_line",
"=",
"True",
"parser",
"=",
"self",
".",
"create_parser",
"(",
"argv",
"[",
"0",
"]",
",",
"argv",
"[",
"1",
"]",
")",
"if",
"self",
".",
"use_argpars... | [
347,
4
] | [
376,
23
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.execute | (self, *args, **options) |
Try to execute this command, performing system checks if needed (as
controlled by attributes ``self.requires_system_checks`` and
``self.requires_model_validation``, except if force-skipped).
|
Try to execute this command, performing system checks if needed (as
controlled by attributes ``self.requires_system_checks`` and
``self.requires_model_validation``, except if force-skipped).
| def execute(self, *args, **options):
"""
Try to execute this command, performing system checks if needed (as
controlled by attributes ``self.requires_system_checks`` and
``self.requires_model_validation``, except if force-skipped).
"""
self.stdout = OutputWrapper(options.... | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"self",
".",
"stdout",
"=",
"OutputWrapper",
"(",
"options",
".",
"get",
"(",
"'stdout'",
",",
"sys",
".",
"stdout",
")",
")",
"if",
"options",
".",
"get",
"(",
... | [
378,
4
] | [
432,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.validate | (self, app_config=None, display_num_errors=False) | Deprecated. Delegates to ``check``. | Deprecated. Delegates to ``check``. | def validate(self, app_config=None, display_num_errors=False):
""" Deprecated. Delegates to ``check``."""
if app_config is None:
app_configs = None
else:
app_configs = [app_config]
return self.check(app_configs=app_configs, display_num_errors=display_num_errors) | [
"def",
"validate",
"(",
"self",
",",
"app_config",
"=",
"None",
",",
"display_num_errors",
"=",
"False",
")",
":",
"if",
"app_config",
"is",
"None",
":",
"app_configs",
"=",
"None",
"else",
":",
"app_configs",
"=",
"[",
"app_config",
"]",
"return",
"self",... | [
434,
4
] | [
442,
89
] | python | en | ['en', 'it', 'en'] | True |
BaseCommand.check | (self, app_configs=None, tags=None, display_num_errors=False,
include_deployment_checks=False) |
Uses the system check framework to validate entire Django project.
Raises CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), they are printed to
stderr and no exception is raised.
|
Uses the system check framework to validate entire Django project.
Raises CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), they are printed to
stderr and no exception is raised.
| def check(self, app_configs=None, tags=None, display_num_errors=False,
include_deployment_checks=False):
"""
Uses the system check framework to validate entire Django project.
Raises CommandError for any serious message (error or critical errors).
If there are only light me... | [
"def",
"check",
"(",
"self",
",",
"app_configs",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"display_num_errors",
"=",
"False",
",",
"include_deployment_checks",
"=",
"False",
")",
":",
"all_issues",
"=",
"checks",
".",
"run_checks",
"(",
"app_configs",
"="... | [
444,
4
] | [
503,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseCommand.handle | (self, *args, **options) |
The actual logic of the command. Subclasses must implement
this method.
|
The actual logic of the command. Subclasses must implement
this method. | def handle(self, *args, **options):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError('subclasses of BaseCommand must provide a handle() method') | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of BaseCommand must provide a handle() method'",
")"
] | [
505,
4
] | [
511,
93
] | python | en | ['en', 'error', 'th'] | False |
AppCommand.handle_app_config | (self, app_config, **options) |
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
|
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
| def handle_app_config(self, app_config, **options):
"""
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
"""
try:
# During the deprecation path, keep delegating to handle_app if
... | [
"def",
"handle_app_config",
"(",
"self",
",",
"app_config",
",",
"*",
"*",
"options",
")",
":",
"try",
":",
"# During the deprecation path, keep delegating to handle_app if",
"# handle_app_config isn't implemented in a subclass.",
"handle_app",
"=",
"self",
".",
"handle_app",... | [
541,
4
] | [
565,
66
] | python | en | ['en', 'error', 'th'] | False |
LabelCommand.handle_label | (self, label, **options) |
Perform the command's actions for ``label``, which will be the
string as given on the command line.
|
Perform the command's actions for ``label``, which will be the
string as given on the command line. | def handle_label(self, label, **options):
"""
Perform the command's actions for ``label``, which will be the
string as given on the command line.
"""
raise NotImplementedError('subclasses of LabelCommand must provide a handle_label() method') | [
"def",
"handle_label",
"(",
"self",
",",
"label",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of LabelCommand must provide a handle_label() method'",
")"
] | [
595,
4
] | [
601,
100
] | python | en | ['en', 'error', 'th'] | False |
NoArgsCommand.handle_noargs | (self, **options) |
Perform this command's actions.
|
Perform this command's actions. | def handle_noargs(self, **options):
"""
Perform this command's actions.
"""
raise NotImplementedError('subclasses of NoArgsCommand must provide a handle_noargs() method') | [
"def",
"handle_noargs",
"(",
"self",
",",
"*",
"*",
"options",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of NoArgsCommand must provide a handle_noargs() method'",
")"
] | [
630,
4
] | [
635,
102
] | python | en | ['en', 'error', 'th'] | False |
CompletionCommand.run | (self, options, args) | Prints the completion code of the given shell | Prints the completion code of the given shell | def run(self, options, args):
"""Prints the completion code of the given shell"""
shells = COMPLETION_SCRIPTS.keys()
shell_options = ['--' + shell for shell in sorted(shells)]
if options.shell in shells:
script = textwrap.dedent(
COMPLETION_SCRIPTS.get(options... | [
"def",
"run",
"(",
"self",
",",
"options",
",",
"args",
")",
":",
"shells",
"=",
"COMPLETION_SCRIPTS",
".",
"keys",
"(",
")",
"shell_options",
"=",
"[",
"'--'",
"+",
"shell",
"for",
"shell",
"in",
"sorted",
"(",
"shells",
")",
"]",
"if",
"options",
"... | [
81,
4
] | [
94,
13
] | python | en | ['en', 'en', 'en'] | True |
test_validators_independence | (self) | Test that we are able to modify a form field validators list without polluting
other forms | Test that we are able to modify a form field validators list without polluting
other forms | def test_validators_independence(self):
""" Test that we are able to modify a form field validators list without polluting
other forms """
from django.core.validators import MaxValueValidator
class MyForm(Form):
myfield = CharField(max_length=25)
f1 = MyForm()
... | [
"def",
"test_validators_independence",
"(",
"self",
")",
":",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"MaxValueValidator",
"class",
"MyForm",
"(",
"Form",
")",
":",
"myfield",
"=",
"CharField",
"(",
"max_length",
"=",
"25",
")",
"f1",
"="... | [
945,
4
] | [
957,
98
] | python | en | ['en', 'en', 'en'] | True |
test_boundfield_rendering | (self) |
Python 2 issue: Test that rendering a BoundField with bytestring content
doesn't lose it's safe string status (#22950).
|
Python 2 issue: Test that rendering a BoundField with bytestring content
doesn't lose it's safe string status (#22950).
| def test_boundfield_rendering(self):
"""
Python 2 issue: Test that rendering a BoundField with bytestring content
doesn't lose it's safe string status (#22950).
"""
class CustomWidget(TextInput):
def render(self, name, value, attrs=None):
return format... | [
"def",
"test_boundfield_rendering",
"(",
"self",
")",
":",
"class",
"CustomWidget",
"(",
"TextInput",
")",
":",
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
")",
":",
"return",
"format_html",
"(",
"str",
"(",
"'<inp... | [
1379,
4
] | [
1392,
62
] | python | en | ['en', 'error', 'th'] | False |
_download | (url, filename) | Download a url to a file in the JAX data temp directory. | Download a url to a file in the JAX data temp directory. | def _download(url, filename):
"""Download a url to a file in the JAX data temp directory."""
if not path.exists(_DATA):
os.makedirs(_DATA)
out_file = path.join(_DATA, filename)
if not path.isfile(out_file):
urlretrieve(url, out_file)
print("downloaded {} to {}".format(url, _DATA)... | [
"def",
"_download",
"(",
"url",
",",
"filename",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"_DATA",
")",
":",
"os",
".",
"makedirs",
"(",
"_DATA",
")",
"out_file",
"=",
"path",
".",
"join",
"(",
"_DATA",
",",
"filename",
")",
"if",
"not",
... | [
17,
0
] | [
24,
55
] | python | en | ['en', 'en', 'en'] | True |
mnist_raw | (root=_DATA) | Download and parse the raw MNIST dataset. | Download and parse the raw MNIST dataset. | def mnist_raw(root=_DATA):
"""Download and parse the raw MNIST dataset."""
# CVDF mirror of http://yann.lecun.com/exdb/mnist/
base_url = "https://storage.googleapis.com/cvdf-datasets/mnist/"
def parse_labels(filename):
with gzip.open(filename, "rb") as fh:
_ = struct.unpack(">II", f... | [
"def",
"mnist_raw",
"(",
"root",
"=",
"_DATA",
")",
":",
"# CVDF mirror of http://yann.lecun.com/exdb/mnist/",
"base_url",
"=",
"\"https://storage.googleapis.com/cvdf-datasets/mnist/\"",
"def",
"parse_labels",
"(",
"filename",
")",
":",
"with",
"gzip",
".",
"open",
"(",
... | [
27,
0
] | [
57,
63
] | python | en | ['en', 'en', 'en'] | True |
Color.__init__ | (
self,
name: str,
number: Optional[int] = None,
triplet: Optional[Tuple[int, int, int]] = None,
) | Raw name of the color - the string from which it was derived from. | Raw name of the color - the string from which it was derived from. | def __init__(
self,
name: str,
number: Optional[int] = None,
triplet: Optional[Tuple[int, int, int]] = None,
):
"""Raw name of the color - the string from which it was derived from."""
self.name = name
"""The color number, if a standard color."""
self.... | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
",",
"number",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"triplet",
":",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
"=",
"None",
",",
")",
":",
"sel... | [
21,
4
] | [
32,
30
] | python | en | ['en', 'en', 'en'] | True |
Color.is_default | (self) | Check if the color is a default color. | Check if the color is a default color. | def is_default(self) -> bool:
"""Check if the color is a default color."""
return self.name == "default" or (self.number is None and self.triplet is None) | [
"def",
"is_default",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"self",
".",
"name",
"==",
"\"default\"",
"or",
"(",
"self",
".",
"number",
"is",
"None",
"and",
"self",
".",
"triplet",
"is",
"None",
")"
] | [
35,
4
] | [
37,
87
] | python | en | ['en', 'en', 'en'] | True |
Color.get_truecolor | (self) | Get an equivalent color triplet (R, G, B) for this color. | Get an equivalent color triplet (R, G, B) for this color. | def get_truecolor(self) -> Optional[Tuple[int, int, int]]:
"""Get an equivalent color triplet (R, G, B) for this color."""
if self.number is not None:
return EIGHT_BIT_PALETTE[self.number]
if self.triplet:
return self.triplet
return None | [
"def",
"get_truecolor",
"(",
"self",
")",
"->",
"Optional",
"[",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
"]",
":",
"if",
"self",
".",
"number",
"is",
"not",
"None",
":",
"return",
"EIGHT_BIT_PALETTE",
"[",
"self",
".",
"number",
"]",
"if",
... | [
39,
4
] | [
45,
19
] | python | en | ['en', 'en', 'en'] | True |
Color.get_ansi_codes | (self, foreground: bool = True, underline: bool = False) | Get the ANSI escape codes for this color. | Get the ANSI escape codes for this color. | def get_ansi_codes(self, foreground: bool = True, underline: bool = False) -> tuple:
"""Get the ANSI escape codes for this color."""
if self.is_default:
return ("39" if foreground else "59" if underline else "49",)
elif self.number < 16 and not underline:
fore, back = (3... | [
"def",
"get_ansi_codes",
"(",
"self",
",",
"foreground",
":",
"bool",
"=",
"True",
",",
"underline",
":",
"bool",
"=",
"False",
")",
"->",
"tuple",
":",
"if",
"self",
".",
"is_default",
":",
"return",
"(",
"\"39\"",
"if",
"foreground",
"else",
"\"59\"",
... | [
47,
4
] | [
64,
83
] | python | en | ['en', 'en', 'en'] | True |
Color.default | (cls) | Get a Color instance representing the default color. | Get a Color instance representing the default color. | def default(cls) -> "Color":
"""Get a Color instance representing the default color."""
return cls(name="default") | [
"def",
"default",
"(",
"cls",
")",
"->",
"\"Color\"",
":",
"return",
"cls",
"(",
"name",
"=",
"\"default\"",
")"
] | [
67,
4
] | [
69,
34
] | python | en | ['en', 'en', 'en'] | True |
Color.from_triplet | (cls, triplet: Tuple[int, int, int]) |
Create a RGB color from a triplet of values (R, G, B).
Returns a new Color object.
|
Create a RGB color from a triplet of values (R, G, B). | def from_triplet(cls, triplet: Tuple[int, int, int]) -> "Color":
"""
Create a RGB color from a triplet of values (R, G, B).
Returns a new Color object.
"""
return cls(name=str(triplet), triplet=triplet) | [
"def",
"from_triplet",
"(",
"cls",
",",
"triplet",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
")",
"->",
"\"Color\"",
":",
"return",
"cls",
"(",
"name",
"=",
"str",
"(",
"triplet",
")",
",",
"triplet",
"=",
"triplet",
")"
] | [
72,
4
] | [
78,
54
] | python | en | ['en', 'error', 'th'] | False |
Color.parse | (cls, color: str) | Parse a color from string. Can take a rgb(r,g,b), color(n), hex code or color name. | Parse a color from string. Can take a rgb(r,g,b), color(n), hex code or color name. | def parse(cls, color: str) -> "Color":
"""Parse a color from string. Can take a rgb(r,g,b), color(n), hex code or color name."""
# Check if default color
color = color.lower().strip()
if color == "default":
return cls(name=color)
# Check if named color
color... | [
"def",
"parse",
"(",
"cls",
",",
"color",
":",
"str",
")",
"->",
"\"Color\"",
":",
"# Check if default color",
"color",
"=",
"color",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"if",
"color",
"==",
"\"default\"",
":",
"return",
"cls",
"(",
"name",... | [
81,
4
] | [
121,
47
] | python | en | ['en', 'en', 'en'] | True |
instrumented_test_render | (self, context) |
An instrumented Template render method, providing a signal
that can be intercepted by the test system Client
|
An instrumented Template render method, providing a signal
that can be intercepted by the test system Client
| def instrumented_test_render(self, context):
"""
An instrumented Template render method, providing a signal
that can be intercepted by the test system Client
"""
template_rendered.send(sender=self, template=self, context=context)
return self.nodelist.render(context) | [
"def",
"instrumented_test_render",
"(",
"self",
",",
"context",
")",
":",
"template_rendered",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"template",
"=",
"self",
",",
"context",
"=",
"context",
")",
"return",
"self",
".",
"nodelist",
".",
"render",
"("... | [
82,
0
] | [
88,
40
] | python | en | ['en', 'error', 'th'] | False |
setup_test_environment | () | Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
| Perform any global pre-test setup. This involves: | def setup_test_environment():
"""Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
"""
Template._original_render = Templat... | [
"def",
"setup_test_environment",
"(",
")",
":",
"Template",
".",
"_original_render",
"=",
"Template",
".",
"_render",
"Template",
".",
"_render",
"=",
"instrumented_test_render",
"# Storing previous values in the settings module itself is problematic.",
"# Store them in arbitrary... | [
91,
0
] | [
112,
16
] | python | en | ['en', 'en', 'en'] | True |
teardown_test_environment | () | Perform any global post-test teardown. This involves:
- Restoring the original test renderer
- Restoring the email sending functions
| Perform any global post-test teardown. This involves: | def teardown_test_environment():
"""Perform any global post-test teardown. This involves:
- Restoring the original test renderer
- Restoring the email sending functions
"""
Template._render = Template._original_render
del Template._original_render
settings.EMAIL_BACKEND = mail._or... | [
"def",
"teardown_test_environment",
"(",
")",
":",
"Template",
".",
"_render",
"=",
"Template",
".",
"_original_render",
"del",
"Template",
".",
"_original_render",
"settings",
".",
"EMAIL_BACKEND",
"=",
"mail",
".",
"_original_email_backend",
"del",
"mail",
".",
... | [
115,
0
] | [
131,
19
] | python | en | ['en', 'en', 'en'] | True |
override_system_checks | (new_checks, deployment_checks=None) | Acts as a decorator. Overrides list of registered system checks.
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
you also need to exclude its system checks. | Acts as a decorator. Overrides list of registered system checks.
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
you also need to exclude its system checks. | def override_system_checks(new_checks, deployment_checks=None):
""" Acts as a decorator. Overrides list of registered system checks.
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
you also need to exclude its system checks. """
from django.core.checks.registry import registr... | [
"def",
"override_system_checks",
"(",
"new_checks",
",",
"deployment_checks",
"=",
"None",
")",
":",
"from",
"django",
".",
"core",
".",
"checks",
".",
"registry",
"import",
"registry",
"def",
"outer",
"(",
"test_func",
")",
":",
"@",
"wraps",
"(",
"test_fun... | [
361,
0
] | [
382,
16
] | python | en | ['en', 'en', 'en'] | True |
compare_xml | (want, got) | Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
| Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison. | def compare_xml(want, got):
"""Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doc... | [
"def",
"compare_xml",
"(",
"want",
",",
"got",
")",
":",
"_norm_whitespace_re",
"=",
"re",
".",
"compile",
"(",
"r'[ \\t\\n][ \\t\\n]+'",
")",
"def",
"norm_whitespace",
"(",
"v",
")",
":",
"return",
"_norm_whitespace_re",
".",
"sub",
"(",
"' '",
",",
"v",
... | [
385,
0
] | [
448,
45
] | python | en | ['en', 'en', 'en'] | True |
strip_quotes | (want, got) |
Strip quotes of doctests output values:
>>> strip_quotes("'foo'")
"foo"
>>> strip_quotes('"foo"')
"foo"
|
Strip quotes of doctests output values: | def strip_quotes(want, got):
"""
Strip quotes of doctests output values:
>>> strip_quotes("'foo'")
"foo"
>>> strip_quotes('"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"... | [
"def",
"strip_quotes",
"(",
"want",
",",
"got",
")",
":",
"def",
"is_quoted_string",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
"return",
"(",
"len",
"(",
"s",
")",
">=",
"2",
"and",
"s",
"[",
"0",
"]",
"==",
"s",
"[",
"-",
... | [
451,
0
] | [
479,
20
] | python | en | ['en', 'error', 'th'] | False |
patch_logger | (logger_name, log_level) |
Context manager that takes a named logger and the logging level
and provides a simple mock-like list of messages received
|
Context manager that takes a named logger and the logging level
and provides a simple mock-like list of messages received
| def patch_logger(logger_name, log_level):
"""
Context manager that takes a named logger and the logging level
and provides a simple mock-like list of messages received
"""
calls = []
def replacement(msg, *args, **kwargs):
calls.append(msg % args)
logger = logging.getLogger(logger_na... | [
"def",
"patch_logger",
"(",
"logger_name",
",",
"log_level",
")",
":",
"calls",
"=",
"[",
"]",
"def",
"replacement",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"calls",
".",
"append",
"(",
"msg",
"%",
"args",
")",
"logger",
"=... | [
546,
0
] | [
561,
40
] | python | en | ['en', 'error', 'th'] | False |
extend_sys_path | (*paths) | Context manager to temporarily add paths to sys.path. | Context manager to temporarily add paths to sys.path. | def extend_sys_path(*paths):
"""Context manager to temporarily add paths to sys.path."""
_orig_sys_path = sys.path[:]
sys.path.extend(paths)
try:
yield
finally:
sys.path = _orig_sys_path | [
"def",
"extend_sys_path",
"(",
"*",
"paths",
")",
":",
"_orig_sys_path",
"=",
"sys",
".",
"path",
"[",
":",
"]",
"sys",
".",
"path",
".",
"extend",
"(",
"paths",
")",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"path",
"=",
"_orig_sys_path"
] | [
575,
0
] | [
582,
33
] | python | en | ['en', 'en', 'en'] | True |
ContextList.keys | (self) |
Flattened keys of subcontexts.
|
Flattened keys of subcontexts.
| def keys(self):
"""
Flattened keys of subcontexts.
"""
keys = set()
for subcontext in self:
for dict in subcontext:
keys |= set(dict.keys())
return keys | [
"def",
"keys",
"(",
"self",
")",
":",
"keys",
"=",
"set",
"(",
")",
"for",
"subcontext",
"in",
"self",
":",
"for",
"dict",
"in",
"subcontext",
":",
"keys",
"|=",
"set",
"(",
"dict",
".",
"keys",
"(",
")",
")",
"return",
"keys"
] | [
71,
4
] | [
79,
19
] | python | en | ['en', 'error', 'th'] | False |
copy_exception | (exc, backend=None) |
Create a new TemplateDoesNotExist. Preserve its declared attributes and
template debug data but discard __traceback__, __context__, and __cause__
to make this object suitable for keeping around (in a cache, for example).
|
Create a new TemplateDoesNotExist. Preserve its declared attributes and
template debug data but discard __traceback__, __context__, and __cause__
to make this object suitable for keeping around (in a cache, for example).
| def copy_exception(exc, backend=None):
"""
Create a new TemplateDoesNotExist. Preserve its declared attributes and
template debug data but discard __traceback__, __context__, and __cause__
to make this object suitable for keeping around (in a cache, for example).
"""
backend = backend or exc.bac... | [
"def",
"copy_exception",
"(",
"exc",
",",
"backend",
"=",
"None",
")",
":",
"backend",
"=",
"backend",
"or",
"exc",
".",
"backend",
"new",
"=",
"exc",
".",
"__class__",
"(",
"*",
"exc",
".",
"args",
",",
"tried",
"=",
"exc",
".",
"tried",
",",
"bac... | [
65,
0
] | [
75,
14
] | python | en | ['en', 'error', 'th'] | False |
reraise | (exc, backend) |
Reraise TemplateDoesNotExist while maintaining template debug information.
|
Reraise TemplateDoesNotExist while maintaining template debug information.
| def reraise(exc, backend):
"""
Reraise TemplateDoesNotExist while maintaining template debug information.
"""
new = copy_exception(exc, backend)
raise new from exc | [
"def",
"reraise",
"(",
"exc",
",",
"backend",
")",
":",
"new",
"=",
"copy_exception",
"(",
"exc",
",",
"backend",
")",
"raise",
"new",
"from",
"exc"
] | [
78,
0
] | [
83,
22
] | python | en | ['en', 'error', 'th'] | False |
get_installed_libraries | () |
Return the built-in template tag libraries and those from installed
applications. Libraries are stored in a dictionary where keys are the
individual module names, not the full module paths. Example:
django.templatetags.i18n is stored as i18n.
|
Return the built-in template tag libraries and those from installed
applications. Libraries are stored in a dictionary where keys are the
individual module names, not the full module paths. Example:
django.templatetags.i18n is stored as i18n.
| def get_installed_libraries():
"""
Return the built-in template tag libraries and those from installed
applications. Libraries are stored in a dictionary where keys are the
individual module names, not the full module paths. Example:
django.templatetags.i18n is stored as i18n.
"""
libraries ... | [
"def",
"get_installed_libraries",
"(",
")",
":",
"libraries",
"=",
"{",
"}",
"candidates",
"=",
"[",
"'django.templatetags'",
"]",
"candidates",
".",
"extend",
"(",
"'%s.templatetags'",
"%",
"app_config",
".",
"name",
"for",
"app_config",
"in",
"apps",
".",
"g... | [
86,
0
] | [
110,
20
] | 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.