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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
default_test_processes | () | Default number of test processes when using the --parallel option. | Default number of test processes when using the --parallel option. | def default_test_processes():
"""Default number of test processes when using the --parallel option."""
# The current implementation of the parallel test runner requires
# multiprocessing to start subprocesses with fork().
if multiprocessing.get_start_method() != 'fork':
return 1
try:
... | [
"def",
"default_test_processes",
"(",
")",
":",
"# The current implementation of the parallel test runner requires",
"# multiprocessing to start subprocesses with fork().",
"if",
"multiprocessing",
".",
"get_start_method",
"(",
")",
"!=",
"'fork'",
":",
"return",
"1",
"try",
":... | [
285,
0
] | [
294,
42
] | python | en | ['en', 'en', 'en'] | True |
_init_worker | (counter) |
Switch to databases dedicated to this worker.
This helper lives at module-level because of the multiprocessing module's
requirements.
|
Switch to databases dedicated to this worker. | def _init_worker(counter):
"""
Switch to databases dedicated to this worker.
This helper lives at module-level because of the multiprocessing module's
requirements.
"""
global _worker_id
with counter.get_lock():
counter.value += 1
_worker_id = counter.value
for alias ... | [
"def",
"_init_worker",
"(",
"counter",
")",
":",
"global",
"_worker_id",
"with",
"counter",
".",
"get_lock",
"(",
")",
":",
"counter",
".",
"value",
"+=",
"1",
"_worker_id",
"=",
"counter",
".",
"value",
"for",
"alias",
"in",
"connections",
":",
"connectio... | [
300,
0
] | [
322,
26
] | python | en | ['en', 'error', 'th'] | False |
_run_subsuite | (args) |
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
|
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. | def _run_subsuite(args):
"""
Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult.
This helper lives at module-level and its arguments are wrapped in a tuple
because of the multiprocessing module's requirements.
"""
runner_class, subsuite_index, subsuite, failfast = args
... | [
"def",
"_run_subsuite",
"(",
"args",
")",
":",
"runner_class",
",",
"subsuite_index",
",",
"subsuite",
",",
"failfast",
"=",
"args",
"runner",
"=",
"runner_class",
"(",
"failfast",
"=",
"failfast",
")",
"result",
"=",
"runner",
".",
"run",
"(",
"subsuite",
... | [
325,
0
] | [
335,
40
] | python | en | ['en', 'error', 'th'] | False |
is_discoverable | (label) |
Check if a test label points to a Python package or file directory.
Relative labels like "." and ".." are seen as directories.
|
Check if a test label points to a Python package or file directory. | def is_discoverable(label):
"""
Check if a test label points to a Python package or file directory.
Relative labels like "." and ".." are seen as directories.
"""
try:
mod = import_module(label)
except (ImportError, TypeError):
pass
else:
return hasattr(mod, '__path_... | [
"def",
"is_discoverable",
"(",
"label",
")",
":",
"try",
":",
"mod",
"=",
"import_module",
"(",
"label",
")",
"except",
"(",
"ImportError",
",",
"TypeError",
")",
":",
"pass",
"else",
":",
"return",
"hasattr",
"(",
"mod",
",",
"'__path__'",
")",
"return"... | [
703,
0
] | [
716,
48
] | python | en | ['en', 'error', 'th'] | False |
reorder_suite | (suite, classes, reverse=False) |
Reorder a test suite by test type.
`classes` is a sequence of types
All tests of type classes[0] are placed first, then tests of type
classes[1], etc. Tests with no match in classes are placed last.
If `reverse` is True, sort tests within classes in opposite order but
don't reverse test clas... |
Reorder a test suite by test type. | def reorder_suite(suite, classes, reverse=False):
"""
Reorder a test suite by test type.
`classes` is a sequence of types
All tests of type classes[0] are placed first, then tests of type
classes[1], etc. Tests with no match in classes are placed last.
If `reverse` is True, sort tests within ... | [
"def",
"reorder_suite",
"(",
"suite",
",",
"classes",
",",
"reverse",
"=",
"False",
")",
":",
"class_count",
"=",
"len",
"(",
"classes",
")",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"bins",
"=",
"[",
"OrderedSet",
"(",
")",
"for",
"i",
"in",
"... | [
719,
0
] | [
738,
26
] | python | en | ['en', 'error', 'th'] | False |
partition_suite_by_type | (suite, classes, bins, reverse=False) |
Partition a test suite by test type. Also prevent duplicated tests.
classes is a sequence of types
bins is a sequence of TestSuites, one more than classes
reverse changes the ordering of tests within bins
Tests of type classes[i] are added to bins[i],
tests with no match found in classes are ... |
Partition a test suite by test type. Also prevent duplicated tests. | def partition_suite_by_type(suite, classes, bins, reverse=False):
"""
Partition a test suite by test type. Also prevent duplicated tests.
classes is a sequence of types
bins is a sequence of TestSuites, one more than classes
reverse changes the ordering of tests within bins
Tests of type class... | [
"def",
"partition_suite_by_type",
"(",
"suite",
",",
"classes",
",",
"bins",
",",
"reverse",
"=",
"False",
")",
":",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"if",
"reverse",
":",
"suite",
"=",
"reversed",
"(",
"tuple",
"(",
"suite",
")",
")",
"f... | [
741,
0
] | [
764,
34
] | python | en | ['en', 'error', 'th'] | False |
partition_suite_by_case | (suite) | Partition a test suite by test case, preserving the order of tests. | Partition a test suite by test case, preserving the order of tests. | def partition_suite_by_case(suite):
"""Partition a test suite by test case, preserving the order of tests."""
groups = []
suite_class = type(suite)
for test_type, test_group in itertools.groupby(suite, type):
if issubclass(test_type, unittest.TestCase):
groups.append(suite_class(test... | [
"def",
"partition_suite_by_case",
"(",
"suite",
")",
":",
"groups",
"=",
"[",
"]",
"suite_class",
"=",
"type",
"(",
"suite",
")",
"for",
"test_type",
",",
"test_group",
"in",
"itertools",
".",
"groupby",
"(",
"suite",
",",
"type",
")",
":",
"if",
"issubc... | [
767,
0
] | [
777,
17
] | python | en | ['en', 'en', 'en'] | True |
RemoteTestResult._confirm_picklable | (self, obj) |
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
|
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
| def _confirm_picklable(self, obj):
"""
Confirm that obj can be pickled and unpickled as multiprocessing will
need to pickle the exception in the child process and unpickle it in
the parent process. Let the exception rise, if not.
"""
pickle.loads(pickle.dumps(obj)) | [
"def",
"_confirm_picklable",
"(",
"self",
",",
"obj",
")",
":",
"pickle",
".",
"loads",
"(",
"pickle",
".",
"dumps",
"(",
"obj",
")",
")"
] | [
123,
4
] | [
129,
39
] | python | en | ['en', 'error', 'th'] | False |
ParallelTestSuite.run | (self, result) |
Distribute test cases across workers.
Return an identifier of each test case with its result in order to use
imap_unordered to show results as soon as they're available.
To minimize pickling errors when getting results from workers:
- pass back numeric indexes in self.subsuit... |
Distribute test cases across workers. | def run(self, result):
"""
Distribute test cases across workers.
Return an identifier of each test case with its result in order to use
imap_unordered to show results as soon as they're available.
To minimize pickling errors when getting results from workers:
- pass ba... | [
"def",
"run",
"(",
"self",
",",
"result",
")",
":",
"counter",
"=",
"multiprocessing",
".",
"Value",
"(",
"ctypes",
".",
"c_int",
",",
"0",
")",
"pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"processes",
"=",
"self",
".",
"processes",
",",
"initial... | [
365,
4
] | [
417,
21
] | python | en | ['en', 'error', 'th'] | False |
DiscoverRunner.teardown_databases | (self, old_config, **kwargs) | Destroy all the non-mirror databases. | Destroy all the non-mirror databases. | def teardown_databases(self, old_config, **kwargs):
"""Destroy all the non-mirror databases."""
_teardown_databases(
old_config,
verbosity=self.verbosity,
parallel=self.parallel,
keepdb=self.keepdb,
) | [
"def",
"teardown_databases",
"(",
"self",
",",
"old_config",
",",
"*",
"*",
"kwargs",
")",
":",
"_teardown_databases",
"(",
"old_config",
",",
"verbosity",
"=",
"self",
".",
"verbosity",
",",
"parallel",
"=",
"self",
".",
"parallel",
",",
"keepdb",
"=",
"s... | [
631,
4
] | [
638,
9
] | python | en | ['en', 'en', 'en'] | True |
DiscoverRunner.run_tests | (self, test_labels, extra_tests=None, **kwargs) |
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
A list of 'extra' tests may also be provided; these tests
will be added to the test suite.
Return the number of t... |
Run the unit tests for all the test labels in the provided list. | def run_tests(self, test_labels, extra_tests=None, **kwargs):
"""
Run the unit tests for all the test labels in the provided list.
Test labels should be dotted Python paths to test modules, test
classes, or test methods.
A list of 'extra' tests may also be provided; these tests... | [
"def",
"run_tests",
"(",
"self",
",",
"test_labels",
",",
"extra_tests",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"setup_test_environment",
"(",
")",
"suite",
"=",
"self",
".",
"build_suite",
"(",
"test_labels",
",",
"extra_tests",
")",... | [
668,
4
] | [
700,
47
] | python | en | ['en', 'error', 'th'] | False |
get_extract_command_template | (filename) | Returns extraction command based on the filename extension. | Returns extraction command based on the filename extension. | def get_extract_command_template(filename):
"""Returns extraction command based on the filename extension."""
for k, v in iteritems(EXTRACT_COMMAND):
if filename.endswith(k):
return v
return None | [
"def",
"get_extract_command_template",
"(",
"filename",
")",
":",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"EXTRACT_COMMAND",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"k",
")",
":",
"return",
"v",
"return",
"None"
] | [
43,
0
] | [
48,
15
] | python | en | ['en', 'en', 'en'] | True |
shell_call | (command, **kwargs) | Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call(['cp', '${A}', '${B}'], A='src_file', B='ds... | Calls shell command with parameter substitution. | def shell_call(command, **kwargs):
"""Calls shell command with parameter substitution.
Args:
command: command to run as a list of tokens
**kwargs: dirctionary with substitutions
Returns:
whether command was successful, i.e. returned 0 status code
Example of usage:
shell_call([... | [
"def",
"shell_call",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"command",
"=",
"list",
"(",
"command",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"command",
")",
")",
":",
"m",
"=",
"CMD_VARIABLE_RE",
".",
"match",
"(",
"command",
"[... | [
51,
0
] | [
73,
40
] | python | en | ['en', 'en', 'en'] | True |
make_directory_writable | (dirname) | Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user with restricted permissions.
So to be abl... | Makes directory readable and writable by everybody. | def make_directory_writable(dirname):
"""Makes directory readable and writable by everybody.
Args:
dirname: name of the directory
Returns:
True if operation was successfull
If you run something inside Docker container and it writes files, then
these files will be written as root user ... | [
"def",
"make_directory_writable",
"(",
"dirname",
")",
":",
"retval",
"=",
"shell_call",
"(",
"[",
"\"docker\"",
",",
"\"run\"",
",",
"\"-v\"",
",",
"\"{0}:/output_dir\"",
".",
"format",
"(",
"dirname",
")",
",",
"\"busybox:1.27.2\"",
",",
"\"chmod\"",
",",
"\... | [
76,
0
] | [
105,
17
] | python | en | ['en', 'en', 'en'] | True |
load_defense_output | (filename) | Loads output of defense from given file. | Loads output of defense from given file. | def load_defense_output(filename):
"""Loads output of defense from given file."""
result = {}
with open(filename) as f:
for row in csv.reader(f):
try:
image_filename = row[0]
if not image_filename.endswith(".png"):
image_filename += ".p... | [
"def",
"load_defense_output",
"(",
"filename",
")",
":",
"result",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"for",
"row",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
":",
"try",
":",
"image_filename",
"=",
"row",
"[",
"0"... | [
108,
0
] | [
121,
17
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator.__init__ | (self, temp_dir, use_gpu) | Initializes instance of SubmissionValidator.
Args:
temp_dir: temporary working directory
use_gpu: whether to use GPU
| Initializes instance of SubmissionValidator. | def __init__(self, temp_dir, use_gpu):
"""Initializes instance of SubmissionValidator.
Args:
temp_dir: temporary working directory
use_gpu: whether to use GPU
"""
self._temp_dir = temp_dir
self._use_gpu = use_gpu
self._tmp_extracted_dir = os.path.join... | [
"def",
"__init__",
"(",
"self",
",",
"temp_dir",
",",
"use_gpu",
")",
":",
"self",
".",
"_temp_dir",
"=",
"temp_dir",
"self",
".",
"_use_gpu",
"=",
"use_gpu",
"self",
".",
"_tmp_extracted_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_t... | [
127,
4
] | [
139,
72
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._prepare_temp_dir | (self) | Cleans up and prepare temporary directory. | Cleans up and prepare temporary directory. | def _prepare_temp_dir(self):
"""Cleans up and prepare temporary directory."""
if not shell_call(["sudo", "rm", "-rf", os.path.join(self._temp_dir, "*")]):
logging.error("Failed to cleanup temporary directory.")
sys.exit(1)
# NOTE: we do not create self._extracted_submissi... | [
"def",
"_prepare_temp_dir",
"(",
"self",
")",
":",
"if",
"not",
"shell_call",
"(",
"[",
"\"sudo\"",
",",
"\"rm\"",
",",
"\"-rf\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_dir",
",",
"\"*\"",
")",
"]",
")",
":",
"logging",
".",
... | [
141,
4
] | [
153,
69
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._extract_submission | (self, filename) | Extracts submission and moves it into self._extracted_submission_dir. | Extracts submission and moves it into self._extracted_submission_dir. | def _extract_submission(self, filename):
"""Extracts submission and moves it into self._extracted_submission_dir."""
# verify filesize
file_size = os.path.getsize(filename)
if file_size > MAX_SUBMISSION_SIZE_ZIPPED:
logging.error(
"Submission archive size %d i... | [
"def",
"_extract_submission",
"(",
"self",
",",
"filename",
")",
":",
"# verify filesize",
"file_size",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"filename",
")",
"if",
"file_size",
">",
"MAX_SUBMISSION_SIZE_ZIPPED",
":",
"logging",
".",
"error",
"(",
"\"Su... | [
155,
4
] | [
216,
19
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._load_and_verify_metadata | (self) | Loads and verifies metadata.
Returns:
dictionaty with metadata or None if metadata not found or invalid
| Loads and verifies metadata. | def _load_and_verify_metadata(self):
"""Loads and verifies metadata.
Returns:
dictionaty with metadata or None if metadata not found or invalid
"""
metadata_filename = os.path.join(
self._extracted_submission_dir, "metadata.json"
)
if not os.path.is... | [
"def",
"_load_and_verify_metadata",
"(",
"self",
")",
":",
"metadata_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_extracted_submission_dir",
",",
"\"metadata.json\"",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"metadata_fil... | [
230,
4
] | [
272,
23
] | python | en | ['en', 'mi', 'en'] | True |
SubmissionValidator._verify_docker_image_size | (self, image_name) | Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
| Verifies size of Docker image. | def _verify_docker_image_size(self, image_name):
"""Verifies size of Docker image.
Args:
image_name: name of the Docker image.
Returns:
True if image size is within the limits, False otherwise.
"""
shell_call(["docker", "pull", image_name])
try:
... | [
"def",
"_verify_docker_image_size",
"(",
"self",
",",
"image_name",
")",
":",
"shell_call",
"(",
"[",
"\"docker\"",
",",
"\"pull\"",
",",
"image_name",
"]",
")",
"try",
":",
"image_size",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"docker\"",
",",
"... | [
274,
4
] | [
295,
50
] | python | en | ['en', 'jv', 'en'] | True |
SubmissionValidator._prepare_sample_data | (self, submission_type) | Prepares sample data for the submission.
Args:
submission_type: type of the submission.
| Prepares sample data for the submission. | def _prepare_sample_data(self, submission_type):
"""Prepares sample data for the submission.
Args:
submission_type: type of the submission.
"""
# write images
images = np.random.randint(
0, 256, size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8
)
... | [
"def",
"_prepare_sample_data",
"(",
"self",
",",
"submission_type",
")",
":",
"# write images",
"images",
"=",
"np",
".",
"random",
".",
"randint",
"(",
"0",
",",
"256",
",",
"size",
"=",
"[",
"BATCH_SIZE",
",",
"299",
",",
"299",
",",
"3",
"]",
",",
... | [
297,
4
] | [
321,
21
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._run_submission | (self, metadata) | Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
| Runs submission inside Docker container. | def _run_submission(self, metadata):
"""Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
"""
container_name = (
... | [
"def",
"_run_submission",
"(",
"self",
",",
"metadata",
")",
":",
"container_name",
"=",
"(",
"metadata",
"[",
"\"container_gpu\"",
"]",
"if",
"self",
".",
"_use_gpu",
"else",
"metadata",
"[",
"\"container\"",
"]",
")",
"if",
"metadata",
"[",
"\"type\"",
"]"... | [
323,
4
] | [
380,
21
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator._verify_output | (self, submission_type) | Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid
| Verifies correctness of the submission output. | def _verify_output(self, submission_type):
"""Verifies correctness of the submission output.
Args:
submission_type: type of the submission
Returns:
True if output looks valid
"""
result = True
if submission_type == "defense":
try:
... | [
"def",
"_verify_output",
"(",
"self",
",",
"submission_type",
")",
":",
"result",
"=",
"True",
"if",
"submission_type",
"==",
"\"defense\"",
":",
"try",
":",
"image_classification",
"=",
"load_defense_output",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | [
382,
4
] | [
422,
21
] | python | en | ['en', 'en', 'en'] | True |
SubmissionValidator.validate_submission | (self, filename) | Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid
| Validates submission. | def validate_submission(self, filename):
"""Validates submission.
Args:
filename: submission filename
Returns:
submission metadata or None if submission is invalid
"""
self._prepare_temp_dir()
# Convert filename to be absolute path, relative path mig... | [
"def",
"validate_submission",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"_prepare_temp_dir",
"(",
")",
"# Convert filename to be absolute path, relative path might cause problems",
"# with mounting directory in Docker",
"filename",
"=",
"os",
".",
"path",
".",
"a... | [
424,
4
] | [
462,
23
] | python | en | ['fr', 'la', 'en'] | False |
sentence | () |
Returns a randomly generated sentence of lorem ipsum text.
The first word is capitalized, and the sentence ends in either a period or
question mark. Commas are added at random.
|
Returns a randomly generated sentence of lorem ipsum text. | def sentence():
"""
Returns a randomly generated sentence of lorem ipsum text.
The first word is capitalized, and the sentence ends in either a period or
question mark. Commas are added at random.
"""
# Determine the number of comma-separated sections and number of words in
# each section f... | [
"def",
"sentence",
"(",
")",
":",
"# Determine the number of comma-separated sections and number of words in",
"# each section for this sentence.",
"sections",
"=",
"[",
"' '",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"WORDS",
",",
"random",
".",
"randint",
"(",
... | [
53,
0
] | [
65,
64
] | python | en | ['en', 'error', 'th'] | False |
paragraph | () |
Returns a randomly generated paragraph of lorem ipsum text.
The paragraph consists of between 1 and 4 sentences, inclusive.
|
Returns a randomly generated paragraph of lorem ipsum text. | def paragraph():
"""
Returns a randomly generated paragraph of lorem ipsum text.
The paragraph consists of between 1 and 4 sentences, inclusive.
"""
return ' '.join(sentence() for i in range(random.randint(1, 4))) | [
"def",
"paragraph",
"(",
")",
":",
"return",
"' '",
".",
"join",
"(",
"sentence",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"random",
".",
"randint",
"(",
"1",
",",
"4",
")",
")",
")"
] | [
68,
0
] | [
74,
68
] | python | en | ['en', 'error', 'th'] | False |
paragraphs | (count, common=True) |
Returns a list of paragraphs as returned by paragraph().
If `common` is True, then the first paragraph will be the standard
'lorem ipsum' paragraph. Otherwise, the first paragraph will be random
Latin text. Either way, subsequent paragraphs will be random Latin text.
|
Returns a list of paragraphs as returned by paragraph(). | def paragraphs(count, common=True):
"""
Returns a list of paragraphs as returned by paragraph().
If `common` is True, then the first paragraph will be the standard
'lorem ipsum' paragraph. Otherwise, the first paragraph will be random
Latin text. Either way, subsequent paragraphs will be random Lat... | [
"def",
"paragraphs",
"(",
"count",
",",
"common",
"=",
"True",
")",
":",
"paras",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"if",
"common",
"and",
"i",
"==",
"0",
":",
"paras",
".",
"append",
"(",
"COMMON_P",
")",
"else",
... | [
77,
0
] | [
91,
16
] | python | en | ['en', 'error', 'th'] | False |
words | (count, common=True) |
Returns a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
'lorem ipsum' words. Otherwise, all words will be selected randomly.
|
Returns a string of `count` lorem ipsum words separated by a single space. | def words(count, common=True):
"""
Returns a string of `count` lorem ipsum words separated by a single space.
If `common` is True, then the first 19 words will be the standard
'lorem ipsum' words. Otherwise, all words will be selected randomly.
"""
if common:
word_list = list(COMMON_WOR... | [
"def",
"words",
"(",
"count",
",",
"common",
"=",
"True",
")",
":",
"if",
"common",
":",
"word_list",
"=",
"list",
"(",
"COMMON_WORDS",
")",
"else",
":",
"word_list",
"=",
"[",
"]",
"c",
"=",
"len",
"(",
"word_list",
")",
"if",
"count",
">",
"c",
... | [
94,
0
] | [
114,
30
] | python | en | ['en', 'error', 'th'] | False |
_route_to_regex | (route, is_endpoint=False) |
Convert a path pattern into a regular expression. Return the regular
expression and a dictionary mapping the capture names to the converters.
For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
and {'pk': <django.urls.converters.IntConverter>}.
|
Convert a path pattern into a regular expression. Return the regular
expression and a dictionary mapping the capture names to the converters.
For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
and {'pk': <django.urls.converters.IntConverter>}.
| def _route_to_regex(route, is_endpoint=False):
"""
Convert a path pattern into a regular expression. Return the regular
expression and a dictionary mapping the capture names to the converters.
For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)'
and {'pk': <django.urls.converters.IntConverter... | [
"def",
"_route_to_regex",
"(",
"route",
",",
"is_endpoint",
"=",
"False",
")",
":",
"if",
"not",
"set",
"(",
"route",
")",
".",
"isdisjoint",
"(",
"string",
".",
"whitespace",
")",
":",
"raise",
"ImproperlyConfigured",
"(",
"\"URL route '%s' cannot contain white... | [
203,
0
] | [
242,
37
] | python | en | ['en', 'error', 'th'] | False |
LocaleRegexDescriptor.__get__ | (self, instance, cls=None) |
Return a compiled regular expression based on the active language.
|
Return a compiled regular expression based on the active language.
| def __get__(self, instance, cls=None):
"""
Return a compiled regular expression based on the active language.
"""
if instance is None:
return self
# As a performance optimization, if the given regex string is a regular
# string (not a lazily-translated string ... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"# As a performance optimization, if the given regex string is a regular",
"# string (not a lazily-translated string proxy), compile it on... | [
92,
4
] | [
108,
50
] | python | en | ['en', 'error', 'th'] | False |
CheckURLMixin.describe | (self) |
Format the URL pattern for display in warning messages.
|
Format the URL pattern for display in warning messages.
| def describe(self):
"""
Format the URL pattern for display in warning messages.
"""
description = "'{}'".format(self)
if self.name:
description += " [name='{}']".format(self.name)
return description | [
"def",
"describe",
"(",
"self",
")",
":",
"description",
"=",
"\"'{}'\"",
".",
"format",
"(",
"self",
")",
"if",
"self",
".",
"name",
":",
"description",
"+=",
"\" [name='{}']\"",
".",
"format",
"(",
"self",
".",
"name",
")",
"return",
"description"
] | [
112,
4
] | [
119,
26
] | python | en | ['en', 'error', 'th'] | False |
CheckURLMixin._check_pattern_startswith_slash | (self) |
Check that the pattern does not begin with a forward slash.
|
Check that the pattern does not begin with a forward slash.
| def _check_pattern_startswith_slash(self):
"""
Check that the pattern does not begin with a forward slash.
"""
regex_pattern = self.regex.pattern
if not settings.APPEND_SLASH:
# Skip check as it can be useful to start a URL pattern with a slash
# when APPE... | [
"def",
"_check_pattern_startswith_slash",
"(",
"self",
")",
":",
"regex_pattern",
"=",
"self",
".",
"regex",
".",
"pattern",
"if",
"not",
"settings",
".",
"APPEND_SLASH",
":",
"# Skip check as it can be useful to start a URL pattern with a slash",
"# when APPEND_SLASH=False."... | [
121,
4
] | [
141,
21
] | python | en | ['en', 'error', 'th'] | False |
RegexPattern._compile | (self, regex) | Compile and return the given regular expression. | Compile and return the given regular expression. | def _compile(self, regex):
"""Compile and return the given regular expression."""
try:
return re.compile(regex)
except re.error as e:
raise ImproperlyConfigured(
'"%s" is not a valid regular expression: %s' % (regex, e)
) | [
"def",
"_compile",
"(",
"self",
",",
"regex",
")",
":",
"try",
":",
"return",
"re",
".",
"compile",
"(",
"regex",
")",
"except",
"re",
".",
"error",
"as",
"e",
":",
"raise",
"ImproperlyConfigured",
"(",
"'\"%s\" is not a valid regular expression: %s'",
"%",
... | [
185,
4
] | [
192,
13
] | python | en | ['en', 'en', 'en'] | True |
URLPattern._check_pattern_name | (self) |
Check that the pattern name does not contain a colon.
|
Check that the pattern name does not contain a colon.
| def _check_pattern_name(self):
"""
Check that the pattern name does not contain a colon.
"""
if self.pattern.name is not None and ":" in self.pattern.name:
warning = Warning(
"Your URL pattern {} has a name including a ':'. Remove the colon, to "
... | [
"def",
"_check_pattern_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"pattern",
".",
"name",
"is",
"not",
"None",
"and",
"\":\"",
"in",
"self",
".",
"pattern",
".",
"name",
":",
"warning",
"=",
"Warning",
"(",
"\"Your URL pattern {} has a name including a '... | [
337,
4
] | [
349,
21
] | python | en | ['en', 'error', 'th'] | False |
URLPattern.lookup_str | (self) |
A string that identifies the view (e.g. 'path.to.view_function' or
'path.to.ClassBasedView').
|
A string that identifies the view (e.g. 'path.to.view_function' or
'path.to.ClassBasedView').
| def lookup_str(self):
"""
A string that identifies the view (e.g. 'path.to.view_function' or
'path.to.ClassBasedView').
"""
callback = self.callback
if isinstance(callback, functools.partial):
callback = callback.func
if not hasattr(callback, '__name__... | [
"def",
"lookup_str",
"(",
"self",
")",
":",
"callback",
"=",
"self",
".",
"callback",
"if",
"isinstance",
"(",
"callback",
",",
"functools",
".",
"partial",
")",
":",
"callback",
"=",
"callback",
".",
"func",
"if",
"not",
"hasattr",
"(",
"callback",
",",... | [
360,
4
] | [
370,
64
] | python | en | ['en', 'error', 'th'] | False |
URLResolver._join_route | (route1, route2) | Join two routes, without the starting ^ in the second route. | Join two routes, without the starting ^ in the second route. | def _join_route(route1, route2):
"""Join two routes, without the starting ^ in the second route."""
if not route1:
return route2
if route2.startswith('^'):
route2 = route2[1:]
return route1 + route2 | [
"def",
"_join_route",
"(",
"route1",
",",
"route2",
")",
":",
"if",
"not",
"route1",
":",
"return",
"route2",
"if",
"route2",
".",
"startswith",
"(",
"'^'",
")",
":",
"route2",
"=",
"route2",
"[",
"1",
":",
"]",
"return",
"route1",
"+",
"route2"
] | [
524,
4
] | [
530,
30
] | python | en | ['en', 'en', 'en'] | True |
csrf_exempt | (view_func) | Mark a view function as being exempt from the CSRF view protection. | Mark a view function as being exempt from the CSRF view protection. | def csrf_exempt(view_func):
"""Mark a view function as being exempt from the CSRF view protection."""
# view_func.csrf_exempt = True would also work, but decorators are nicer
# if they don't have side effects, so return a new function.
def wrapped_view(*args, **kwargs):
return view_func(*args, *... | [
"def",
"csrf_exempt",
"(",
"view_func",
")",
":",
"# view_func.csrf_exempt = True would also work, but decorators are nicer",
"# if they don't have side effects, so return a new function.",
"def",
"wrapped_view",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
... | [
48,
0
] | [
55,
41
] | python | en | ['en', 'en', 'en'] | True |
bulk_create_users | (
realm: Realm,
users_raw: Set[Tuple[str, str, bool]],
bot_type: Optional[int] = None,
bot_owner: Optional[UserProfile] = None,
tos_version: Optional[str] = None,
timezone: str = "",
) |
Creates and saves a UserProfile with the given email.
Has some code based off of UserManage.create_user, but doesn't .save()
|
Creates and saves a UserProfile with the given email.
Has some code based off of UserManage.create_user, but doesn't .save()
| def bulk_create_users(
realm: Realm,
users_raw: Set[Tuple[str, str, bool]],
bot_type: Optional[int] = None,
bot_owner: Optional[UserProfile] = None,
tos_version: Optional[str] = None,
timezone: str = "",
) -> None:
"""
Creates and saves a UserProfile with the given email.
Has some co... | [
"def",
"bulk_create_users",
"(",
"realm",
":",
"Realm",
",",
"users_raw",
":",
"Set",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"bool",
"]",
"]",
",",
"bot_type",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"bot_owner",
":",
"Optional",
"[",... | [
10,
0
] | [
95,
61
] | python | en | ['en', 'error', 'th'] | False |
get_current_site | (request) |
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
|
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
| def get_current_site(request):
"""
Check if contrib.sites is installed and return either the current
``Site`` object or a ``RequestSite`` object based on the request.
"""
# Imports are inside the function because its point is to avoid importing
# the Site models when django.contrib.sites isn't i... | [
"def",
"get_current_site",
"(",
"request",
")",
":",
"# Imports are inside the function because its point is to avoid importing",
"# the Site models when django.contrib.sites isn't installed.",
"if",
"apps",
".",
"is_installed",
"(",
"'django.contrib.sites'",
")",
":",
"from",
".",... | [
3,
0
] | [
15,
35
] | python | en | ['en', 'error', 'th'] | False |
ArrayField.get_default | (self) | Overridden from the default to prevent string-mangling. | Overridden from the default to prevent string-mangling. | def get_default(self):
"""Overridden from the default to prevent string-mangling."""
if self.has_default():
if callable(self.default):
return self.default()
return self.default
return '' | [
"def",
"get_default",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_default",
"(",
")",
":",
"if",
"callable",
"(",
"self",
".",
"default",
")",
":",
"return",
"self",
".",
"default",
"(",
")",
"return",
"self",
".",
"default",
"return",
"''"
] | [
96,
4
] | [
102,
17
] | python | en | ['en', 'en', 'en'] | True |
build_ext.check_extensions_list | (self, extensions) | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.
... | Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here. | def check_extensions_list(self, extensions):
"""Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects. We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which ... | [
"def",
"check_extensions_list",
"(",
"self",
",",
"extensions",
")",
":",
"if",
"not",
"isinstance",
"(",
"extensions",
",",
"list",
")",
":",
"raise",
"DistutilsSetupError",
"(",
"\"'ext_modules' option must be a list of Extension instances\"",
")",
"for",
"i",
",",
... | [
341,
4
] | [
417,
31
] | python | en | ['en', 'en', 'en'] | True |
build_ext.swig_sources | (self, sources, extension) | Walk the list of source files in 'sources', looking for SWIG
interface (.i) files. Run SWIG on all that are found, and
return a modified 'sources' list with SWIG source files replaced
by the generated C (or C++) files.
| Walk the list of source files in 'sources', looking for SWIG
interface (.i) files. Run SWIG on all that are found, and
return a modified 'sources' list with SWIG source files replaced
by the generated C (or C++) files.
| def swig_sources(self, sources, extension):
"""Walk the list of source files in 'sources', looking for SWIG
interface (.i) files. Run SWIG on all that are found, and
return a modified 'sources' list with SWIG source files replaced
by the generated C (or C++) files.
"""
n... | [
"def",
"swig_sources",
"(",
"self",
",",
"sources",
",",
"extension",
")",
":",
"new_sources",
"=",
"[",
"]",
"swig_sources",
"=",
"[",
"]",
"swig_targets",
"=",
"{",
"}",
"# XXX this drops generated C/C++ files into the source tree, which",
"# is fine for developers wh... | [
561,
4
] | [
613,
26
] | python | en | ['en', 'en', 'en'] | True |
build_ext.find_swig | (self) | Return the name of the SWIG executable. On Unix, this is
just "swig" -- it should be in the PATH. Tries a bit harder on
Windows.
| Return the name of the SWIG executable. On Unix, this is
just "swig" -- it should be in the PATH. Tries a bit harder on
Windows.
| def find_swig(self):
"""Return the name of the SWIG executable. On Unix, this is
just "swig" -- it should be in the PATH. Tries a bit harder on
Windows.
"""
if os.name == "posix":
return "swig"
elif os.name == "nt":
# Look for SWIG in its standar... | [
"def",
"find_swig",
"(",
"self",
")",
":",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"return",
"\"swig\"",
"elif",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"# Look for SWIG in its standard installation directory on",
"# Windows (or so I presume!). If we find it t... | [
615,
4
] | [
635,
47
] | python | en | ['en', 'en', 'en'] | True |
build_ext.get_ext_fullpath | (self, ext_name) | Returns the path of the filename for a given extension.
The file is located in `build_lib` or directly in the package
(inplace option).
| Returns the path of the filename for a given extension. | def get_ext_fullpath(self, ext_name):
"""Returns the path of the filename for a given extension.
The file is located in `build_lib` or directly in the package
(inplace option).
"""
fullname = self.get_ext_fullname(ext_name)
modpath = fullname.split('.')
filename ... | [
"def",
"get_ext_fullpath",
"(",
"self",
",",
"ext_name",
")",
":",
"fullname",
"=",
"self",
".",
"get_ext_fullname",
"(",
"ext_name",
")",
"modpath",
"=",
"fullname",
".",
"split",
"(",
"'.'",
")",
"filename",
"=",
"self",
".",
"get_ext_filename",
"(",
"mo... | [
639,
4
] | [
664,
50
] | python | en | ['en', 'en', 'en'] | True |
build_ext.get_ext_fullname | (self, ext_name) | Returns the fullname of a given extension name.
Adds the `package.` prefix | Returns the fullname of a given extension name. | def get_ext_fullname(self, ext_name):
"""Returns the fullname of a given extension name.
Adds the `package.` prefix"""
if self.package is None:
return ext_name
else:
return self.package + '.' + ext_name | [
"def",
"get_ext_fullname",
"(",
"self",
",",
"ext_name",
")",
":",
"if",
"self",
".",
"package",
"is",
"None",
":",
"return",
"ext_name",
"else",
":",
"return",
"self",
".",
"package",
"+",
"'.'",
"+",
"ext_name"
] | [
666,
4
] | [
673,
48
] | python | en | ['en', 'en', 'en'] | True |
build_ext.get_ext_filename | (self, ext_name) | r"""Convert the name of an extension (eg. "foo.bar") into the name
of the file from which it will be loaded (eg. "foo/bar.so", or
"foo\bar.pyd").
| r"""Convert the name of an extension (eg. "foo.bar") into the name
of the file from which it will be loaded (eg. "foo/bar.so", or
"foo\bar.pyd").
| def get_ext_filename(self, ext_name):
r"""Convert the name of an extension (eg. "foo.bar") into the name
of the file from which it will be loaded (eg. "foo/bar.so", or
"foo\bar.pyd").
"""
from distutils.sysconfig import get_config_var
ext_path = ext_name.split('.')
... | [
"def",
"get_ext_filename",
"(",
"self",
",",
"ext_name",
")",
":",
"from",
"distutils",
".",
"sysconfig",
"import",
"get_config_var",
"ext_path",
"=",
"ext_name",
".",
"split",
"(",
"'.'",
")",
"ext_suffix",
"=",
"get_config_var",
"(",
"'EXT_SUFFIX'",
")",
"re... | [
675,
4
] | [
683,
51
] | python | en | ['en', 'en', 'en'] | True |
build_ext.get_export_symbols | (self, ext) | Return the list of symbols that a shared extension has to
export. This either uses 'ext.export_symbols' or, if it's not
provided, "PyInit_" + module_name. Only relevant on Windows, where
the .pyd file (DLL) must export the module "PyInit_" function.
| Return the list of symbols that a shared extension has to
export. This either uses 'ext.export_symbols' or, if it's not
provided, "PyInit_" + module_name. Only relevant on Windows, where
the .pyd file (DLL) must export the module "PyInit_" function.
| def get_export_symbols(self, ext):
"""Return the list of symbols that a shared extension has to
export. This either uses 'ext.export_symbols' or, if it's not
provided, "PyInit_" + module_name. Only relevant on Windows, where
the .pyd file (DLL) must export the module "PyInit_" function... | [
"def",
"get_export_symbols",
"(",
"self",
",",
"ext",
")",
":",
"suffix",
"=",
"'_'",
"+",
"ext",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"try",
":",
"# Unicode module name support as defined in PEP-489",
"# https://www.python.org/dev/pep... | [
685,
4
] | [
702,
33
] | python | en | ['en', 'en', 'en'] | True |
build_ext.get_libraries | (self, ext) | Return the list of libraries to link against when building a
shared extension. On most platforms, this is just 'ext.libraries';
on Windows, we add the Python library (eg. python20.dll).
| Return the list of libraries to link against when building a
shared extension. On most platforms, this is just 'ext.libraries';
on Windows, we add the Python library (eg. python20.dll).
| def get_libraries(self, ext):
"""Return the list of libraries to link against when building a
shared extension. On most platforms, this is just 'ext.libraries';
on Windows, we add the Python library (eg. python20.dll).
"""
# The python library is always needed on Windows. For M... | [
"def",
"get_libraries",
"(",
"self",
",",
"ext",
")",
":",
"# The python library is always needed on Windows. For MSVC, this",
"# is redundant, since the library is mentioned in a pragma in",
"# pyconfig.h that MSVC groks. The other Windows compilers all seem",
"# to need it mentioned explic... | [
704,
4
] | [
753,
28
] | python | en | ['en', 'en', 'en'] | True |
DatabaseIntrospection.get_table_list | (self, cursor) | Return a list of table and view names in the current database. | Return a list of table and view names in the current database. | def get_table_list(self, cursor):
"""Return a list of table and view names in the current database."""
cursor.execute("""
SELECT table_name, 't'
FROM user_tables
WHERE
NOT EXISTS (
SELECT 1
FROM user_mviews
... | [
"def",
"get_table_list",
"(",
"self",
",",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT table_name, 't'\n FROM user_tables\n WHERE\n NOT EXISTS (\n SELECT 1\n FROM user_mviews\n ... | [
69,
4
] | [
85,
98
] | python | en | ['en', 'en', 'en'] | True |
DatabaseIntrospection.get_table_description | (self, cursor, table_name) |
Return a description of the table with the DB-API cursor.description
interface.
|
Return a description of the table with the DB-API cursor.description
interface.
| def get_table_description(self, cursor, table_name):
"""
Return a description of the table with the DB-API cursor.description
interface.
"""
# user_tab_columns gives data default for columns
cursor.execute("""
SELECT
column_name,
... | [
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"# user_tab_columns gives data default for columns",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT\n column_name,\n data_default,\n CASE\n ... | [
87,
4
] | [
124,
26
] | python | en | ['en', 'error', 'th'] | False |
DatabaseIntrospection.identifier_converter | (self, name) | Identifier comparison is case insensitive under Oracle. | Identifier comparison is case insensitive under Oracle. | def identifier_converter(self, name):
"""Identifier comparison is case insensitive under Oracle."""
return name.lower() | [
"def",
"identifier_converter",
"(",
"self",
",",
"name",
")",
":",
"return",
"name",
".",
"lower",
"(",
")"
] | [
126,
4
] | [
128,
27
] | python | en | ['en', 'fr', 'en'] | True |
DatabaseIntrospection.get_relations | (self, cursor, table_name) |
Return a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
|
Return a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
| def get_relations(self, cursor, table_name):
"""
Return a dictionary of {field_name: (field_name_other_table, other_table)}
representing all relationships to the given table.
"""
table_name = table_name.upper()
cursor.execute("""
SELECT ca.column_name, cb.table_name, ... | [
"def",
"get_relations",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"table_name",
"=",
"table_name",
".",
"upper",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT ca.column_name, cb.table_name, cb.column_name\n FROM user_constraints, USER_CONS... | [
161,
4
] | [
180,
9
] | python | en | ['en', 'error', 'th'] | False |
DatabaseIntrospection.get_constraints | (self, cursor, table_name) |
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns.
|
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns.
| def get_constraints(self, cursor, table_name):
"""
Retrieve any constraints or keys (unique, pk, fk, check, index) across
one or more columns.
"""
constraints = {}
# Loop over the constraints, getting PKs, uniques, and checks
cursor.execute("""
SELECT
... | [
"def",
"get_constraints",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"constraints",
"=",
"{",
"}",
"# Loop over the constraints, getting PKs, uniques, and checks",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT\n user_constraints.constra... | [
212,
4
] | [
312,
26
] | python | en | ['en', 'error', 'th'] | False |
mark_safe | (s) |
Explicitly mark a string as safe for (HTML) output purposes. The returned
object can be used everywhere a string is appropriate.
If used on a method as a decorator, mark the returned data as safe.
Can be called multiple times on a single string.
|
Explicitly mark a string as safe for (HTML) output purposes. The returned
object can be used everywhere a string is appropriate. | def mark_safe(s):
"""
Explicitly mark a string as safe for (HTML) output purposes. The returned
object can be used everywhere a string is appropriate.
If used on a method as a decorator, mark the returned data as safe.
Can be called multiple times on a single string.
"""
if hasattr(s, '__h... | [
"def",
"mark_safe",
"(",
"s",
")",
":",
"if",
"hasattr",
"(",
"s",
",",
"'__html__'",
")",
":",
"return",
"s",
"if",
"callable",
"(",
"s",
")",
":",
"return",
"_safety_decorator",
"(",
"mark_safe",
",",
"s",
")",
"return",
"SafeString",
"(",
"s",
")"... | [
49,
0
] | [
62,
24
] | python | en | ['en', 'error', 'th'] | False |
SafeData.__html__ | (self) |
Return the html representation of a string for interoperability.
This allows other template engines to understand Django's SafeData.
|
Return the html representation of a string for interoperability. | def __html__(self):
"""
Return the html representation of a string for interoperability.
This allows other template engines to understand Django's SafeData.
"""
return self | [
"def",
"__html__",
"(",
"self",
")",
":",
"return",
"self"
] | [
11,
4
] | [
17,
19
] | python | en | ['en', 'error', 'th'] | False |
SafeString.__add__ | (self, rhs) |
Concatenating a safe string with another safe bytestring or
safe string is safe. Otherwise, the result is no longer safe.
|
Concatenating a safe string with another safe bytestring or
safe string is safe. Otherwise, the result is no longer safe.
| def __add__(self, rhs):
"""
Concatenating a safe string with another safe bytestring or
safe string is safe. Otherwise, the result is no longer safe.
"""
t = super().__add__(rhs)
if isinstance(rhs, SafeData):
return SafeString(t)
return t | [
"def",
"__add__",
"(",
"self",
",",
"rhs",
")",
":",
"t",
"=",
"super",
"(",
")",
".",
"__add__",
"(",
"rhs",
")",
"if",
"isinstance",
"(",
"rhs",
",",
"SafeData",
")",
":",
"return",
"SafeString",
"(",
"t",
")",
"return",
"t"
] | [
25,
4
] | [
33,
16
] | python | en | ['en', 'error', 'th'] | False |
DependencySource.get_root | (self, path: Path) | Determines package root if it has one.
Args:
path (Path): Path to check
Returns:
bool: True if is package
| Determines package root if it has one. | def get_root(self, path: Path) -> Optional[Path]:
"""Determines package root if it has one.
Args:
path (Path): Path to check
Returns:
bool: True if is package
"""
init = next(path.rglob("__init__.py"), None)
if init:
return init.pare... | [
"def",
"get_root",
"(",
"self",
",",
"path",
":",
"Path",
")",
"->",
"Optional",
"[",
"Path",
"]",
":",
"init",
"=",
"next",
"(",
"path",
".",
"rglob",
"(",
"\"__init__.py\"",
")",
",",
"None",
")",
"if",
"init",
":",
"return",
"init",
".",
"parent... | [
41,
4
] | [
54,
19
] | python | en | ['en', 'en', 'en'] | True |
DependencySource.generate_stubs | (self, path: Path) | Generate Stub Files from a package.
Args:
path (Path): Path to package.
Returns:
List[Tuple[Path, Path]]: List of tuples containing
a path to the original file and stub, respectively.
| Generate Stub Files from a package. | def generate_stubs(self, path: Path) -> List[Tuple[Path, Path]]:
"""Generate Stub Files from a package.
Args:
path (Path): Path to package.
Returns:
List[Tuple[Path, Path]]: List of tuples containing
a path to the original file and stub, respectively.
... | [
"def",
"generate_stubs",
"(",
"self",
",",
"path",
":",
"Path",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Path",
",",
"Path",
"]",
"]",
":",
"py_files",
"=",
"fileutils",
".",
"iter_find_files",
"(",
"str",
"(",
"path",
")",
",",
"patterns",
"=",
"\"*.p... | [
56,
4
] | [
69,
20
] | python | en | ['en', 'en', 'en'] | True |
DependencySource.__enter__ | (self) | Method to prepare source. | Method to prepare source. | def __enter__(self):
"""Method to prepare source.""" | [
"def",
"__enter__",
"(",
"self",
")",
":"
] | [
71,
4
] | [
72,
39
] | python | en | ['en', 'sr', 'en'] | True |
from_key | (api_key, **kwargs) | Returns an authenticated Heroku instance, via API Key. | Returns an authenticated Heroku instance, via API Key. | def from_key(api_key, **kwargs):
"""Returns an authenticated Heroku instance, via API Key."""
h = Heroku(**kwargs)
# Login.
h.authenticate(api_key)
return h | [
"def",
"from_key",
"(",
"api_key",
",",
"*",
"*",
"kwargs",
")",
":",
"h",
"=",
"Heroku",
"(",
"*",
"*",
"kwargs",
")",
"# Login.",
"h",
".",
"authenticate",
"(",
"api_key",
")",
"return",
"h"
] | [
11,
0
] | [
19,
12
] | python | en | ['en', 'haw', 'en'] | True |
from_pass | (username, password) | Returns an authenticated Heroku instance, via password. | Returns an authenticated Heroku instance, via password. | def from_pass(username, password):
"""Returns an authenticated Heroku instance, via password."""
key = get_key(username, password)
return from_key(key) | [
"def",
"from_pass",
"(",
"username",
",",
"password",
")",
":",
"key",
"=",
"get_key",
"(",
"username",
",",
"password",
")",
"return",
"from_key",
"(",
"key",
")"
] | [
21,
0
] | [
25,
24
] | python | en | ['en', 'nl', 'en'] | True |
get_key | (username, password) | Returns an API Key, fetched via password. | Returns an API Key, fetched via password. | def get_key(username, password):
"""Returns an API Key, fetched via password."""
return Heroku().request_key(username, password) | [
"def",
"get_key",
"(",
"username",
",",
"password",
")",
":",
"return",
"Heroku",
"(",
")",
".",
"request_key",
"(",
"username",
",",
"password",
")"
] | [
27,
0
] | [
30,
51
] | python | en | ['en', 'pt', 'en'] | True |
OGRGeomType.__init__ | (self, type_input) | Figures out the correct OGR Type based upon the input. | Figures out the correct OGR Type based upon the input. | def __init__(self, type_input):
"Figures out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
elif isinstance(type_input, six.string_types):
type_input = type_input.lower()
if type_input == 'geometry':
... | [
"def",
"__init__",
"(",
"self",
",",
"type_input",
")",
":",
"if",
"isinstance",
"(",
"type_input",
",",
"OGRGeomType",
")",
":",
"num",
"=",
"type_input",
".",
"num",
"elif",
"isinstance",
"(",
"type_input",
",",
"six",
".",
"string_types",
")",
":",
"t... | [
32,
4
] | [
51,
22
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__str__ | (self) | Returns the value of the name property. | Returns the value of the name property. | def __str__(self):
"Returns the value of the name property."
return self.name | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"self",
".",
"name"
] | [
53,
4
] | [
55,
24
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.__eq__ | (self, other) |
Does an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
|
Does an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
| def __eq__(self, other):
"""
Does an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, six.string_types):
... | [
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"OGRGeomType",
")",
":",
"return",
"self",
".",
"num",
"==",
"other",
".",
"num",
"elif",
"isinstance",
"(",
"other",
",",
"six",
".",
"string_types",
")",
"... | [
57,
4
] | [
69,
24
] | python | en | ['en', 'error', 'th'] | False |
OGRGeomType.name | (self) | Returns a short-hand string form of the OGR Geometry type. | Returns a short-hand string form of the OGR Geometry type. | def name(self):
"Returns a short-hand string form of the OGR Geometry type."
return self._types[self.num] | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_types",
"[",
"self",
".",
"num",
"]"
] | [
75,
4
] | [
77,
36
] | python | en | ['en', 'en', 'en'] | True |
OGRGeomType.django | (self) | Returns the Django GeometryField for this OGR Type. | Returns the Django GeometryField for this OGR Type. | def django(self):
"Returns the Django GeometryField for this OGR Type."
s = self.name.replace('25D', '')
if s in ('LinearRing', 'None'):
return None
elif s == 'Unknown':
s = 'Geometry'
return s + 'Field' | [
"def",
"django",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"name",
".",
"replace",
"(",
"'25D'",
",",
"''",
")",
"if",
"s",
"in",
"(",
"'LinearRing'",
",",
"'None'",
")",
":",
"return",
"None",
"elif",
"s",
"==",
"'Unknown'",
":",
"s",
"=",
... | [
80,
4
] | [
87,
26
] | python | en | ['en', 'en', 'en'] | True |
NullQueriesTests.test_none_as_null | (self) |
Regression test for the use of None as a query value.
None is interpreted as an SQL NULL, but only in __exact and __iexact
queries.
Set up some initial polls and choices
|
Regression test for the use of None as a query value. | def test_none_as_null(self):
"""
Regression test for the use of None as a query value.
None is interpreted as an SQL NULL, but only in __exact and __iexact
queries.
Set up some initial polls and choices
"""
p1 = Poll(question='Why?')
p1.save()
c1 ... | [
"def",
"test_none_as_null",
"(",
"self",
")",
":",
"p1",
"=",
"Poll",
"(",
"question",
"=",
"'Why?'",
")",
"p1",
".",
"save",
"(",
")",
"c1",
"=",
"Choice",
"(",
"poll",
"=",
"p1",
",",
"choice",
"=",
"'Because.'",
")",
"c1",
".",
"save",
"(",
")... | [
10,
4
] | [
49,
57
] | python | en | ['en', 'error', 'th'] | False |
NullQueriesTests.test_reverse_relations | (self) |
Querying across reverse relations and then another relation should
insert outer joins correctly so as not to exclude results.
|
Querying across reverse relations and then another relation should
insert outer joins correctly so as not to exclude results.
| def test_reverse_relations(self):
"""
Querying across reverse relations and then another relation should
insert outer joins correctly so as not to exclude results.
"""
obj = OuterA.objects.create()
self.assertQuerysetEqual(
OuterA.objects.filter(inner__third=N... | [
"def",
"test_reverse_relations",
"(",
"self",
")",
":",
"obj",
"=",
"OuterA",
".",
"objects",
".",
"create",
"(",
")",
"self",
".",
"assertQuerysetEqual",
"(",
"OuterA",
".",
"objects",
".",
"filter",
"(",
"inner__third",
"=",
"None",
")",
",",
"[",
"'<O... | [
51,
4
] | [
83,
9
] | python | en | ['en', 'error', 'th'] | False |
lazy | (func, *resultclasses) |
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
|
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
| def lazy(func, *resultclasses):
"""
Turn any callable into a lazy evaluated callable. result classes or types
is required -- at least one is needed so that the automatic forcing of
the lazy evaluation code is triggered. Results are not memoized; the
function is evaluated on every access.
"""
... | [
"def",
"lazy",
"(",
"func",
",",
"*",
"resultclasses",
")",
":",
"@",
"total_ordering",
"class",
"__proxy__",
"(",
"Promise",
")",
":",
"\"\"\"\n Encapsulate a function call and act as a proxy for methods that are\n called on the result of that function. The function ... | [
59,
0
] | [
174,
22
] | python | en | ['en', 'error', 'th'] | False |
lazystr | (text) |
Shortcut for the common case of a lazy callable that returns str.
|
Shortcut for the common case of a lazy callable that returns str.
| def lazystr(text):
"""
Shortcut for the common case of a lazy callable that returns str.
"""
return lazy(str, str)(text) | [
"def",
"lazystr",
"(",
"text",
")",
":",
"return",
"lazy",
"(",
"str",
",",
"str",
")",
"(",
"text",
")"
] | [
181,
0
] | [
185,
31
] | python | en | ['en', 'error', 'th'] | False |
keep_lazy | (*resultclasses) |
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
|
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
| def keep_lazy(*resultclasses):
"""
A decorator that allows a function to be called with one or more lazy
arguments. If none of the args are lazy, the function is evaluated
immediately, otherwise a __proxy__ is returned that will evaluate the
function when needed.
"""
if not resultclasses:
... | [
"def",
"keep_lazy",
"(",
"*",
"resultclasses",
")",
":",
"if",
"not",
"resultclasses",
":",
"raise",
"TypeError",
"(",
"\"You must pass at least one argument to keep_lazy().\"",
")",
"def",
"decorator",
"(",
"func",
")",
":",
"lazy_func",
"=",
"lazy",
"(",
"func",... | [
188,
0
] | [
207,
20
] | python | en | ['en', 'error', 'th'] | False |
keep_lazy_text | (func) |
A decorator for functions that accept lazy arguments and return text.
|
A decorator for functions that accept lazy arguments and return text.
| def keep_lazy_text(func):
"""
A decorator for functions that accept lazy arguments and return text.
"""
return keep_lazy(str)(func) | [
"def",
"keep_lazy_text",
"(",
"func",
")",
":",
"return",
"keep_lazy",
"(",
"str",
")",
"(",
"func",
")"
] | [
210,
0
] | [
214,
31
] | python | en | ['en', 'error', 'th'] | False |
unpickle_lazyobject | (wrapped) |
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
|
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
| def unpickle_lazyobject(wrapped):
"""
Used to unpickle lazy objects. Just return its argument, which will be the
wrapped object.
"""
return wrapped | [
"def",
"unpickle_lazyobject",
"(",
"wrapped",
")",
":",
"return",
"wrapped"
] | [
331,
0
] | [
336,
18
] | python | en | ['en', 'error', 'th'] | False |
partition | (predicate, values) |
Split the values into two sets, based on the return value of the function
(True/False). e.g.:
>>> partition(lambda x: x > 3, range(5))
[0, 1, 2, 3], [4]
|
Split the values into two sets, based on the return value of the function
(True/False). e.g.: | def partition(predicate, values):
"""
Split the values into two sets, based on the return value of the function
(True/False). e.g.:
>>> partition(lambda x: x > 3, range(5))
[0, 1, 2, 3], [4]
"""
results = ([], [])
for item in values:
results[predicate(item)].append(item)... | [
"def",
"partition",
"(",
"predicate",
",",
"values",
")",
":",
"results",
"=",
"(",
"[",
"]",
",",
"[",
"]",
")",
"for",
"item",
"in",
"values",
":",
"results",
"[",
"predicate",
"(",
"item",
")",
"]",
".",
"append",
"(",
"item",
")",
"return",
"... | [
389,
0
] | [
400,
18
] | python | en | ['en', 'error', 'th'] | False |
cached_property.__get__ | (self, instance, cls=None) |
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
|
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
| def __get__(self, instance, cls=None):
"""
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
"""
if instance is None:
retur... | [
"def",
"__get__",
"(",
"self",
",",
"instance",
",",
"cls",
"=",
"None",
")",
":",
"if",
"instance",
"is",
"None",
":",
"return",
"self",
"res",
"=",
"instance",
".",
"__dict__",
"[",
"self",
".",
"name",
"]",
"=",
"self",
".",
"func",
"(",
"instan... | [
39,
4
] | [
48,
18
] | python | en | ['en', 'error', 'th'] | False |
LazyObject._setup | (self) |
Must be implemented by subclasses to initialize the wrapped object.
|
Must be implemented by subclasses to initialize the wrapped object.
| def _setup(self):
"""
Must be implemented by subclasses to initialize the wrapped object.
"""
raise NotImplementedError('subclasses of LazyObject must provide a _setup() method') | [
"def",
"_setup",
"(",
"self",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of LazyObject must provide a _setup() method'",
")"
] | [
263,
4
] | [
267,
92
] | python | en | ['en', 'error', 'th'] | False |
SimpleLazyObject.__init__ | (self, func) |
Pass in a callable that returns the object to be wrapped.
If copies are made of the resulting SimpleLazyObject, which can happen
in various circumstances within Django, then you must ensure that the
callable can be safely run more than once and will return the same
value.
... |
Pass in a callable that returns the object to be wrapped. | def __init__(self, func):
"""
Pass in a callable that returns the object to be wrapped.
If copies are made of the resulting SimpleLazyObject, which can happen
in various circumstances within Django, then you must ensure that the
callable can be safely run more than once and will... | [
"def",
"__init__",
"(",
"self",
",",
"func",
")",
":",
"self",
".",
"__dict__",
"[",
"'_setupfunc'",
"]",
"=",
"func",
"super",
"(",
")",
".",
"__init__",
"(",
")"
] | [
346,
4
] | [
356,
26
] | python | en | ['en', 'error', 'th'] | False |
DatabaseIntrospection.get_table_list | (self, cursor) |
Returns a list of table and view names in the current database.
|
Returns a list of table and view names in the current database.
| def get_table_list(self, cursor):
"""
Returns a list of table and view names in the current database.
"""
cursor.execute("""
SELECT c.relname, c.relkind
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
... | [
"def",
"get_table_list",
"(",
"self",
",",
"cursor",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT c.relname, c.relkind\n FROM pg_catalog.pg_class c\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind IN ('... | [
30,
4
] | [
43,
53
] | python | en | ['en', 'error', 'th'] | False |
DatabaseIntrospection.get_table_description | (self, cursor, table_name) | Returns a description of the table, with the DB-API cursor.description interface. | Returns a description of the table, with the DB-API cursor.description interface. | def get_table_description(self, cursor, table_name):
"Returns a description of the table, with the DB-API cursor.description interface."
# As cursor.description does not return reliably the nullable property,
# we have to query the information_schema (#7783)
cursor.execute("""
... | [
"def",
"get_table_description",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"# As cursor.description does not return reliably the nullable property,",
"# we have to query the information_schema (#7783)",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT column_n... | [
45,
4
] | [
56,
47
] | python | en | ['en', 'fr', 'en'] | True |
DatabaseIntrospection.get_relations | (self, cursor, table_name) |
Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.
|
Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.
| def get_relations(self, cursor, table_name):
"""
Returns a dictionary of {field_index: (field_index_other_table, other_table)}
representing all relationships to the given table. Indexes are 0-based.
"""
cursor.execute("""
SELECT con.conkey, con.confkey, c2.relname
... | [
"def",
"get_relations",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"cursor",
".",
"execute",
"(",
"\"\"\"\n SELECT con.conkey, con.confkey, c2.relname\n FROM pg_constraint con, pg_class c1, pg_class c2\n WHERE c1.oid = con.conrelid\n ... | [
58,
4
] | [
74,
24
] | python | en | ['en', 'error', 'th'] | False |
DatabaseIntrospection.get_constraints | (self, cursor, table_name) |
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
|
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
| def get_constraints(self, cursor, table_name):
"""
Retrieves any constraints or keys (unique, pk, fk, check, index) across one or more columns.
"""
constraints = {}
# Loop over the key table, collecting things as constraints
# This will get PKs, FKs, and uniques, but not ... | [
"def",
"get_constraints",
"(",
"self",
",",
"cursor",
",",
"table_name",
")",
":",
"constraints",
"=",
"{",
"}",
"# Loop over the key table, collecting things as constraints",
"# This will get PKs, FKs, and uniques, but not CHECK",
"cursor",
".",
"execute",
"(",
"\"\"\"\n ... | [
122,
4
] | [
212,
26
] | python | en | ['en', 'error', 'th'] | False |
_project_perturbation | (
perturbation, epsilon, input_image, clip_min=None, clip_max=None
) | Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
| Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
| def _project_perturbation(
perturbation, epsilon, input_image, clip_min=None, clip_max=None
):
"""Project `perturbation` onto L-infinity ball of radius `epsilon`.
Also project into hypercube such that the resulting adversarial example
is between clip_min and clip_max, if applicable.
"""
if clip... | [
"def",
"_project_perturbation",
"(",
"perturbation",
",",
"epsilon",
",",
"input_image",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
")",
":",
"if",
"clip_min",
"is",
"None",
"or",
"clip_max",
"is",
"None",
":",
"raise",
"NotImplementedError",
... | [
226,
0
] | [
254,
38
] | python | en | ['en', 'fa', 'en'] | True |
margin_logit_loss | (model_logits, label, nb_classes=10, num_classes=None) | Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimization, i.e. it returns a batch of loss values.
| Computes difference between logit for `label` and next highest logit. | def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None):
"""Computes difference between logit for `label` and next highest logit.
The loss is high when `label` is unlikely (targeted by default).
This follows the same interface as `loss_fn` for TensorOptimizer and
projected_optimizat... | [
"def",
"margin_logit_loss",
"(",
"model_logits",
",",
"label",
",",
"nb_classes",
"=",
"10",
",",
"num_classes",
"=",
"None",
")",
":",
"if",
"num_classes",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"`num_classes` is depreciated. Switch to `nb_clas... | [
466,
0
] | [
499,
15
] | python | en | ['en', 'en', 'en'] | True |
spm | (
x,
model,
y=None,
n_samples=None,
dx_min=-0.1,
dx_max=0.1,
n_dxs=5,
dy_min=-0.1,
dy_max=0.1,
n_dys=5,
angle_min=-30,
angle_max=30,
n_angles=31,
black_border_size=0,
) |
TensorFlow implementation of the Spatial Transformation Method.
:return: a tensor for the adversarial example
|
TensorFlow implementation of the Spatial Transformation Method.
:return: a tensor for the adversarial example
| def spm(
x,
model,
y=None,
n_samples=None,
dx_min=-0.1,
dx_max=0.1,
n_dxs=5,
dy_min=-0.1,
dy_max=0.1,
n_dys=5,
angle_min=-30,
angle_max=30,
n_angles=31,
black_border_size=0,
):
"""
TensorFlow implementation of the Spatial Transformation Method.
:return... | [
"def",
"spm",
"(",
"x",
",",
"model",
",",
"y",
"=",
"None",
",",
"n_samples",
"=",
"None",
",",
"dx_min",
"=",
"-",
"0.1",
",",
"dx_max",
"=",
"0.1",
",",
"n_dxs",
"=",
"5",
",",
"dy_min",
"=",
"-",
"0.1",
",",
"dy_max",
"=",
"0.1",
",",
"n_... | [
547,
0
] | [
615,
23
] | python | en | ['en', 'error', 'th'] | False |
parallel_apply_transformations | (x, transforms, black_border_size=0) |
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
|
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
| def parallel_apply_transformations(x, transforms, black_border_size=0):
"""
Apply image transformations in parallel.
:param transforms: TODO
:param black_border_size: int, size of black border to apply
Returns:
Transformed images
"""
transforms = tf.convert_to_tensor(transforms, dtype=... | [
"def",
"parallel_apply_transformations",
"(",
"x",
",",
"transforms",
",",
"black_border_size",
"=",
"0",
")",
":",
"transforms",
"=",
"tf",
".",
"convert_to_tensor",
"(",
"transforms",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
"x",
"=",
"_apply_black_bord... | [
618,
0
] | [
644,
26
] | python | en | ['en', 'error', 'th'] | False |
projected_optimization | (
loss_fn,
input_image,
label,
epsilon,
num_steps,
clip_min=None,
clip_max=None,
optimizer=TensorAdam(),
project_perturbation=_project_perturbation,
early_stop_loss_threshold=None,
is_debug=False,
) | Generic projected optimization, generalized to work with approximate
gradients. Used for e.g. the SPSA attack.
Args:
:param loss_fn: A callable which takes `input_image` and `label` as
arguments, and returns a batch of loss values. Same
interface as TensorOptim... | Generic projected optimization, generalized to work with approximate
gradients. Used for e.g. the SPSA attack. | def projected_optimization(
loss_fn,
input_image,
label,
epsilon,
num_steps,
clip_min=None,
clip_max=None,
optimizer=TensorAdam(),
project_perturbation=_project_perturbation,
early_stop_loss_threshold=None,
is_debug=False,
):
"""Generic projected optimization, generalized... | [
"def",
"projected_optimization",
"(",
"loss_fn",
",",
"input_image",
",",
"label",
",",
"epsilon",
",",
"num_steps",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"optimizer",
"=",
"TensorAdam",
"(",
")",
",",
"project_perturbation",
"=",
... | [
647,
0
] | [
805,
46
] | python | en | ['en', 'en', 'en'] | True |
SPSA.generate | (
self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_threshold=None,
learning_rate=DEFAULT_LEARNING_RATE,
delta=DEFAULT_DELTA,
spsa_samples=DEFAULT... |
Generate symbolic graph for adversarial examples.
:param x: The model's symbolic inputs. Must be a batch of size 1.
:param y: A Tensor or None. The index of the correct label.
:param y_target: A Tensor or None. The index of the target label in a
targeted attack... |
Generate symbolic graph for adversarial examples. | def generate(
self,
x,
y=None,
y_target=None,
eps=None,
clip_min=None,
clip_max=None,
nb_iter=None,
is_targeted=None,
early_stop_loss_threshold=None,
learning_rate=DEFAULT_LEARNING_RATE,
delta=DEFAULT_DELTA,
spsa_sam... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"eps",
"=",
"None",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"nb_iter",
"=",
"None",
",",
"is_targeted",
"=",
"None",
",",
... | [
51,
4
] | [
193,
20
] | python | en | ['en', 'error', 'th'] | False |
TensorOptimizer._compute_gradients | (self, loss_fn, x, unused_optim_state) | Compute a new value of `x` to minimize `loss_fn`.
Args:
loss_fn: a callable that takes `x`, a batch of images, and returns
a batch of loss values. `x` will be optimized to minimize
`loss_fn(x)`.
x: A list of Tensors, the values to be updated. This is anal... | Compute a new value of `x` to minimize `loss_fn`. | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute a new value of `x` to minimize `loss_fn`.
Args:
loss_fn: a callable that takes `x`, a batch of images, and returns
a batch of loss values. `x` will be optimized to minimize
`loss_fn(x)`.... | [
"def",
"_compute_gradients",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"unused_optim_state",
")",
":",
"# Assumes `x` is a list,",
"# and contains a tensor representing a batch of images",
"assert",
"len",
"(",
"x",
")",
"==",
"1",
"and",
"isinstance",
"(",
"x",
"... | [
269,
4
] | [
294,
36
] | python | en | ['en', 'en', 'en'] | True |
TensorOptimizer._apply_gradients | (self, grads, x, optim_state) |
Given a gradient, make one optimization step.
:param grads: list of tensors, same length as `x`, containing the corresponding gradients
:param x: list of tensors to update
:param optim_state: dict
Returns:
new_x: list of tensors, updated version of `x`
new_... |
Given a gradient, make one optimization step. | def _apply_gradients(self, grads, x, optim_state):
"""
Given a gradient, make one optimization step.
:param grads: list of tensors, same length as `x`, containing the corresponding gradients
:param x: list of tensors to update
:param optim_state: dict
Returns:
... | [
"def",
"_apply_gradients",
"(",
"self",
",",
"grads",
",",
"x",
",",
"optim_state",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"_apply_gradients should be defined in each subclass\"",
")"
] | [
296,
4
] | [
308,
88
] | python | en | ['en', 'error', 'th'] | False |
TensorOptimizer.minimize | (self, loss_fn, x, optim_state) |
Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
new_x: list of Tensor, ... |
Analogous to tf.Optimizer.minimize | def minimize(self, loss_fn, x, optim_state):
"""
Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer st... | [
"def",
"minimize",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"optim_state",
")",
":",
"grads",
"=",
"self",
".",
"_compute_gradients",
"(",
"loss_fn",
",",
"x",
",",
"optim_state",
")",
"return",
"self",
".",
"_apply_gradients",
"(",
"grads",
",",
"x",... | [
310,
4
] | [
323,
59
] | python | en | ['en', 'error', 'th'] | False |
TensorOptimizer.init_state | (self, x) | Returns the initial state of the optimizer.
Args:
x: A list of Tensors, which will be optimized.
Returns:
A dictionary, representing the initial state of the optimizer.
| Returns the initial state of the optimizer. | def init_state(self, x):
"""Returns the initial state of the optimizer.
Args:
x: A list of Tensors, which will be optimized.
Returns:
A dictionary, representing the initial state of the optimizer.
"""
raise NotImplementedError("init_state should be defin... | [
"def",
"init_state",
"(",
"self",
",",
"x",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"init_state should be defined in each subclass\"",
")"
] | [
325,
4
] | [
334,
82
] | python | en | ['en', 'en', 'en'] | True |
TensorAdam.init_state | (self, x) |
Initialize t, m, and u
|
Initialize t, m, and u
| def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.0
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | [
"def",
"init_state",
"(",
"self",
",",
"x",
")",
":",
"optim_state",
"=",
"{",
"}",
"optim_state",
"[",
"\"t\"",
"]",
"=",
"0.0",
"optim_state",
"[",
"\"m\"",
"]",
"=",
"[",
"tf",
".",
"zeros_like",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"opt... | [
362,
4
] | [
370,
26
] | python | en | ['en', 'error', 'th'] | False |
TensorAdam._apply_gradients | (self, grads, x, optim_state) | Refer to parent class documentation. | Refer to parent class documentation. | def _apply_gradients(self, grads, x, optim_state):
"""Refer to parent class documentation."""
new_x = [None] * len(x)
new_optim_state = {
"t": optim_state["t"] + 1.0,
"m": [None] * len(x),
"u": [None] * len(x),
}
t = new_optim_state["t"]
... | [
"def",
"_apply_gradients",
"(",
"self",
",",
"grads",
",",
"x",
",",
"optim_state",
")",
":",
"new_x",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"x",
")",
"new_optim_state",
"=",
"{",
"\"t\"",
":",
"optim_state",
"[",
"\"t\"",
"]",
"+",
"1.0",
",",
"... | [
372,
4
] | [
390,
37
] | python | en | ['en', 'pt', 'en'] | True |
SPSAAdam._compute_gradients | (self, loss_fn, x, unused_optim_state) | Compute gradient estimates using SPSA. | Compute gradient estimates using SPSA. | def _compute_gradients(self, loss_fn, x, unused_optim_state):
"""Compute gradient estimates using SPSA."""
# Assumes `x` is a list, containing a [1, H, W, C] image
# If static batch dimension is None, tf.reshape to batch size 1
# so that static shape can be inferred
assert len(x)... | [
"def",
"_compute_gradients",
"(",
"self",
",",
"loss_fn",
",",
"x",
",",
"unused_optim_state",
")",
":",
"# Assumes `x` is a list, containing a [1, H, W, C] image",
"# If static batch dimension is None, tf.reshape to batch size 1",
"# so that static shape can be inferred",
"assert",
... | [
427,
4
] | [
463,
25
] | python | en | ['fr', 'la', 'en'] | False |
TestAdminOrdering.test_default_ordering | (self) |
The default ordering should be by name, as specified in the inner Meta
class.
|
The default ordering should be by name, as specified in the inner Meta
class.
| def test_default_ordering(self):
"""
The default ordering should be by name, as specified in the inner Meta
class.
"""
ma = ModelAdmin(Band, admin.site)
names = [b.name for b in ma.get_queryset(request)]
self.assertListEqual(['Aerosmith', 'Radiohead', 'Van Halen']... | [
"def",
"test_default_ordering",
"(",
"self",
")",
":",
"ma",
"=",
"ModelAdmin",
"(",
"Band",
",",
"admin",
".",
"site",
")",
"names",
"=",
"[",
"b",
".",
"name",
"for",
"b",
"in",
"ma",
".",
"get_queryset",
"(",
"request",
")",
"]",
"self",
".",
"a... | [
41,
4
] | [
48,
76
] | python | en | ['en', 'error', 'th'] | False |
TestAdminOrdering.test_specified_ordering | (self) |
Let's use a custom ModelAdmin that changes the ordering, and make sure
it actually changes.
|
Let's use a custom ModelAdmin that changes the ordering, and make sure
it actually changes.
| def test_specified_ordering(self):
"""
Let's use a custom ModelAdmin that changes the ordering, and make sure
it actually changes.
"""
class BandAdmin(ModelAdmin):
ordering = ('rank',) # default ordering is ('name',)
ma = BandAdmin(Band, admin.site)
n... | [
"def",
"test_specified_ordering",
"(",
"self",
")",
":",
"class",
"BandAdmin",
"(",
"ModelAdmin",
")",
":",
"ordering",
"=",
"(",
"'rank'",
",",
")",
"# default ordering is ('name',)",
"ma",
"=",
"BandAdmin",
"(",
"Band",
",",
"admin",
".",
"site",
")",
"nam... | [
50,
4
] | [
59,
76
] | python | en | ['en', 'error', 'th'] | False |
TestAdminOrdering.test_dynamic_ordering | (self) |
Let's use a custom ModelAdmin that changes the ordering dynamically.
|
Let's use a custom ModelAdmin that changes the ordering dynamically.
| def test_dynamic_ordering(self):
"""
Let's use a custom ModelAdmin that changes the ordering dynamically.
"""
super_user = User.objects.create(username='admin', is_superuser=True)
other_user = User.objects.create(username='other')
request = self.request_factory.get('/')
... | [
"def",
"test_dynamic_ordering",
"(",
"self",
")",
":",
"super_user",
"=",
"User",
".",
"objects",
".",
"create",
"(",
"username",
"=",
"'admin'",
",",
"is_superuser",
"=",
"True",
")",
"other_user",
"=",
"User",
".",
"objects",
".",
"create",
"(",
"usernam... | [
61,
4
] | [
74,
76
] | python | en | ['en', 'error', 'th'] | False |
TestInlineModelAdminOrdering.test_default_ordering | (self) |
The default ordering should be by name, as specified in the inner Meta
class.
|
The default ordering should be by name, as specified in the inner Meta
class.
| def test_default_ordering(self):
"""
The default ordering should be by name, as specified in the inner Meta
class.
"""
inline = SongInlineDefaultOrdering(self.band, admin.site)
names = [s.name for s in inline.get_queryset(request)]
self.assertListEqual(['Dude (Loo... | [
"def",
"test_default_ordering",
"(",
"self",
")",
":",
"inline",
"=",
"SongInlineDefaultOrdering",
"(",
"self",
".",
"band",
",",
"admin",
".",
"site",
")",
"names",
"=",
"[",
"s",
".",
"name",
"for",
"s",
"in",
"inline",
".",
"get_queryset",
"(",
"reque... | [
91,
4
] | [
98,
82
] | python | en | ['en', 'error', 'th'] | False |
TestInlineModelAdminOrdering.test_specified_ordering | (self) |
Let's check with ordering set to something different than the default.
|
Let's check with ordering set to something different than the default.
| def test_specified_ordering(self):
"""
Let's check with ordering set to something different than the default.
"""
inline = SongInlineNewOrdering(self.band, admin.site)
names = [s.name for s in inline.get_queryset(request)]
self.assertListEqual(['Jaded', 'Pink', 'Dude (Loo... | [
"def",
"test_specified_ordering",
"(",
"self",
")",
":",
"inline",
"=",
"SongInlineNewOrdering",
"(",
"self",
".",
"band",
",",
"admin",
".",
"site",
")",
"names",
"=",
"[",
"s",
".",
"name",
"for",
"s",
"in",
"inline",
".",
"get_queryset",
"(",
"request... | [
100,
4
] | [
106,
82
] | 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.