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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
load_pyproject_toml | (
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
) | Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
r... | Load the pyproject.toml file. | def load_pyproject_toml(
use_pep517, # type: Optional[bool]
pyproject_toml, # type: str
setup_py, # type: str
req_name # type: str
):
# type: (...) -> Optional[BuildSystemDetails]
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing... | [
"def",
"load_pyproject_toml",
"(",
"use_pep517",
",",
"# type: Optional[bool]",
"pyproject_toml",
",",
"# type: str",
"setup_py",
",",
"# type: str",
"req_name",
"# type: str",
")",
":",
"# type: (...) -> Optional[BuildSystemDetails]",
"has_pyproject",
"=",
"os",
".",
"path... | [
41,
0
] | [
195,
69
] | python | en | ['en', 'en', 'en'] | True |
perform_MIRC_search | (
image_from_loader,
target_list,
path,
model,
DEVICE,
Ullman_or_ImageNet,
descendent_specifier,
exp_dir,
write_or_append,
) | This procedure carries out the search for MIRCs - it's the meat of the search procedure!
High level: The search starts with the original, preprocessed image. Its classification accuracy for the whole image is evaluated. If it is above 0.5, the image gets successively cropped and reduced in resolution until the cla... | This procedure carries out the search for MIRCs - it's the meat of the search procedure! | def perform_MIRC_search(
image_from_loader,
target_list,
path,
model,
DEVICE,
Ullman_or_ImageNet,
descendent_specifier,
exp_dir,
write_or_append,
):
"""This procedure carries out the search for MIRCs - it's the meat of the search procedure!
High level: The search starts with... | [
"def",
"perform_MIRC_search",
"(",
"image_from_loader",
",",
"target_list",
",",
"path",
",",
"model",
",",
"DEVICE",
",",
"Ullman_or_ImageNet",
",",
"descendent_specifier",
",",
"exp_dir",
",",
"write_or_append",
",",
")",
":",
"image",
"=",
"torch",
".",
"sque... | [
17,
0
] | [
275,
5
] | python | en | ['en', 'en', 'en'] | True |
AuthRouter.db_for_read | (self, model, **hints) | Point all read operations on auth models to 'default | Point all read operations on auth models to 'default | def db_for_read(self, model, **hints):
"Point all read operations on auth models to 'default'"
if model._meta.app_label == 'auth':
# We use default here to ensure we can tell the difference
# between a read request and a write request for Auth objects
return 'default'... | [
"def",
"db_for_read",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
":",
"# We use default here to ensure we can tell the difference",
"# between a read request and a write request for Auth obje... | [
27,
4
] | [
33,
19
] | python | en | ['en', 'en', 'en'] | True |
AuthRouter.db_for_write | (self, model, **hints) | Point all operations on auth models to 'other | Point all operations on auth models to 'other | def db_for_write(self, model, **hints):
"Point all operations on auth models to 'other'"
if model._meta.app_label == 'auth':
return 'other'
return None | [
"def",
"db_for_write",
"(",
"self",
",",
"model",
",",
"*",
"*",
"hints",
")",
":",
"if",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
":",
"return",
"'other'",
"return",
"None"
] | [
35,
4
] | [
39,
19
] | python | en | ['en', 'en', 'en'] | True |
AuthRouter.allow_relation | (self, obj1, obj2, **hints) | Allow any relation if a model in Auth is involved | Allow any relation if a model in Auth is involved | def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in Auth is involved"
if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':
return True
return None | [
"def",
"allow_relation",
"(",
"self",
",",
"obj1",
",",
"obj2",
",",
"*",
"*",
"hints",
")",
":",
"if",
"obj1",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
"or",
"obj2",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
":",
"return",
"True",
"retu... | [
41,
4
] | [
45,
19
] | python | en | ['en', 'en', 'en'] | True |
AuthRouter.allow_migrate | (self, db, model) | Make sure the auth app only appears on the 'other' db | Make sure the auth app only appears on the 'other' db | def allow_migrate(self, db, model):
"Make sure the auth app only appears on the 'other' db"
if db == 'other':
return model._meta.app_label == 'auth'
elif model._meta.app_label == 'auth':
return False
return None | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"db",
"==",
"'other'",
":",
"return",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
"elif",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'auth'",
":",
"return",... | [
47,
4
] | [
53,
19
] | python | en | ['en', 'en', 'en'] | True |
expand_reqs | (fpath: str) |
Returns a sorted list of unique dependencies specified by the requirements file `fpath`.
Removes comments from the output and recursively visits files specified inside `fpath`.
`fpath` can be either an absolute path or a relative path.
|
Returns a sorted list of unique dependencies specified by the requirements file `fpath`.
Removes comments from the output and recursively visits files specified inside `fpath`.
`fpath` can be either an absolute path or a relative path.
| def expand_reqs(fpath: str) -> List[str]:
"""
Returns a sorted list of unique dependencies specified by the requirements file `fpath`.
Removes comments from the output and recursively visits files specified inside `fpath`.
`fpath` can be either an absolute path or a relative path.
"""
absfpath =... | [
"def",
"expand_reqs",
"(",
"fpath",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"absfpath",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"fpath",
")",
"output",
"=",
"expand_reqs_helper",
"(",
"absfpath",
")",
"return",
"sorted",
"(",
"set",
... | [
22,
0
] | [
30,
30
] | python | en | ['en', 'error', 'th'] | False |
python_version | () |
Returns the Python version as string 'Python major.minor.patchlevel'
|
Returns the Python version as string 'Python major.minor.patchlevel'
| def python_version() -> str:
"""
Returns the Python version as string 'Python major.minor.patchlevel'
"""
return subprocess.check_output(["/usr/bin/python3", "-VV"], universal_newlines=True) | [
"def",
"python_version",
"(",
")",
"->",
"str",
":",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"\"/usr/bin/python3\"",
",",
"\"-VV\"",
"]",
",",
"universal_newlines",
"=",
"True",
")"
] | [
33,
0
] | [
37,
88
] | python | en | ['en', 'error', 'th'] | False |
tuplize | (seq) | Turn all nested sequences to tuples in given sequence. | Turn all nested sequences to tuples in given sequence. | def tuplize(seq):
"Turn all nested sequences to tuples in given sequence."
if isinstance(seq, (list, tuple)):
return tuple(tuplize(i) for i in seq)
return seq | [
"def",
"tuplize",
"(",
"seq",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"tuple",
"(",
"tuplize",
"(",
"i",
")",
"for",
"i",
"in",
"seq",
")",
"return",
"seq"
] | [
19,
0
] | [
23,
14
] | python | en | ['en', 'en', 'en'] | True |
strconvert | (d) | Converts all keys in dictionary to str type. | Converts all keys in dictionary to str type. | def strconvert(d):
"Converts all keys in dictionary to str type."
return dict((str(k), v) for k, v in six.iteritems(d)) | [
"def",
"strconvert",
"(",
"d",
")",
":",
"return",
"dict",
"(",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"d",
")",
")"
] | [
26,
0
] | [
28,
57
] | python | en | ['en', 'en', 'en'] | True |
BaseHeuristic.warning | (self, response) |
Return a valid 1xx warning header value describing the cache
adjustments.
The response is provided too allow warnings like 113
http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
to explicitly say response is over 24 hours old.
|
Return a valid 1xx warning header value describing the cache
adjustments. | def warning(self, response):
"""
Return a valid 1xx warning header value describing the cache
adjustments.
The response is provided too allow warnings like 113
http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need
to explicitly say response is over 24 hours old.... | [
"def",
"warning",
"(",
"self",
",",
"response",
")",
":",
"return",
"'110 - \"Response is Stale\"'"
] | [
21,
4
] | [
30,
42
] | python | en | ['en', 'error', 'th'] | False |
BaseHeuristic.update_headers | (self, response) | Update the response headers with any new headers.
NOTE: This SHOULD always include some Warning header to
signify that the response was cached by the client, not
by way of the provided headers.
| Update the response headers with any new headers. | def update_headers(self, response):
"""Update the response headers with any new headers.
NOTE: This SHOULD always include some Warning header to
signify that the response was cached by the client, not
by way of the provided headers.
"""
return {} | [
"def",
"update_headers",
"(",
"self",
",",
"response",
")",
":",
"return",
"{",
"}"
] | [
32,
4
] | [
39,
17
] | python | en | ['en', 'en', 'en'] | True |
normalize_eols | (raw_contents) |
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment.
Return the resulting block of text with normalized `\n` EOL sequences ready
to be written to disk using current platform's native EOLs.
|
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment. | def normalize_eols(raw_contents):
"""
Take a block of raw text that will be passed through str.splitlines() to
get universal newlines treatment.
Return the resulting block of text with normalized `\n` EOL sequences ready
to be written to disk using current platform's native EOLs.
"""
lines_... | [
"def",
"normalize_eols",
"(",
"raw_contents",
")",
":",
"lines_list",
"=",
"raw_contents",
".",
"splitlines",
"(",
")",
"# Ensure last line has its EOL",
"if",
"lines_list",
"and",
"lines_list",
"[",
"-",
"1",
"]",
":",
"lines_list",
".",
"append",
"(",
"''",
... | [
154,
0
] | [
166,
32
] | python | en | ['en', 'error', 'th'] | False |
write_pot_file | (potfile, msgs) |
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
|
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
| def write_pot_file(potfile, msgs):
"""
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
"""
pot_lines = msgs.splitlines()
if os.path.exists(potfile):
# Strip the header
lines = dropwhile(len, pot_lines)
else:
lines = []
found, hea... | [
"def",
"write_pot_file",
"(",
"potfile",
",",
"msgs",
")",
":",
"pot_lines",
"=",
"msgs",
".",
"splitlines",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"potfile",
")",
":",
"# Strip the header",
"lines",
"=",
"dropwhile",
"(",
"len",
",",
"... | [
169,
0
] | [
193,
22
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.work_path | (self) |
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
|
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
| def work_path(self):
"""
Path to a file which is being fed into GNU gettext pipeline. This may
be either a translatable or its preprocessed version.
"""
if not self.is_templatized:
return self.path
extension = {
'djangojs': 'c',
'django... | [
"def",
"work_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"self",
".",
"path",
"extension",
"=",
"{",
"'djangojs'",
":",
"'c'",
",",
"'django'",
":",
"'py'",
",",
"}",
".",
"get",
"(",
"self",
".",
"domain"... | [
82,
4
] | [
94,
64
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.preprocess | (self) |
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
|
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
| def preprocess(self):
"""
Preprocess (if necessary) a translatable file before passing it to
xgettext GNU gettext utility.
"""
if not self.is_templatized:
return
encoding = settings.FILE_CHARSET if self.command.settings_available else 'utf-8'
with ope... | [
"def",
"preprocess",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"encoding",
"=",
"settings",
".",
"FILE_CHARSET",
"if",
"self",
".",
"command",
".",
"settings_available",
"else",
"'utf-8'",
"with",
"open",
"(",
"self",
... | [
96,
4
] | [
114,
29
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.postprocess_messages | (self, msgs) |
Postprocess messages generated by xgettext GNU gettext utility.
Transform paths as if these messages were generated from original
translatable files rather than from preprocessed versions.
|
Postprocess messages generated by xgettext GNU gettext utility. | def postprocess_messages(self, msgs):
"""
Postprocess messages generated by xgettext GNU gettext utility.
Transform paths as if these messages were generated from original
translatable files rather than from preprocessed versions.
"""
if not self.is_templatized:
... | [
"def",
"postprocess_messages",
"(",
"self",
",",
"msgs",
")",
":",
"if",
"not",
"self",
".",
"is_templatized",
":",
"return",
"msgs",
"# Remove '.py' suffix",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"# Preserve '.\\' prefix on Windows to respect gettext behavior",... | [
116,
4
] | [
140,
9
] | python | en | ['en', 'error', 'th'] | False |
BuildFile.cleanup | (self) |
Remove a preprocessed copy of a translatable file (if any).
|
Remove a preprocessed copy of a translatable file (if any).
| def cleanup(self):
"""
Remove a preprocessed copy of a translatable file (if any).
"""
if self.is_templatized:
# This check is needed for the case of a symlinked file and its
# source being processed inside a single group (locale dir);
# removing eithe... | [
"def",
"cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_templatized",
":",
"# This check is needed for the case of a symlinked file and its",
"# source being processed inside a single group (locale dir);",
"# removing either of those two removes both.",
"if",
"os",
".",
"pa... | [
142,
4
] | [
151,
41
] | python | en | ['en', 'error', 'th'] | False |
Command.build_potfiles | (self) |
Build pot files and apply msguniq to them.
|
Build pot files and apply msguniq to them.
| def build_potfiles(self):
"""
Build pot files and apply msguniq to them.
"""
file_list = self.find_files(".")
self.remove_potfiles()
self.process_files(file_list)
potfiles = []
for path in self.locale_paths:
potfile = os.path.join(path, '%s.pot... | [
"def",
"build_potfiles",
"(",
"self",
")",
":",
"file_list",
"=",
"self",
".",
"find_files",
"(",
"\".\"",
")",
"self",
".",
"remove_potfiles",
"(",
")",
"self",
".",
"process_files",
"(",
"file_list",
")",
"potfiles",
"=",
"[",
"]",
"for",
"path",
"in",... | [
417,
4
] | [
441,
23
] | python | en | ['en', 'error', 'th'] | False |
Command.find_files | (self, root) |
Get all files in the given root. Also check that there is a matching
locale dir for each file.
|
Get all files in the given root. Also check that there is a matching
locale dir for each file.
| def find_files(self, root):
"""
Get all files in the given root. Also check that there is a matching
locale dir for each file.
"""
all_files = []
ignored_roots = []
if self.settings_available:
ignored_roots = [os.path.normpath(p) for p in (settings.MED... | [
"def",
"find_files",
"(",
"self",
",",
"root",
")",
":",
"all_files",
"=",
"[",
"]",
"ignored_roots",
"=",
"[",
"]",
"if",
"self",
".",
"settings_available",
":",
"ignored_roots",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
"for",
"p... | [
449,
4
] | [
482,
32
] | python | en | ['en', 'error', 'th'] | False |
Command.process_files | (self, file_list) |
Group translatable files by locale directory and run pot file build
process for each group.
|
Group translatable files by locale directory and run pot file build
process for each group.
| def process_files(self, file_list):
"""
Group translatable files by locale directory and run pot file build
process for each group.
"""
file_groups = {}
for translatable in file_list:
file_group = file_groups.setdefault(translatable.locale_dir, [])
... | [
"def",
"process_files",
"(",
"self",
",",
"file_list",
")",
":",
"file_groups",
"=",
"{",
"}",
"for",
"translatable",
"in",
"file_list",
":",
"file_group",
"=",
"file_groups",
".",
"setdefault",
"(",
"translatable",
".",
"locale_dir",
",",
"[",
"]",
")",
"... | [
484,
4
] | [
494,
54
] | python | en | ['en', 'error', 'th'] | False |
Command.process_locale_dir | (self, locale_dir, files) |
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory.
Use the xgettext GNU gettext utility.
|
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory. | def process_locale_dir(self, locale_dir, files):
"""
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory.
Use the xgettext GNU gettext utility.
"""
build_files = []
for translatable in files:
... | [
"def",
"process_locale_dir",
"(",
"self",
",",
"locale_dir",
",",
"files",
")",
":",
"build_files",
"=",
"[",
"]",
"for",
"translatable",
"in",
"files",
":",
"if",
"self",
".",
"verbosity",
">",
"1",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'pro... | [
496,
4
] | [
589,
32
] | python | en | ['en', 'error', 'th'] | False |
Command.write_po_file | (self, potfile, locale) |
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`.
Use msgmerge and msgattrib GNU gettext utilities.
|
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`. | def write_po_file(self, potfile, locale):
"""
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`.
Use msgmerge and msgattrib GNU gettext utilities.
"""
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
... | [
"def",
"write_po_file",
"(",
"self",
",",
"potfile",
",",
"locale",
")",
":",
"basedir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"potfile",
")",
",",
"locale",
",",
"'LC_MESSAGES'",
")",
"os",
".",
"makedirs"... | [
591,
4
] | [
630,
45
] | python | en | ['en', 'error', 'th'] | False |
Command.copy_plural_forms | (self, msgs, locale) |
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
|
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
| def copy_plural_forms(self, msgs, locale):
"""
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
"""
django_dir = os.path.normpath(os.path.join(os... | [
"def",
"copy_plural_forms",
"(",
"self",
",",
"msgs",
",",
"locale",
")",
":",
"django_dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"django",
".",
"__file__",
")",
... | [
632,
4
] | [
661,
19
] | python | en | ['en', 'error', 'th'] | False |
plot_report_from_path | (
path,
success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES,
label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True,
) |
Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that
should be used to measure success rate
:param f... |
Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepath for the stored report.
(Should be the output of make_confidence_report*.py)
:param success_name: The name (confidence report key) of the data that
should be used to measure success rate
:param f... | def plot_report_from_path(
path,
success_name=DEFAULT_SUCCESS_NAME,
fail_names=DEFAULT_FAIL_NAMES,
label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True,
):
"""
Plots a success-fail curve from a confidence report stored on disk,
:param path: string filepa... | [
"def",
"plot_report_from_path",
"(",
"path",
",",
"success_name",
"=",
"DEFAULT_SUCCESS_NAME",
",",
"fail_names",
"=",
"DEFAULT_FAIL_NAMES",
",",
"label",
"=",
"None",
",",
"is_max_confidence",
"=",
"True",
",",
"linewidth",
"=",
"LINEWIDTH",
",",
"plot_upper_bound"... | [
18,
0
] | [
65,
5
] | python | en | ['en', 'error', 'th'] | False |
plot_report | (
report,
success_name,
fail_names,
label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True,
) |
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:param label: see plot_report_from_path
:param is_max_c... |
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:param label: see plot_report_from_path
:param is_max_c... | def plot_report(
report,
success_name,
fail_names,
label=None,
is_max_confidence=True,
linewidth=LINEWIDTH,
plot_upper_bound=True,
):
"""
Plot a success fail curve from a confidence report
:param report: A confidence report
(the type of object saved by make_confidence_repor... | [
"def",
"plot_report",
"(",
"report",
",",
"success_name",
",",
"fail_names",
",",
"label",
"=",
"None",
",",
"is_max_confidence",
"=",
"True",
",",
"linewidth",
"=",
"LINEWIDTH",
",",
"plot_upper_bound",
"=",
"True",
",",
")",
":",
"(",
"fail_optimal",
",",
... | [
68,
0
] | [
124,
37
] | python | en | ['en', 'error', 'th'] | False |
make_curve | (report, success_name, fail_names) |
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of failure rates on adversarial data for the ... |
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_optimal: list of failure rates on adversarial data for the ... | def make_curve(report, success_name, fail_names):
"""
Make a success-failure curve.
:param report: A confidence report
(the type of object saved by make_confidence_report.py)
:param success_name: see plot_report_from_path
:param fail_names: see plot_report_from_path
:returns:
fail_op... | [
"def",
"make_curve",
"(",
"report",
",",
"success_name",
",",
"fail_names",
")",
":",
"success_results",
"=",
"report",
"[",
"success_name",
"]",
"fail_name",
"=",
"None",
"# pacify pylint",
"found",
"=",
"False",
"for",
"fail_name",
"in",
"fail_names",
":",
"... | [
127,
0
] | [
316,
14
] | python | en | ['en', 'error', 'th'] | False |
serve | (request, path, insecure=False, **kwargs) |
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
path('<path:path>', views.serve)
in your URLconf.
It uses the django.views... |
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders. | def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
path('<path:path>', views... | [
"def",
"serve",
"(",
"request",
",",
"path",
",",
"insecure",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"settings",
".",
"DEBUG",
"and",
"not",
"insecure",
":",
"raise",
"Http404",
"normalized_path",
"=",
"posixpath",
".",
"normpath",... | [
14,
0
] | [
38,
77
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.optimize | (self, operations, app_label=None) |
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances.
Unfortunately, due to the scope of the optimization (two combinable
operations might be separated by several hundred others), this can't be
done as a peephole optimi... |
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances. | def optimize(self, operations, app_label=None):
"""
Main optimization entry point. Pass in a list of Operation instances,
get out a new list of Operation instances.
Unfortunately, due to the scope of the optimization (two combinable
operations might be separated by several hundr... | [
"def",
"optimize",
"(",
"self",
",",
"operations",
",",
"app_label",
"=",
"None",
")",
":",
"# Internal tracking variable for test assertions about # of loops",
"self",
".",
"_iterations",
"=",
"0",
"while",
"True",
":",
"result",
"=",
"self",
".",
"optimize_inner",... | [
17,
4
] | [
44,
31
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.optimize_inner | (self, operations, app_label=None) |
Inner optimization loop.
|
Inner optimization loop.
| def optimize_inner(self, operations, app_label=None):
"""
Inner optimization loop.
"""
new_operations = []
for i, operation in enumerate(operations):
# Compare it to each operation after it
for j, other in enumerate(operations[i + 1:]):
res... | [
"def",
"optimize_inner",
"(",
"self",
",",
"operations",
",",
"app_label",
"=",
"None",
")",
":",
"new_operations",
"=",
"[",
"]",
"for",
"i",
",",
"operation",
"in",
"enumerate",
"(",
"operations",
")",
":",
"# Compare it to each operation after it",
"for",
"... | [
46,
4
] | [
66,
29
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.reduce | (self, operation, other, in_between=None) |
Either returns a list of zero, one or two operations,
or None, meaning this pair cannot be optimized.
|
Either returns a list of zero, one or two operations,
or None, meaning this pair cannot be optimized.
| def reduce(self, operation, other, in_between=None):
"""
Either returns a list of zero, one or two operations,
or None, meaning this pair cannot be optimized.
"""
submethods = [
(
migrations.CreateModel,
migrations.DeleteModel,
... | [
"def",
"reduce",
"(",
"self",
",",
"operation",
",",
"other",
",",
"in_between",
"=",
"None",
")",
":",
"submethods",
"=",
"[",
"(",
"migrations",
".",
"CreateModel",
",",
"migrations",
".",
"DeleteModel",
",",
"self",
".",
"reduce_model_create_delete",
",",... | [
70,
4
] | [
160,
19
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.model_to_key | (self, model) |
Takes either a model class or a "appname.ModelName" string
and returns (appname, modelname)
|
Takes either a model class or a "appname.ModelName" string
and returns (appname, modelname)
| def model_to_key(self, model):
"""
Takes either a model class or a "appname.ModelName" string
and returns (appname, modelname)
"""
if isinstance(model, six.string_types):
return model.split(".", 1)
else:
return (
model._meta.app_lab... | [
"def",
"model_to_key",
"(",
"self",
",",
"model",
")",
":",
"if",
"isinstance",
"(",
"model",
",",
"six",
".",
"string_types",
")",
":",
"return",
"model",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"else",
":",
"return",
"(",
"model",
".",
"_meta",
... | [
162,
4
] | [
173,
13
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.reduce_model_create_delete | (self, operation, other, in_between) |
Folds a CreateModel and a DeleteModel into nothing.
|
Folds a CreateModel and a DeleteModel into nothing.
| def reduce_model_create_delete(self, operation, other, in_between):
"""
Folds a CreateModel and a DeleteModel into nothing.
"""
if (operation.name.lower() == other.name.lower() and
not operation.options.get("proxy", False)):
return [] | [
"def",
"reduce_model_create_delete",
"(",
"self",
",",
"operation",
",",
"other",
",",
"in_between",
")",
":",
"if",
"(",
"operation",
".",
"name",
".",
"lower",
"(",
")",
"==",
"other",
".",
"name",
".",
"lower",
"(",
")",
"and",
"not",
"operation",
"... | [
175,
4
] | [
181,
21
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.reduce_model_alter_delete | (self, operation, other, in_between) |
Folds an AlterModelSomething and a DeleteModel into just delete.
|
Folds an AlterModelSomething and a DeleteModel into just delete.
| def reduce_model_alter_delete(self, operation, other, in_between):
"""
Folds an AlterModelSomething and a DeleteModel into just delete.
"""
if operation.name.lower() == other.name.lower():
return [other] | [
"def",
"reduce_model_alter_delete",
"(",
"self",
",",
"operation",
",",
"other",
",",
"in_between",
")",
":",
"if",
"operation",
".",
"name",
".",
"lower",
"(",
")",
"==",
"other",
".",
"name",
".",
"lower",
"(",
")",
":",
"return",
"[",
"other",
"]"
] | [
183,
4
] | [
188,
26
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.reduce_model_create_rename | (self, operation, other, in_between) |
Folds a model rename into its create
|
Folds a model rename into its create
| def reduce_model_create_rename(self, operation, other, in_between):
"""
Folds a model rename into its create
"""
if operation.name.lower() == other.old_name.lower():
return [
migrations.CreateModel(
other.new_name,
field... | [
"def",
"reduce_model_create_rename",
"(",
"self",
",",
"operation",
",",
"other",
",",
"in_between",
")",
":",
"if",
"operation",
".",
"name",
".",
"lower",
"(",
")",
"==",
"other",
".",
"old_name",
".",
"lower",
"(",
")",
":",
"return",
"[",
"migrations... | [
190,
4
] | [
202,
13
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.reduce_model_rename_self | (self, operation, other, in_between) |
Folds a model rename into another one
|
Folds a model rename into another one
| def reduce_model_rename_self(self, operation, other, in_between):
"""
Folds a model rename into another one
"""
if operation.new_name.lower() == other.old_name.lower():
return [
migrations.RenameModel(
operation.old_name,
... | [
"def",
"reduce_model_rename_self",
"(",
"self",
",",
"operation",
",",
"other",
",",
"in_between",
")",
":",
"if",
"operation",
".",
"new_name",
".",
"lower",
"(",
")",
"==",
"other",
".",
"old_name",
".",
"lower",
"(",
")",
":",
"return",
"[",
"migratio... | [
204,
4
] | [
214,
13
] | python | en | ['en', 'error', 'th'] | False |
MigrationOptimizer.can_optimize_through | (self, operation, other, app_label=None) |
Returns True if it's possible to optimize 'operation' with something
the other side of 'other'. This is possible if, for example, they
affect different models.
|
Returns True if it's possible to optimize 'operation' with something
the other side of 'other'. This is possible if, for example, they
affect different models.
| def can_optimize_through(self, operation, other, app_label=None):
"""
Returns True if it's possible to optimize 'operation' with something
the other side of 'other'. This is possible if, for example, they
affect different models.
"""
MODEL_LEVEL_OPERATIONS = (
... | [
"def",
"can_optimize_through",
"(",
"self",
",",
"operation",
",",
"other",
",",
"app_label",
"=",
"None",
")",
":",
"MODEL_LEVEL_OPERATIONS",
"=",
"(",
"migrations",
".",
"CreateModel",
",",
"migrations",
".",
"AlterModelTable",
",",
"migrations",
".",
"AlterUn... | [
334,
4
] | [
360,
20
] | python | en | ['en', 'error', 'th'] | False |
DataSource.__del__ | (self) | Destroys this DataStructure object. | Destroys this DataStructure object. | def __del__(self):
"Destroys this DataStructure object."
if self._ptr and capi:
capi.destroy_ds(self._ptr) | [
"def",
"__del__",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ptr",
"and",
"capi",
":",
"capi",
".",
"destroy_ds",
"(",
"self",
".",
"_ptr",
")"
] | [
96,
4
] | [
99,
38
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__iter__ | (self) | Allows for iteration over the layers in a data source. | Allows for iteration over the layers in a data source. | def __iter__(self):
"Allows for iteration over the layers in a data source."
for i in xrange(self.layer_count):
yield self[i] | [
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"self",
".",
"layer_count",
")",
":",
"yield",
"self",
"[",
"i",
"]"
] | [
101,
4
] | [
104,
25
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__getitem__ | (self, index) | Allows use of the index [] operator to get a layer at the index. | Allows use of the index [] operator to get a layer at the index. | def __getitem__(self, index):
"Allows use of the index [] operator to get a layer at the index."
if isinstance(index, six.string_types):
l = capi.get_layer_by_name(self.ptr, force_bytes(index))
if not l:
raise OGRIndexError('invalid OGR Layer name given: "%s"' % i... | [
"def",
"__getitem__",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"six",
".",
"string_types",
")",
":",
"l",
"=",
"capi",
".",
"get_layer_by_name",
"(",
"self",
".",
"ptr",
",",
"force_bytes",
"(",
"index",
")",
")",
"... | [
106,
4
] | [
118,
29
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__len__ | (self) | Returns the number of layers within the data source. | Returns the number of layers within the data source. | def __len__(self):
"Returns the number of layers within the data source."
return self.layer_count | [
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"self",
".",
"layer_count"
] | [
120,
4
] | [
122,
31
] | python | en | ['en', 'en', 'en'] | True |
DataSource.__str__ | (self) | Returns OGR GetName and Driver for the Data Source. | Returns OGR GetName and Driver for the Data Source. | def __str__(self):
"Returns OGR GetName and Driver for the Data Source."
return '%s (%s)' % (self.name, str(self.driver)) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"'%s (%s)'",
"%",
"(",
"self",
".",
"name",
",",
"str",
"(",
"self",
".",
"driver",
")",
")"
] | [
124,
4
] | [
126,
56
] | python | en | ['en', 'en', 'en'] | True |
DataSource.layer_count | (self) | Returns the number of layers in the data source. | Returns the number of layers in the data source. | def layer_count(self):
"Returns the number of layers in the data source."
return capi.get_layer_count(self._ptr) | [
"def",
"layer_count",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_layer_count",
"(",
"self",
".",
"_ptr",
")"
] | [
129,
4
] | [
131,
46
] | python | en | ['en', 'en', 'en'] | True |
DataSource.name | (self) | Returns the name of the data source. | Returns the name of the data source. | def name(self):
"Returns the name of the data source."
name = capi.get_ds_name(self._ptr)
return force_text(name, self.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_ds_name",
"(",
"self",
".",
"_ptr",
")",
"return",
"force_text",
"(",
"name",
",",
"self",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
134,
4
] | [
137,
65
] | python | en | ['en', 'en', 'en'] | True |
new_date | (d) | Generate a safe date from a datetime.date object. | Generate a safe date from a datetime.date object. | def new_date(d):
"Generate a safe date from a datetime.date object."
return date(d.year, d.month, d.day) | [
"def",
"new_date",
"(",
"d",
")",
":",
"return",
"date",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
")"
] | [
33,
0
] | [
35,
39
] | python | en | ['en', 'en', 'en'] | True |
new_datetime | (d) |
Generate a safe datetime from a datetime.date or datetime.datetime object.
|
Generate a safe datetime from a datetime.date or datetime.datetime object.
| def new_datetime(d):
"""
Generate a safe datetime from a datetime.date or datetime.datetime object.
"""
kw = [d.year, d.month, d.day]
if isinstance(d, real_datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime(*kw) | [
"def",
"new_datetime",
"(",
"d",
")",
":",
"kw",
"=",
"[",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
"]",
"if",
"isinstance",
"(",
"d",
",",
"real_datetime",
")",
":",
"kw",
".",
"extend",
"(",
"[",
"d",
".",
"hour",
","... | [
38,
0
] | [
45,
24
] | python | en | ['en', 'error', 'th'] | False |
get_return_data_type | (func_name) | Return a somewhat-helpful data type given a function name | Return a somewhat-helpful data type given a function name | def get_return_data_type(func_name):
"""Return a somewhat-helpful data type given a function name"""
if func_name.startswith('get_'):
if func_name.endswith('_list'):
return 'List'
elif func_name.endswith('_count'):
return 'Integer'
return '' | [
"def",
"get_return_data_type",
"(",
"func_name",
")",
":",
"if",
"func_name",
".",
"startswith",
"(",
"'get_'",
")",
":",
"if",
"func_name",
".",
"endswith",
"(",
"'_list'",
")",
":",
"return",
"'List'",
"elif",
"func_name",
".",
"endswith",
"(",
"'_count'",... | [
325,
0
] | [
332,
13
] | python | en | ['en', 'en', 'en'] | True |
get_readable_field_data_type | (field) | Returns the description for a given field type, if it exists,
Fields' descriptions can contain format strings, which will be interpolated
against the values of field.__dict__ before being output. | Returns the description for a given field type, if it exists,
Fields' descriptions can contain format strings, which will be interpolated
against the values of field.__dict__ before being output. | def get_readable_field_data_type(field):
"""Returns the description for a given field type, if it exists,
Fields' descriptions can contain format strings, which will be interpolated
against the values of field.__dict__ before being output."""
return field.description % field.__dict__ | [
"def",
"get_readable_field_data_type",
"(",
"field",
")",
":",
"return",
"field",
".",
"description",
"%",
"field",
".",
"__dict__"
] | [
335,
0
] | [
340,
45
] | python | en | ['en', 'en', 'en'] | True |
extract_views_from_urlpatterns | (urlpatterns, base='', namespace=None) |
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
|
Return a list of views from a list of urlpatterns. | def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None):
"""
Return a list of views from a list of urlpatterns.
Each object in the returned list is a two-tuple: (view_func, regex)
"""
views = []
for p in urlpatterns:
if hasattr(p, 'url_patterns'):
try:
... | [
"def",
"extract_views_from_urlpatterns",
"(",
"urlpatterns",
",",
"base",
"=",
"''",
",",
"namespace",
"=",
"None",
")",
":",
"views",
"=",
"[",
"]",
"for",
"p",
"in",
"urlpatterns",
":",
"if",
"hasattr",
"(",
"p",
",",
"'url_patterns'",
")",
":",
"try",... | [
343,
0
] | [
369,
16
] | python | en | ['en', 'error', 'th'] | False |
simplify_regex | (pattern) |
Clean up urlpattern regexes into something somewhat readable by Mere Humans:
turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "<sport_slug>/athletes/<athlete_slug>/"
|
Clean up urlpattern regexes into something somewhat readable by Mere Humans:
turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "<sport_slug>/athletes/<athlete_slug>/"
| def simplify_regex(pattern):
"""
Clean up urlpattern regexes into something somewhat readable by Mere Humans:
turns something like "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
into "<sport_slug>/athletes/<athlete_slug>/"
"""
# handle named groups first
pattern = named_group_matche... | [
"def",
"simplify_regex",
"(",
"pattern",
")",
":",
"# handle named groups first",
"pattern",
"=",
"named_group_matcher",
".",
"sub",
"(",
"lambda",
"m",
":",
"m",
".",
"group",
"(",
"1",
")",
",",
"pattern",
")",
"# handle non-named groups",
"pattern",
"=",
"n... | [
375,
0
] | [
391,
18
] | python | en | ['en', 'error', 'th'] | False |
admin_url | (pattern, view, name) |
Define an URL pattern which requires Respa Admin login.
|
Define an URL pattern which requires Respa Admin login.
| def admin_url(pattern, view, name):
"""
Define an URL pattern which requires Respa Admin login.
"""
return url(pattern, admin_login_required(view), name=name) | [
"def",
"admin_url",
"(",
"pattern",
",",
"view",
",",
"name",
")",
":",
"return",
"url",
"(",
"pattern",
",",
"admin_login_required",
"(",
"view",
")",
",",
"name",
"=",
"name",
")"
] | [
6,
0
] | [
10,
62
] | python | en | ['en', 'error', 'th'] | False |
admin_login_required | (function) |
Decorator which requires login as Respa Admin allowed user.
|
Decorator which requires login as Respa Admin allowed user.
| def admin_login_required(function):
"""
Decorator which requires login as Respa Admin allowed user.
"""
decorator = user_passes_test(
is_allowed_user,
login_url='respa_admin:login')
return decorator(function) | [
"def",
"admin_login_required",
"(",
"function",
")",
":",
"decorator",
"=",
"user_passes_test",
"(",
"is_allowed_user",
",",
"login_url",
"=",
"'respa_admin:login'",
")",
"return",
"decorator",
"(",
"function",
")"
] | [
13,
0
] | [
20,
30
] | python | en | ['en', 'error', 'th'] | False |
is_allowed_user | (user) |
Test if given user is allowed to use Respa Admin.
:type user: django.contrib.auth.models.AbstractUser
:rtype: bool
|
Test if given user is allowed to use Respa Admin. | def is_allowed_user(user):
"""
Test if given user is allowed to use Respa Admin.
:type user: django.contrib.auth.models.AbstractUser
:rtype: bool
"""
if not user or not user.is_authenticated or not user.is_active:
return False
return can_login_to_respa_admin(user) | [
"def",
"is_allowed_user",
"(",
"user",
")",
":",
"if",
"not",
"user",
"or",
"not",
"user",
".",
"is_authenticated",
"or",
"not",
"user",
".",
"is_active",
":",
"return",
"False",
"return",
"can_login_to_respa_admin",
"(",
"user",
")"
] | [
23,
0
] | [
32,
41
] | python | en | ['en', 'error', 'th'] | False |
retry | (*dargs, **dkw) |
Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object
|
Decorator function that instantiates the Retrying object
| def retry(*dargs, **dkw):
"""
Decorator function that instantiates the Retrying object
@param *dargs: positional arguments passed to Retrying object
@param **dkw: keyword arguments passed to the Retrying object
"""
# support both @retry and @retry() as valid syntax
if len(dargs) == 1 and cal... | [
"def",
"retry",
"(",
"*",
"dargs",
",",
"*",
"*",
"dkw",
")",
":",
"# support both @retry and @retry() as valid syntax",
"if",
"len",
"(",
"dargs",
")",
"==",
"1",
"and",
"callable",
"(",
"dargs",
"[",
"0",
"]",
")",
":",
"def",
"wrap_simple",
"(",
"f",
... | [
25,
0
] | [
52,
19
] | python | en | ['en', 'error', 'th'] | False |
Retrying.stop_after_attempt | (self, previous_attempt_number, delay_since_first_attempt_ms) | Stop after the previous attempt >= stop_max_attempt_number. | Stop after the previous attempt >= stop_max_attempt_number. | def stop_after_attempt(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Stop after the previous attempt >= stop_max_attempt_number."""
return previous_attempt_number >= self._stop_max_attempt_number | [
"def",
"stop_after_attempt",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"previous_attempt_number",
">=",
"self",
".",
"_stop_max_attempt_number"
] | [
140,
4
] | [
142,
71
] | python | en | ['en', 'en', 'en'] | True |
Retrying.stop_after_delay | (self, previous_attempt_number, delay_since_first_attempt_ms) | Stop after the time from the first attempt >= stop_max_delay. | Stop after the time from the first attempt >= stop_max_delay. | def stop_after_delay(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Stop after the time from the first attempt >= stop_max_delay."""
return delay_since_first_attempt_ms >= self._stop_max_delay | [
"def",
"stop_after_delay",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"delay_since_first_attempt_ms",
">=",
"self",
".",
"_stop_max_delay"
] | [
144,
4
] | [
146,
67
] | python | en | ['en', 'en', 'en'] | True |
Retrying.no_sleep | (self, previous_attempt_number, delay_since_first_attempt_ms) | Don't sleep at all before retrying. | Don't sleep at all before retrying. | def no_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Don't sleep at all before retrying."""
return 0 | [
"def",
"no_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"0"
] | [
148,
4
] | [
150,
16
] | python | en | ['en', 'en', 'en'] | True |
Retrying.fixed_sleep | (self, previous_attempt_number, delay_since_first_attempt_ms) | Sleep a fixed amount of time between each retry. | Sleep a fixed amount of time between each retry. | def fixed_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Sleep a fixed amount of time between each retry."""
return self._wait_fixed | [
"def",
"fixed_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"self",
".",
"_wait_fixed"
] | [
152,
4
] | [
154,
31
] | python | en | ['en', 'en', 'en'] | True |
Retrying.random_sleep | (self, previous_attempt_number, delay_since_first_attempt_ms) | Sleep a random amount of time between wait_random_min and wait_random_max | Sleep a random amount of time between wait_random_min and wait_random_max | def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""Sleep a random amount of time between wait_random_min and wait_random_max"""
return random.randint(self._wait_random_min, self._wait_random_max) | [
"def",
"random_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"return",
"random",
".",
"randint",
"(",
"self",
".",
"_wait_random_min",
",",
"self",
".",
"_wait_random_max",
")"
] | [
156,
4
] | [
158,
75
] | python | en | ['en', 'so', 'en'] | True |
Retrying.incrementing_sleep | (self, previous_attempt_number, delay_since_first_attempt_ms) |
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
|
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
| def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms):
"""
Sleep an incremental amount of time after each attempt, starting at
wait_incrementing_start and incrementing by wait_incrementing_increment
"""
result = self._wait_incrementing_start + (self.... | [
"def",
"incrementing_sleep",
"(",
"self",
",",
"previous_attempt_number",
",",
"delay_since_first_attempt_ms",
")",
":",
"result",
"=",
"self",
".",
"_wait_incrementing_start",
"+",
"(",
"self",
".",
"_wait_incrementing_increment",
"*",
"(",
"previous_attempt_number",
"... | [
160,
4
] | [
168,
21
] | python | en | ['en', 'error', 'th'] | False |
Attempt.get | (self, wrap_exception=False) |
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
|
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
| def get(self, wrap_exception=False):
"""
Return the return value of this Attempt instance or raise an Exception.
If wrap_exception is true, this Attempt is wrapped inside of a
RetryError before being raised.
"""
if self.has_exception:
if wrap_exception:
... | [
"def",
"get",
"(",
"self",
",",
"wrap_exception",
"=",
"False",
")",
":",
"if",
"self",
".",
"has_exception",
":",
"if",
"wrap_exception",
":",
"raise",
"RetryError",
"(",
"self",
")",
"else",
":",
"six",
".",
"reraise",
"(",
"self",
".",
"value",
"[",... | [
236,
4
] | [
248,
29
] | python | en | ['en', 'error', 'th'] | False |
get_connection | (using=None) |
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
|
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
| def get_connection(using=None):
"""
Get a database connection by name, or the default database connection
if no name is provided. This is a private API.
"""
if using is None:
using = DEFAULT_DB_ALIAS
return connections[using] | [
"def",
"get_connection",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"using",
"=",
"DEFAULT_DB_ALIAS",
"return",
"connections",
"[",
"using",
"]"
] | [
13,
0
] | [
20,
29
] | python | en | ['en', 'error', 'th'] | False |
get_autocommit | (using=None) |
Get the autocommit status of the connection.
|
Get the autocommit status of the connection.
| def get_autocommit(using=None):
"""
Get the autocommit status of the connection.
"""
return get_connection(using).get_autocommit() | [
"def",
"get_autocommit",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_autocommit",
"(",
")"
] | [
23,
0
] | [
27,
49
] | python | en | ['en', 'error', 'th'] | False |
set_autocommit | (autocommit, using=None) |
Set the autocommit status of the connection.
|
Set the autocommit status of the connection.
| def set_autocommit(autocommit, using=None):
"""
Set the autocommit status of the connection.
"""
return get_connection(using).set_autocommit(autocommit) | [
"def",
"set_autocommit",
"(",
"autocommit",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_autocommit",
"(",
"autocommit",
")"
] | [
30,
0
] | [
34,
59
] | python | en | ['en', 'error', 'th'] | False |
commit | (using=None) |
Commits a transaction.
|
Commits a transaction.
| def commit(using=None):
"""
Commits a transaction.
"""
get_connection(using).commit() | [
"def",
"commit",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"commit",
"(",
")"
] | [
37,
0
] | [
41,
34
] | python | en | ['en', 'error', 'th'] | False |
rollback | (using=None) |
Rolls back a transaction.
|
Rolls back a transaction.
| def rollback(using=None):
"""
Rolls back a transaction.
"""
get_connection(using).rollback() | [
"def",
"rollback",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"rollback",
"(",
")"
] | [
44,
0
] | [
48,
36
] | python | en | ['en', 'error', 'th'] | False |
savepoint | (using=None) |
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
|
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
| def savepoint(using=None):
"""
Creates a savepoint (if supported and required by the backend) inside the
current transaction. Returns an identifier for the savepoint that will be
used for the subsequent rollback or commit.
"""
return get_connection(using).savepoint() | [
"def",
"savepoint",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"savepoint",
"(",
")"
] | [
51,
0
] | [
57,
44
] | python | en | ['en', 'error', 'th'] | False |
savepoint_rollback | (sid, using=None) |
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
|
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
| def savepoint_rollback(sid, using=None):
"""
Rolls back the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_rollback(sid) | [
"def",
"savepoint_rollback",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_rollback",
"(",
"sid",
")"
] | [
60,
0
] | [
65,
49
] | python | en | ['en', 'error', 'th'] | False |
savepoint_commit | (sid, using=None) |
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
|
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
| def savepoint_commit(sid, using=None):
"""
Commits the most recent savepoint (if one exists). Does nothing if
savepoints are not supported.
"""
get_connection(using).savepoint_commit(sid) | [
"def",
"savepoint_commit",
"(",
"sid",
",",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"savepoint_commit",
"(",
"sid",
")"
] | [
68,
0
] | [
73,
47
] | python | en | ['en', 'error', 'th'] | False |
clean_savepoints | (using=None) |
Resets the counter used to generate unique savepoint ids in this thread.
|
Resets the counter used to generate unique savepoint ids in this thread.
| def clean_savepoints(using=None):
"""
Resets the counter used to generate unique savepoint ids in this thread.
"""
get_connection(using).clean_savepoints() | [
"def",
"clean_savepoints",
"(",
"using",
"=",
"None",
")",
":",
"get_connection",
"(",
"using",
")",
".",
"clean_savepoints",
"(",
")"
] | [
76,
0
] | [
80,
44
] | python | en | ['en', 'error', 'th'] | False |
get_rollback | (using=None) |
Gets the "needs rollback" flag -- for *advanced use* only.
|
Gets the "needs rollback" flag -- for *advanced use* only.
| def get_rollback(using=None):
"""
Gets the "needs rollback" flag -- for *advanced use* only.
"""
return get_connection(using).get_rollback() | [
"def",
"get_rollback",
"(",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"get_rollback",
"(",
")"
] | [
83,
0
] | [
87,
47
] | python | en | ['en', 'error', 'th'] | False |
set_rollback | (rollback, using=None) |
Sets or unsets the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, it triggers a rollback when exiting the
innermost enclosing atomic block that has `savepoint=True` (that's the
default). Use this to force a rollback without raising an exception.
When `rollback` is `F... |
Sets or unsets the "needs rollback" flag -- for *advanced use* only. | def set_rollback(rollback, using=None):
"""
Sets or unsets the "needs rollback" flag -- for *advanced use* only.
When `rollback` is `True`, it triggers a rollback when exiting the
innermost enclosing atomic block that has `savepoint=True` (that's the
default). Use this to force a rollback without r... | [
"def",
"set_rollback",
"(",
"rollback",
",",
"using",
"=",
"None",
")",
":",
"return",
"get_connection",
"(",
"using",
")",
".",
"set_rollback",
"(",
"rollback",
")"
] | [
90,
0
] | [
102,
55
] | python | en | ['en', 'error', 'th'] | False |
InheritanceTests.test_force_update_on_inherited_model_without_fields | (self) |
Issue 13864: force_update fails on subclassed models, if they don't
specify custom fields.
|
Issue 13864: force_update fails on subclassed models, if they don't
specify custom fields.
| def test_force_update_on_inherited_model_without_fields(self):
'''
Issue 13864: force_update fails on subclassed models, if they don't
specify custom fields.
'''
a = SubCounter(name="count", value=1)
a.save()
a.value = 2
a.save(force_update=True) | [
"def",
"test_force_update_on_inherited_model_without_fields",
"(",
"self",
")",
":",
"a",
"=",
"SubCounter",
"(",
"name",
"=",
"\"count\"",
",",
"value",
"=",
"1",
")",
"a",
".",
"save",
"(",
")",
"a",
".",
"value",
"=",
"2",
"a",
".",
"save",
"(",
"fo... | [
59,
4
] | [
67,
33
] | python | en | ['en', 'error', 'th'] | False |
_clean_credentials | (credentials) |
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
|
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions. | def _clean_credentials(credentials):
"""
Clean a dictionary of credentials of potentially sensitive info before
sending to less secure functions.
Not comprehensive - intended for user_login_failed signal
"""
SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)
... | [
"def",
"_clean_credentials",
"(",
"credentials",
")",
":",
"SENSITIVE_CREDENTIALS",
"=",
"re",
".",
"compile",
"(",
"'api|token|key|secret|password|signature'",
",",
"re",
".",
"I",
")",
"CLEANSED_SUBSTITUTE",
"=",
"'********************'",
"for",
"key",
"in",
"creden... | [
39,
0
] | [
51,
22
] | python | en | ['en', 'error', 'th'] | False |
authenticate | (request=None, **credentials) |
If the given credentials are valid, return a User object.
|
If the given credentials are valid, return a User object.
| def authenticate(request=None, **credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend, backend_path in _get_backends(return_tuples=True):
try:
inspect.getcallargs(backend.authenticate, request, **credentials)
except TypeError:
... | [
"def",
"authenticate",
"(",
"request",
"=",
"None",
",",
"*",
"*",
"credentials",
")",
":",
"for",
"backend",
",",
"backend_path",
"in",
"_get_backends",
"(",
"return_tuples",
"=",
"True",
")",
":",
"try",
":",
"inspect",
".",
"getcallargs",
"(",
"backend"... | [
60,
0
] | [
82,
105
] | python | en | ['en', 'error', 'th'] | False |
login | (request, user, backend=None) |
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
|
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
| def login(request, user, backend=None):
"""
Persist a user id and a backend in the request. This way a user doesn't
have to reauthenticate on every request. Note that data set during
the anonymous session is retained when the user logs in.
"""
session_auth_hash = ''
if user is None:
... | [
"def",
"login",
"(",
"request",
",",
"user",
",",
"backend",
"=",
"None",
")",
":",
"session_auth_hash",
"=",
"''",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"request",
".",
"user",
"if",
"hasattr",
"(",
"user",
",",
"'get_session_auth_hash'",
")",
... | [
85,
0
] | [
130,
74
] | python | en | ['en', 'error', 'th'] | False |
logout | (request) |
Remove the authenticated user's ID from the request and flush their session
data.
|
Remove the authenticated user's ID from the request and flush their session
data.
| def logout(request):
"""
Remove the authenticated user's ID from the request and flush their session
data.
"""
# Dispatch the signal before the user is logged out so the receivers have a
# chance to find out *who* logged out.
user = getattr(request, 'user', None)
if not getattr(user, 'is... | [
"def",
"logout",
"(",
"request",
")",
":",
"# Dispatch the signal before the user is logged out so the receivers have a",
"# chance to find out *who* logged out.",
"user",
"=",
"getattr",
"(",
"request",
",",
"'user'",
",",
"None",
")",
"if",
"not",
"getattr",
"(",
"user"... | [
133,
0
] | [
147,
38
] | python | en | ['en', 'error', 'th'] | False |
get_user_model | () |
Return the User model that is active in this project.
|
Return the User model that is active in this project.
| def get_user_model():
"""
Return the User model that is active in this project.
"""
try:
return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
except ValueError:
raise ImproperlyConfigured("AUTH_USER_MODEL must be of the form 'app_label.model_name'")
except ... | [
"def",
"get_user_model",
"(",
")",
":",
"try",
":",
"return",
"django_apps",
".",
"get_model",
"(",
"settings",
".",
"AUTH_USER_MODEL",
",",
"require_ready",
"=",
"False",
")",
"except",
"ValueError",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"AUTH_USER_MODEL m... | [
150,
0
] | [
161,
9
] | python | en | ['en', 'error', 'th'] | False |
get_user | (request) |
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
|
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
| def get_user(request):
"""
Return the user model instance associated with the given request session.
If no user is retrieved, return an instance of `AnonymousUser`.
"""
from .models import AnonymousUser
user = None
try:
user_id = _get_user_session_key(request)
backend_path = ... | [
"def",
"get_user",
"(",
"request",
")",
":",
"from",
".",
"models",
"import",
"AnonymousUser",
"user",
"=",
"None",
"try",
":",
"user_id",
"=",
"_get_user_session_key",
"(",
"request",
")",
"backend_path",
"=",
"request",
".",
"session",
"[",
"BACKEND_SESSION_... | [
164,
0
] | [
191,
34
] | python | en | ['en', 'error', 'th'] | False |
get_permission_codename | (action, opts) |
Return the codename of the permission for the specified action.
|
Return the codename of the permission for the specified action.
| def get_permission_codename(action, opts):
"""
Return the codename of the permission for the specified action.
"""
return '%s_%s' % (action, opts.model_name) | [
"def",
"get_permission_codename",
"(",
"action",
",",
"opts",
")",
":",
"return",
"'%s_%s'",
"%",
"(",
"action",
",",
"opts",
".",
"model_name",
")"
] | [
194,
0
] | [
198,
46
] | python | en | ['en', 'error', 'th'] | False |
update_session_auth_hash | (request, user) |
Updating a user's password logs out all sessions for the user.
Take the current request and the updated user object from which the new
session hash will be derived and update the session hash appropriately to
prevent a password change from logging out the session from which the
password was change... |
Updating a user's password logs out all sessions for the user. | def update_session_auth_hash(request, user):
"""
Updating a user's password logs out all sessions for the user.
Take the current request and the updated user object from which the new
session hash will be derived and update the session hash appropriately to
prevent a password change from logging ou... | [
"def",
"update_session_auth_hash",
"(",
"request",
",",
"user",
")",
":",
"request",
".",
"session",
".",
"cycle_key",
"(",
")",
"if",
"hasattr",
"(",
"user",
",",
"'get_session_auth_hash'",
")",
"and",
"request",
".",
"user",
"==",
"user",
":",
"request",
... | [
201,
0
] | [
212,
72
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection.host | (self) |
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In add... |
Getter method to remove any trailing dots that indicate the hostname is an FQDN. | def host(self):
"""
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name th... | [
"def",
"host",
"(",
"self",
")",
":",
"return",
"self",
".",
"_dns_host",
".",
"rstrip",
"(",
"\".\"",
")"
] | [
117,
4
] | [
133,
41
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection.host | (self, value) |
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
|
Setter for the `host` property. | def host(self, value):
"""
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
"""
self._dns_host = value | [
"def",
"host",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_dns_host",
"=",
"value"
] | [
136,
4
] | [
143,
30
] | python | en | ['en', 'error', 'th'] | False |
HTTPConnection._new_conn | (self) | Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
| Establish a socket connection and set nodelay settings on it. | def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw["source_address"] = self.source_address
if self.socket_options:
extra_kw["so... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"extra_kw",
"=",
"{",
"}",
"if",
"self",
".",
"source_address",
":",
"extra_kw",
"[",
"\"source_address\"",
"]",
"=",
"self",
".",
"source_address",
"if",
"self",
".",
"socket_options",
":",
"extra_kw",
"[",
"\"so... | [
145,
4
] | [
174,
19
] | python | en | ['en', 'st', 'en'] | True |
HTTPConnection.putrequest | (self, method, url, *args, **kwargs) | Send a request to the server | Send a request to the server | def putrequest(self, method, url, *args, **kwargs):
"""Send a request to the server"""
match = _CONTAINS_CONTROL_CHAR_RE.search(method)
if match:
raise ValueError(
"Method cannot contain non-token characters %r (found at least %r)"
% (method, match.gro... | [
"def",
"putrequest",
"(",
"self",
",",
"method",
",",
"url",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"match",
"=",
"_CONTAINS_CONTROL_CHAR_RE",
".",
"search",
"(",
"method",
")",
"if",
"match",
":",
"raise",
"ValueError",
"(",
"\"Method cann... | [
189,
4
] | [
198,
77
] | python | en | ['en', 'en', 'en'] | True |
HTTPConnection.request_chunked | (self, method, url, body=None, headers=None) |
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
|
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
| def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = HTTPHeaderDict(headers if headers is not None else {})
skip_accept_encoding = "acce... | [
"def",
"request_chunked",
"(",
"self",
",",
"method",
",",
"url",
",",
"body",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"headers",
"=",
"HTTPHeaderDict",
"(",
"headers",
"if",
"headers",
"is",
"not",
"None",
"else",
"{",
"}",
")",
"skip_acce... | [
200,
4
] | [
233,
31
] | python | en | ['en', 'error', 'th'] | False |
HTTPSConnection.set_cert | (
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
ca_cert_data=None,
) |
This method should only be called once, before the connection is used.
|
This method should only be called once, before the connection is used.
| def set_cert(
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
ca_cert_data=None,
):
"""
This method should only be c... | [
"def",
"set_cert",
"(",
"self",
",",
"key_file",
"=",
"None",
",",
"cert_file",
"=",
"None",
",",
"cert_reqs",
"=",
"None",
",",
"key_password",
"=",
"None",
",",
"ca_certs",
"=",
"None",
",",
"assert_hostname",
"=",
"None",
",",
"assert_fingerprint",
"=",... | [
272,
4
] | [
303,
40
] | python | en | ['en', 'error', 'th'] | False |
wrapper_warning | () |
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="probs".
Using "probs" as any part of the attack interface is dangerous.
We can't just change output_layer to logits because... |
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="probs".
Using "probs" as any part of the attack interface is dangerous.
We can't just change output_layer to logits because... | def wrapper_warning():
"""
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="probs".
Using "probs" as any part of the attack interface is dangerous.
We can't just change ... | [
"def",
"wrapper_warning",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Passing a callable is deprecated, because using\"",
"\" probabilities is dangerous. It has a high risk \"",
"\" of causing gradient masking due to loss of precision \"",
"\" in the softmax op. Passing a callable rather... | [
255,
0
] | [
278,
5
] | python | en | ['en', 'error', 'th'] | False |
wrapper_warning_logits | () |
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="logits".
This is dangerous because it is under-the-hood automagic that the user
may not realize has been invoked for them. ... |
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="logits".
This is dangerous because it is under-the-hood automagic that the user
may not realize has been invoked for them. ... | def wrapper_warning_logits():
"""
Issue a deprecation warning. Used in multiple places that implemented
attacks by automatically wrapping a user-supplied callable with a
CallableModelWrapper with output_layer="logits".
This is dangerous because it is under-the-hood automagic that the user
may no... | [
"def",
"wrapper_warning_logits",
"(",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Passing a callable is deprecated, because it runs the \"",
"\"risk of accidentally using probabilities in the place \"",
"\"of logits. Please switch to passing a Model subclass \"",
"\"so that you clearly specif... | [
281,
0
] | [
299,
5
] | python | en | ['en', 'error', 'th'] | False |
Model.__init__ | (
self, scope=None, nb_classes=None, hparams=None, needs_dummy_fprop=False
) |
Constructor.
:param scope: str, the name of model.
:param nb_classes: integer, the number of classes.
:param hparams: dict, hyper-parameters for the model.
:needs_dummy_fprop: bool, if True the model's parameters are not
created until fprop is called.
|
Constructor.
:param scope: str, the name of model.
:param nb_classes: integer, the number of classes.
:param hparams: dict, hyper-parameters for the model.
:needs_dummy_fprop: bool, if True the model's parameters are not
created until fprop is called.
| def __init__(
self, scope=None, nb_classes=None, hparams=None, needs_dummy_fprop=False
):
"""
Constructor.
:param scope: str, the name of model.
:param nb_classes: integer, the number of classes.
:param hparams: dict, hyper-parameters for the model.
:needs_dum... | [
"def",
"__init__",
"(",
"self",
",",
"scope",
"=",
"None",
",",
"nb_classes",
"=",
"None",
",",
"hparams",
"=",
"None",
",",
"needs_dummy_fprop",
"=",
"False",
")",
":",
"self",
".",
"scope",
"=",
"scope",
"or",
"self",
".",
"__class__",
".",
"__name__... | [
23,
4
] | [
37,
50
] | python | en | ['en', 'error', 'th'] | False |
Model.__call__ | (self, *args, **kwargs) |
For compatibility with functions used as model definitions (taking
an input tensor and returning the tensor giving the output
of the model on that input).
|
For compatibility with functions used as model definitions (taking
an input tensor and returning the tensor giving the output
of the model on that input).
| def __call__(self, *args, **kwargs):
"""
For compatibility with functions used as model definitions (taking
an input tensor and returning the tensor giving the output
of the model on that input).
"""
warnings.warn(
"Model.__call__ is deprecated. "
... | [
"def",
"__call__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Model.__call__ is deprecated. \"",
"\"The call is ambiguous as to whether the output should \"",
"\"be logits or probabilities, and getting the wrong one \"",
... | [
39,
4
] | [
60,
46
] | python | en | ['en', 'error', 'th'] | False |
Model.get_logits | (self, x, **kwargs) |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
|
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
| def get_logits(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output logits
(i.e., the values fed as inputs to the softmax layer).
"""
outputs = self.fprop(x, **kwargs)
i... | [
"def",
"get_logits",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"outputs",
"=",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"O_LOGITS",
"in",
"outputs",
":",
"return",
"outputs",
"[",
"self",
".... | [
62,
4
] | [
74,
9
] | python | en | ['en', 'error', 'th'] | False |
Model.get_predicted_class | (self, x, **kwargs) |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
|
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
| def get_predicted_class(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the predicted label
"""
return tf.argmax(self.get_logits(x, **kwargs), axis=1) | [
"def",
"get_predicted_class",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tf",
".",
"argmax",
"(",
"self",
".",
"get_logits",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
",",
"axis",
"=",
"1",
")"
] | [
76,
4
] | [
81,
62
] | python | en | ['en', 'error', 'th'] | False |
Model.get_probs | (self, x, **kwargs) |
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
|
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
| def get_probs(self, x, **kwargs):
"""
:param x: A symbolic representation (Tensor) of the network input
:return: A symbolic representation (Tensor) of the output
probabilities (i.e., the output values produced by the softmax layer).
"""
d = self.fprop(x, **kwargs)
... | [
"def",
"get_probs",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"if",
"self",
".",
"O_PROBS",
"in",
"d",
":",
"output",
"=",
"d",
"[",
"self",
".",
"O_PROBS... | [
83,
4
] | [
104,
60
] | python | en | ['en', 'error', 'th'] | False |
Model.fprop | (self, x, **kwargs) |
Forward propagation to compute the model outputs.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
|
Forward propagation to compute the model outputs.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
| def fprop(self, x, **kwargs):
"""
Forward propagation to compute the model outputs.
:param x: A symbolic representation of the network input
:return: A dictionary mapping layer names to the symbolic
representation of their output.
"""
raise NotImplemented... | [
"def",
"fprop",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"`fprop` not implemented.\"",
")"
] | [
106,
4
] | [
113,
61
] | python | en | ['en', 'error', 'th'] | False |
Model.get_params | (self) |
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
|
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
| def get_params(self):
"""
Provides access to the model's parameters.
:return: A list of all Variables defining the model parameters.
"""
if hasattr(self, "params"):
return list(self.params)
# Catch eager execution and assert function overload.
try:
... | [
"def",
"get_params",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"params\"",
")",
":",
"return",
"list",
"(",
"self",
".",
"params",
")",
"# Catch eager execution and assert function overload.",
"try",
":",
"if",
"tf",
".",
"executing_eagerly",
... | [
115,
4
] | [
157,
25
] | python | en | ['en', 'error', 'th'] | False |
Model.make_params | (self) |
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
|
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
| def make_params(self):
"""
Create all Variables to be returned later by get_params.
By default this is a no-op.
Models that need their fprop to be called for their params to be
created can set `needs_dummy_fprop=True` in the constructor.
"""
if self.needs_dummy_f... | [
"def",
"make_params",
"(",
"self",
")",
":",
"if",
"self",
".",
"needs_dummy_fprop",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"_dummy_input\"",
")",
":",
"return",
"self",
".",
"_dummy_input",
"=",
"self",
".",
"make_input_placeholder",
"(",
")",
"self",
... | [
159,
4
] | [
171,
41
] | python | en | ['en', 'error', 'th'] | False |
Model.get_layer_names | (self) | Return the list of exposed layers for this model. | Return the list of exposed layers for this model. | def get_layer_names(self):
"""Return the list of exposed layers for this model."""
raise NotImplementedError | [
"def",
"get_layer_names",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | [
173,
4
] | [
175,
33
] | python | en | ['en', 'en', 'en'] | True |
Model.get_layer | (self, x, layer, **kwargs) | Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
| Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
| def get_layer(self, x, layer, **kwargs):
"""Return a layer output.
:param x: tensor, the input to the network.
:param layer: str, the name of the layer to compute.
:param **kwargs: dict, extra optional params to pass to self.fprop.
:return: the content of layer `layer`
""... | [
"def",
"get_layer",
"(",
"self",
",",
"x",
",",
"layer",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"fprop",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
"[",
"layer",
"]"
] | [
177,
4
] | [
184,
45
] | python | en | ['es', 'en', 'en'] | True |
Model.make_input_placeholder | (self) | Create and return a placeholder representing an input to the model.
This method should respect context managers (e.g. "with tf.device")
and should not just return a reference to a single pre-created
placeholder.
| Create and return a placeholder representing an input to the model. | def make_input_placeholder(self):
"""Create and return a placeholder representing an input to the model.
This method should respect context managers (e.g. "with tf.device")
and should not just return a reference to a single pre-created
placeholder.
"""
raise NotImplemen... | [
"def",
"make_input_placeholder",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"str",
"(",
"type",
"(",
"self",
")",
")",
"+",
"\" does not implement \"",
"\"make_input_placeholder\"",
")"
] | [
186,
4
] | [
196,
9
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.