Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
test_add_argparse_args_redefined_error | (cli_args, monkeypatch) | Asserts thar an error raised in case of passing not default cli arguments. | Asserts thar an error raised in case of passing not default cli arguments. | def test_add_argparse_args_redefined_error(cli_args, monkeypatch):
"""Asserts thar an error raised in case of passing not default cli arguments."""
class _UnkArgError(Exception):
pass
def _raise():
raise _UnkArgError
parser = ArgumentParser(add_help=False)
parser = Trainer.add_arg... | [
"def",
"test_add_argparse_args_redefined_error",
"(",
"cli_args",
",",
"monkeypatch",
")",
":",
"class",
"_UnkArgError",
"(",
"Exception",
")",
":",
"pass",
"def",
"_raise",
"(",
")",
":",
"raise",
"_UnkArgError",
"parser",
"=",
"ArgumentParser",
"(",
"add_help",
... | [
92,
0
] | [
107,
35
] | python | en | ['en', 'en', 'en'] | True |
test_argparse_args_parsing | (cli_args, expected) | Test multi type argument with bool. | Test multi type argument with bool. | def test_argparse_args_parsing(cli_args, expected):
"""Test multi type argument with bool."""
cli_args = cli_args.split(' ') if cli_args else []
with mock.patch("argparse._sys.argv", ["any.py"] + cli_args):
parser = ArgumentParser(add_help=False)
parser = Trainer.add_argparse_args(parent_par... | [
"def",
"test_argparse_args_parsing",
"(",
"cli_args",
",",
"expected",
")",
":",
"cli_args",
"=",
"cli_args",
".",
"split",
"(",
"' '",
")",
"if",
"cli_args",
"else",
"[",
"]",
"with",
"mock",
".",
"patch",
"(",
"\"argparse._sys.argv\"",
",",
"[",
"\"any.py\... | [
160,
0
] | [
170,
43
] | python | en | ['en', 'en', 'en'] | True |
test_argparse_args_parsing_gpus | (cli_args, expected_gpu) | Test multi type argument with bool. | Test multi type argument with bool. | def test_argparse_args_parsing_gpus(cli_args, expected_gpu):
"""Test multi type argument with bool."""
cli_args = cli_args.split(' ') if cli_args else []
with mock.patch("argparse._sys.argv", ["any.py"] + cli_args):
parser = ArgumentParser(add_help=False)
parser = Trainer.add_argparse_args(p... | [
"def",
"test_argparse_args_parsing_gpus",
"(",
"cli_args",
",",
"expected_gpu",
")",
":",
"cli_args",
"=",
"cli_args",
".",
"split",
"(",
"' '",
")",
"if",
"cli_args",
"else",
"[",
"]",
"with",
"mock",
".",
"patch",
"(",
"\"argparse._sys.argv\"",
",",
"[",
"... | [
178,
0
] | [
187,
59
] | python | en | ['en', 'en', 'en'] | True |
inject_context_dict | (_, __, event_dict) | Add the structlog context dict to log events generated by the stdlib logging library.
>>> import structlog
>>> from django_structlog.processors import inject_context_dict
>>>
>>> LOGGING = {
... "version": 1,
... "disable_existing_loggers": False,
... "formatters": {
... ... | Add the structlog context dict to log events generated by the stdlib logging library. | def inject_context_dict(_, __, event_dict):
"""Add the structlog context dict to log events generated by the stdlib logging library.
>>> import structlog
>>> from django_structlog.processors import inject_context_dict
>>>
>>> LOGGING = {
... "version": 1,
... "disable_existing_logge... | [
"def",
"inject_context_dict",
"(",
"_",
",",
"__",
",",
"event_dict",
")",
":",
"context_class",
"=",
"structlog",
".",
"get_config",
"(",
")",
".",
"get",
"(",
"\"context_class\"",
")",
"if",
"context_class",
":",
"for",
"key",
",",
"value",
"in",
"contex... | [
3,
0
] | [
72,
21
] | python | en | ['en', 'en', 'en'] | True |
TestFromString.test_floating_overflow | (self) | Strings containing an unrepresentable float overflow | Strings containing an unrepresentable float overflow | def test_floating_overflow(self):
""" Strings containing an unrepresentable float overflow """
fhalf = np.half('1e10000')
assert_equal(fhalf, np.inf)
fsingle = np.single('1e10000')
assert_equal(fsingle, np.inf)
fdouble = np.double('1e10000')
assert_equal(fdouble, ... | [
"def",
"test_floating_overflow",
"(",
"self",
")",
":",
"fhalf",
"=",
"np",
".",
"half",
"(",
"'1e10000'",
")",
"assert_equal",
"(",
"fhalf",
",",
"np",
".",
"inf",
")",
"fsingle",
"=",
"np",
".",
"single",
"(",
"'1e10000'",
")",
"assert_equal",
"(",
"... | [
24,
4
] | [
42,
42
] | python | en | ['en', 'en', 'en'] | True |
generate_config | (template_path, template, output_file, **context) | Generate a final config file based on a template and some context. | Generate a final config file based on a template and some context. | def generate_config(template_path, template, output_file, **context):
""" Generate a final config file based on a template and some context. """
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path, followlinks=True),
undefined=jinja2.StrictUndefined)
raw_output = env.get_t... | [
"def",
"generate_config",
"(",
"template_path",
",",
"template",
",",
"output_file",
",",
"*",
"*",
"context",
")",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"template_path",
",",
"followlinks",
... | [
96,
0
] | [
103,
28
] | python | en | ['en', 'en', 'en'] | True |
test_gpu_stats_monitor | (tmpdir) |
Test GPU stats are logged using a logger.
|
Test GPU stats are logged using a logger.
| def test_gpu_stats_monitor(tmpdir):
"""
Test GPU stats are logged using a logger.
"""
model = BoringModel()
gpu_stats = GPUStatsMonitor(intra_step_time=True)
logger = CSVLogger(tmpdir)
log_every_n_steps = 2
trainer = Trainer(
default_root_dir=tmpdir,
max_epochs=2,
... | [
"def",
"test_gpu_stats_monitor",
"(",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"gpu_stats",
"=",
"GPUStatsMonitor",
"(",
"intra_step_time",
"=",
"True",
")",
"logger",
"=",
"CSVLogger",
"(",
"tmpdir",
")",
"log_every_n_steps",
"=",
"2",
"trai... | [
29,
0
] | [
66,
58
] | python | en | ['en', 'error', 'th'] | False |
test_gpu_stats_monitor_cpu_machine | (tmpdir) |
Test GPUStatsMonitor on CPU machine.
|
Test GPUStatsMonitor on CPU machine.
| def test_gpu_stats_monitor_cpu_machine(tmpdir):
"""
Test GPUStatsMonitor on CPU machine.
"""
with pytest.raises(MisconfigurationException, match='NVIDIA driver is not installed'):
GPUStatsMonitor() | [
"def",
"test_gpu_stats_monitor_cpu_machine",
"(",
"tmpdir",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"MisconfigurationException",
",",
"match",
"=",
"'NVIDIA driver is not installed'",
")",
":",
"GPUStatsMonitor",
"(",
")"
] | [
70,
0
] | [
75,
25
] | python | en | ['en', 'error', 'th'] | False |
test_gpu_stats_monitor_no_logger | (tmpdir) |
Test GPUStatsMonitor with no logger in Trainer.
|
Test GPUStatsMonitor with no logger in Trainer.
| def test_gpu_stats_monitor_no_logger(tmpdir):
"""
Test GPUStatsMonitor with no logger in Trainer.
"""
model = BoringModel()
gpu_stats = GPUStatsMonitor()
trainer = Trainer(
default_root_dir=tmpdir,
callbacks=[gpu_stats],
max_epochs=1,
gpus=1,
logger=False... | [
"def",
"test_gpu_stats_monitor_no_logger",
"(",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"gpu_stats",
"=",
"GPUStatsMonitor",
"(",
")",
"trainer",
"=",
"Trainer",
"(",
"default_root_dir",
"=",
"tmpdir",
",",
"callbacks",
"=",
"[",
"gpu_stats",
... | [
79,
0
] | [
95,
26
] | python | en | ['en', 'error', 'th'] | False |
test_gpu_stats_monitor_no_gpu_warning | (tmpdir) |
Test GPUStatsMonitor raises a warning when not training on GPU device.
|
Test GPUStatsMonitor raises a warning when not training on GPU device.
| def test_gpu_stats_monitor_no_gpu_warning(tmpdir):
"""
Test GPUStatsMonitor raises a warning when not training on GPU device.
"""
model = BoringModel()
gpu_stats = GPUStatsMonitor()
trainer = Trainer(
default_root_dir=tmpdir,
callbacks=[gpu_stats],
max_steps=1,
g... | [
"def",
"test_gpu_stats_monitor_no_gpu_warning",
"(",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"gpu_stats",
"=",
"GPUStatsMonitor",
"(",
")",
"trainer",
"=",
"Trainer",
"(",
"default_root_dir",
"=",
"tmpdir",
",",
"callbacks",
"=",
"[",
"gpu_sta... | [
99,
0
] | [
114,
26
] | python | en | ['en', 'error', 'th'] | False |
path_and_filename | (label) | Retrieve actual path and filename from bazel label
Args:
label: bazel label to specify target proto.
Returns:
actual path and filename
| Retrieve actual path and filename from bazel label | def path_and_filename(label):
"""Retrieve actual path and filename from bazel label
Args:
label: bazel label to specify target proto.
Returns:
actual path and filename
"""
if label.startswith('/'):
label = label.replace('//', '/', 1)
elif label.startswith('@'):
... | [
"def",
"path_and_filename",
"(",
"label",
")",
":",
"if",
"label",
".",
"startswith",
"(",
"'/'",
")",
":",
"label",
"=",
"label",
".",
"replace",
"(",
"'//'",
",",
"'/'",
",",
"1",
")",
"elif",
"label",
".",
"startswith",
"(",
"'@'",
")",
":",
"la... | [
12,
0
] | [
29,
83
] | python | en | ['en', 'en', 'en'] | True |
golden_proto_file | (path, filename, version) | Retrieve golden proto file path. In general, those are placed in tools/testdata/protoxform.
Args:
path: target proto path
filename: target proto filename
version: api version to specify target golden proto filename
Returns:
actual golden proto absolute path
| Retrieve golden proto file path. In general, those are placed in tools/testdata/protoxform. | def golden_proto_file(path, filename, version):
"""Retrieve golden proto file path. In general, those are placed in tools/testdata/protoxform.
Args:
path: target proto path
filename: target proto filename
version: api version to specify target golden proto filename
Returns:
... | [
"def",
"golden_proto_file",
"(",
"path",
",",
"filename",
",",
"version",
")",
":",
"base",
"=",
"\"./\"",
"base",
"+=",
"path",
"+",
"\"/\"",
"+",
"filename",
"+",
"\".\"",
"+",
"version",
"+",
"\".gold\"",
"return",
"os",
".",
"path",
".",
"abspath",
... | [
32,
0
] | [
45,
32
] | python | en | ['en', 'en', 'en'] | True |
proto_print | (src, dst) | Pretty-print FileDescriptorProto to a destination file.
Args:
src: source path for FileDescriptorProto.
dst: destination path for formatted proto.
| Pretty-print FileDescriptorProto to a destination file. | def proto_print(src, dst):
"""Pretty-print FileDescriptorProto to a destination file.
Args:
src: source path for FileDescriptorProto.
dst: destination path for formatted proto.
"""
print('proto_print %s -> %s' % (src, dst))
subprocess.check_call([
'bazel-bin/tools/protoxform... | [
"def",
"proto_print",
"(",
"src",
",",
"dst",
")",
":",
"print",
"(",
"'proto_print %s -> %s'",
"%",
"(",
"src",
",",
"dst",
")",
")",
"subprocess",
".",
"check_call",
"(",
"[",
"'bazel-bin/tools/protoxform/protoprint'",
",",
"src",
",",
"dst",
",",
"'./baze... | [
48,
0
] | [
60,
6
] | python | it | ['it', 'it', 'en'] | True |
result_proto_file | (cmd, path, tmp, filename, version) | Retrieve result proto file path. In general, those are placed in bazel artifacts.
Args:
cmd: fix or freeze?
path: target proto path
tmp: temporary directory.
filename: target proto filename
version: api version to specify target result proto filename
Returns:
ac... | Retrieve result proto file path. In general, those are placed in bazel artifacts. | def result_proto_file(cmd, path, tmp, filename, version):
"""Retrieve result proto file path. In general, those are placed in bazel artifacts.
Args:
cmd: fix or freeze?
path: target proto path
tmp: temporary directory.
filename: target proto filename
version: api version... | [
"def",
"result_proto_file",
"(",
"cmd",
",",
"path",
",",
"tmp",
",",
"filename",
",",
"version",
")",
":",
"base",
"=",
"\"./bazel-bin\"",
"base",
"+=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"%s_protos\"",
"%",
"cmd",
")",
"base",
"+=",
... | [
63,
0
] | [
82,
14
] | python | en | ['en', 'en', 'en'] | True |
diff | (result_file, golden_file) | Execute diff command with unified form
Args:
result_file: result proto file
golden_file: golden proto file
Returns:
output and status code
| Execute diff command with unified form | def diff(result_file, golden_file):
"""Execute diff command with unified form
Args:
result_file: result proto file
golden_file: golden proto file
Returns:
output and status code
"""
command = 'diff -u '
command += result_file + ' '
command += golden_file
status,... | [
"def",
"diff",
"(",
"result_file",
",",
"golden_file",
")",
":",
"command",
"=",
"'diff -u '",
"command",
"+=",
"result_file",
"+",
"' '",
"command",
"+=",
"golden_file",
"status",
",",
"stdout",
",",
"stderr",
"=",
"run_command",
"(",
"command",
")",
"retur... | [
85,
0
] | [
99,
35
] | python | en | ['en', 'en', 'en'] | True |
run | (cmd, path, filename, version) | Run main execution for protoxform test
Args:
cmd: fix or freeze?
path: target proto path
filename: target proto filename
version: api version to specify target result proto filename
Returns:
result message extracted from diff command
| Run main execution for protoxform test | def run(cmd, path, filename, version):
"""Run main execution for protoxform test
Args:
cmd: fix or freeze?
path: target proto path
filename: target proto filename
version: api version to specify target result proto filename
Returns:
result message extracted from dif... | [
"def",
"run",
"(",
"cmd",
",",
"path",
",",
"filename",
",",
"version",
")",
":",
"message",
"=",
"\"\"",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tmp",
":",
"golden_path",
"=",
"golden_proto_file",
"(",
"path",
",",
"filename",
",... | [
102,
0
] | [
126,
22
] | python | en | ['en', 'gl', 'ur'] | False |
_display_as_base | (cls) |
A decorator that makes an exception class look like its base.
We use this to hide subclasses that are implementation details - the user
should catch the base type, which is what the traceback will show them.
Classes decorated with this decorator are subject to removal without a
deprecation warnin... |
A decorator that makes an exception class look like its base. | def _display_as_base(cls):
"""
A decorator that makes an exception class look like its base.
We use this to hide subclasses that are implementation details - the user
should catch the base type, which is what the traceback will show them.
Classes decorated with this decorator are subject to remova... | [
"def",
"_display_as_base",
"(",
"cls",
")",
":",
"assert",
"issubclass",
"(",
"cls",
",",
"Exception",
")",
"cls",
".",
"__name__",
"=",
"cls",
".",
"__base__",
".",
"__name__",
"cls",
".",
"__qualname__",
"=",
"cls",
".",
"__base__",
".",
"__qualname__",
... | [
16,
0
] | [
30,
14
] | python | en | ['en', 'error', 'th'] | False |
checkCodeSignature | (programPath, programType) | Checks the code signature of the referenced program. | Checks the code signature of the referenced program. | def checkCodeSignature(programPath, programType):
"""Checks the code signature of the referenced program."""
# Use the codesign tool to check the signature. The second "-v" is required to enable
# verbose mode, which causes codesign to do more checking. By default it does the minimum
# amount of chec... | [
"def",
"checkCodeSignature",
"(",
"programPath",
",",
"programType",
")",
":",
"# Use the codesign tool to check the signature. The second \"-v\" is required to enable",
"# verbose mode, which causes codesign to do more checking. By default it does the minimum",
"# amount of checking (\"Is the... | [
76,
0
] | [
96,
84
] | python | en | ['en', 'en', 'en'] | True |
readDesignatedRequirement | (programPath, programType) | Returns the designated requirement of the program as a string. | Returns the designated requirement of the program as a string. | def readDesignatedRequirement(programPath, programType):
"""Returns the designated requirement of the program as a string."""
args = [
# "false",
"codesign",
"-d",
"-r",
"-",
programPath
]
try:
req = subprocess.check_output(args, stderr=open("/dev/... | [
"def",
"readDesignatedRequirement",
"(",
"programPath",
",",
"programType",
")",
":",
"args",
"=",
"[",
"# \"false\",",
"\"codesign\"",
",",
"\"-d\"",
",",
"\"-r\"",
",",
"\"-\"",
",",
"programPath",
"]",
"try",
":",
"req",
"=",
"subprocess",
".",
"check_outpu... | [
98,
0
] | [
116,
46
] | python | en | ['en', 'en', 'en'] | True |
readInfoPlistFromPath | (infoPath) | Reads an "Info.plist" file from the specified path. | Reads an "Info.plist" file from the specified path. | def readInfoPlistFromPath(infoPath):
"""Reads an "Info.plist" file from the specified path."""
try:
info = plistlib.readPlist(infoPath)
except:
raise CheckException("'Info.plist' not readable", infoPath)
if not isinstance(info, dict):
raise CheckException("'Info.plist' root must ... | [
"def",
"readInfoPlistFromPath",
"(",
"infoPath",
")",
":",
"try",
":",
"info",
"=",
"plistlib",
".",
"readPlist",
"(",
"infoPath",
")",
"except",
":",
"raise",
"CheckException",
"(",
"\"'Info.plist' not readable\"",
",",
"infoPath",
")",
"if",
"not",
"isinstance... | [
118,
0
] | [
126,
15
] | python | en | ['en', 'en', 'en'] | True |
readPlistFromToolSection | (toolPath, segmentName, sectionName) | Reads a dictionary property list from the specified section within the specified executable. | Reads a dictionary property list from the specified section within the specified executable. | def readPlistFromToolSection(toolPath, segmentName, sectionName):
"""Reads a dictionary property list from the specified section within the specified executable."""
# Run otool -s to get a hex dump of the section.
args = [
# "false",
"otool",
"-s",
segmentName,
sect... | [
"def",
"readPlistFromToolSection",
"(",
"toolPath",
",",
"segmentName",
",",
"sectionName",
")",
":",
"# Run otool -s to get a hex dump of the section.",
"args",
"=",
"[",
"# \"false\",",
"\"otool\"",
",",
"\"-s\"",
",",
"segmentName",
",",
"sectionName",
",",
"toolPath... | [
128,
0
] | [
172,
16
] | python | en | ['en', 'en', 'en'] | True |
checkStep1 | (appPath) | Checks that the app and the tool are both correctly code signed. | Checks that the app and the tool are both correctly code signed. | def checkStep1(appPath):
"""Checks that the app and the tool are both correctly code signed."""
if not os.path.isdir(appPath):
raise CheckException("app not found", appPath)
# Check the app's code signature.
checkCodeSignature(appPath, "app")
# Check the tool directory.
toolDirPath ... | [
"def",
"checkStep1",
"(",
"appPath",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"appPath",
")",
":",
"raise",
"CheckException",
"(",
"\"app not found\"",
",",
"appPath",
")",
"# Check the app's code signature.",
"checkCodeSignature",
"(",
"appP... | [
174,
0
] | [
206,
23
] | python | en | ['en', 'en', 'en'] | True |
checkStep2 | (appPath, toolPathList) | Checks the SMPrivilegedExecutables entry in the app's "Info.plist". | Checks the SMPrivilegedExecutables entry in the app's "Info.plist". | def checkStep2(appPath, toolPathList):
"""Checks the SMPrivilegedExecutables entry in the app's "Info.plist"."""
# Create a map from the tool name (not path) to its designated requirement.
toolNameToReqMap = dict()
for toolPath in toolPathList:
req = readDesignatedRequirement(toolPath, "tool")... | [
"def",
"checkStep2",
"(",
"appPath",
",",
"toolPathList",
")",
":",
"# Create a map from the tool name (not path) to its designated requirement.",
"toolNameToReqMap",
"=",
"dict",
"(",
")",
"for",
"toolPath",
"in",
"toolPathList",
":",
"req",
"=",
"readDesignatedRequirement... | [
208,
0
] | [
248,
177
] | python | en | ['en', 'en', 'en'] | True |
checkStep3 | (appPath, toolPathList) | Checks the "Info.plist" embedded in each helper tool. | Checks the "Info.plist" embedded in each helper tool. | def checkStep3(appPath, toolPathList):
"""Checks the "Info.plist" embedded in each helper tool."""
# First get the app's designated requirement.
appReq = readDesignatedRequirement(appPath, "app")
# Then check that the tool's SMAuthorizedClients value matches it.
for toolPath in toolPathList:
... | [
"def",
"checkStep3",
"(",
"appPath",
",",
"toolPathList",
")",
":",
"# First get the app's designated requirement.",
"appReq",
"=",
"readDesignatedRequirement",
"(",
"appPath",
",",
"\"app\"",
")",
"# Then check that the tool's SMAuthorizedClients value matches it.",
"for",
"to... | [
250,
0
] | [
280,
157
] | python | en | ['en', 'fy', 'en'] | True |
checkStep4 | (appPath, toolPathList) | Checks the "launchd.plist" embedded in each helper tool. | Checks the "launchd.plist" embedded in each helper tool. | def checkStep4(appPath, toolPathList):
"""Checks the "launchd.plist" embedded in each helper tool."""
for toolPath in toolPathList:
launchd = readPlistFromToolSection(toolPath, "__TEXT", "__launchd_plist")
if not launchd.has_key("Label") or launchd["Label"] != os.path.basename(toolPath):
... | [
"def",
"checkStep4",
"(",
"appPath",
",",
"toolPathList",
")",
":",
"for",
"toolPath",
"in",
"toolPathList",
":",
"launchd",
"=",
"readPlistFromToolSection",
"(",
"toolPath",
",",
"\"__TEXT\"",
",",
"\"__launchd_plist\"",
")",
"if",
"not",
"launchd",
".",
"has_k... | [
282,
0
] | [
289,
115
] | python | en | ['en', 'gd', 'en'] | True |
checkStep5 | (appPath) | There's nothing to do here; we effectively checked for this is steps 1 and 2. | There's nothing to do here; we effectively checked for this is steps 1 and 2. | def checkStep5(appPath):
"""There's nothing to do here; we effectively checked for this is steps 1 and 2."""
pass | [
"def",
"checkStep5",
"(",
"appPath",
")",
":",
"pass"
] | [
295,
0
] | [
297,
8
] | python | en | ['en', 'en', 'en'] | True |
check | (appPath) | Checks the SMJobBless setup of the specified app. | Checks the SMJobBless setup of the specified app. | def check(appPath):
"""Checks the SMJobBless setup of the specified app."""
# Each of the following steps matches a bullet point in the SMJobBless header doc.
toolPathList = checkStep1(appPath)
checkStep2(appPath, toolPathList)
checkStep3(appPath, toolPathList)
checkStep4(appPath, toolPathL... | [
"def",
"check",
"(",
"appPath",
")",
":",
"# Each of the following steps matches a bullet point in the SMJobBless header doc.",
"toolPathList",
"=",
"checkStep1",
"(",
"appPath",
")",
"checkStep2",
"(",
"appPath",
",",
"toolPathList",
")",
"checkStep3",
"(",
"appPath",
",... | [
299,
0
] | [
312,
23
] | python | en | ['en', 'en', 'en'] | True |
setreq | (appPath, appInfoPlistPath, toolInfoPlistPaths) |
Reads information from the built app and uses it to set the SMJobBless setup
in the specified app and tool Info.plist source files.
|
Reads information from the built app and uses it to set the SMJobBless setup
in the specified app and tool Info.plist source files.
| def setreq(appPath, appInfoPlistPath, toolInfoPlistPaths):
"""
Reads information from the built app and uses it to set the SMJobBless setup
in the specified app and tool Info.plist source files.
"""
if not os.path.isdir(appPath):
raise CheckException("app not found", appPath)
if not os... | [
"def",
"setreq",
"(",
"appPath",
",",
"appInfoPlistPath",
",",
"toolInfoPlistPaths",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"appPath",
")",
":",
"raise",
"CheckException",
"(",
"\"app not found\"",
",",
"appPath",
")",
"if",
"not",
"o... | [
314,
0
] | [
395,
66
] | python | en | ['en', 'error', 'th'] | False |
main | (params, logger) | The main function. Sets up a chip and enters an interactive prompt
:param params: Command line arguments and chip options
:type params: dict
:param logger: The logger object for logging messages to the console
and file
:type logger: logging.Logger object
| The main function. Sets up a chip and enters an interactive prompt | def main(params, logger):
"""The main function. Sets up a chip and enters an interactive prompt
:param params: Command line arguments and chip options
:type params: dict
:param logger: The logger object for logging messages to the console
and file
:type logger: logging.Logger obj... | [
"def",
"main",
"(",
"params",
",",
"logger",
")",
":",
"params",
"[",
"'load_devram'",
"]",
"=",
"True",
"# always load DEVRAM",
"params",
"[",
"'load_trims'",
"]",
"=",
"TRIM_PATH",
"if",
"params",
"[",
"'trim'",
"]",
"else",
"None",
"logger",
".",
"info"... | [
41,
0
] | [
67,
19
] | python | en | ['en', 'en', 'en'] | True |
wrap_fp16_model | (model) | Wrap the FP32 model to FP16.
1. Convert FP32 model to FP16.
2. Remain some necessary layers to be FP32, e.g., normalization layers.
Args:
model (nn.Module): Model in FP32.
| Wrap the FP32 model to FP16. | def wrap_fp16_model(model):
"""Wrap the FP32 model to FP16.
1. Convert FP32 model to FP16.
2. Remain some necessary layers to be FP32, e.g., normalization layers.
Args:
model (nn.Module): Model in FP32.
"""
# convert model to fp16
model.half()
# patch the normalization layers t... | [
"def",
"wrap_fp16_model",
"(",
"model",
")",
":",
"# convert model to fp16",
"model",
".",
"half",
"(",
")",
"# patch the normalization layers to make it work in fp32 mode",
"patch_norm_fp32",
"(",
"model",
")",
"# set `fp16_enabled` flag",
"for",
"m",
"in",
"model",
".",... | [
107,
0
] | [
123,
33
] | python | en | ['en', 'en', 'en'] | True |
patch_norm_fp32 | (module) | Recursively convert normalization layers from FP16 to FP32.
Args:
module (nn.Module): The modules to be converted in FP16.
Returns:
nn.Module: The converted module, the normalization layers have been
converted to FP32.
| Recursively convert normalization layers from FP16 to FP32. | def patch_norm_fp32(module):
"""Recursively convert normalization layers from FP16 to FP32.
Args:
module (nn.Module): The modules to be converted in FP16.
Returns:
nn.Module: The converted module, the normalization layers have been
converted to FP32.
"""
if isinstance(m... | [
"def",
"patch_norm_fp32",
"(",
"module",
")",
":",
"if",
"isinstance",
"(",
"module",
",",
"(",
"_BatchNorm",
",",
"nn",
".",
"GroupNorm",
")",
")",
":",
"module",
".",
"float",
"(",
")",
"module",
".",
"forward",
"=",
"patch_forward_method",
"(",
"modul... | [
126,
0
] | [
142,
17
] | python | en | ['en', 'en', 'en'] | True |
patch_forward_method | (func, src_type, dst_type, convert_output=True) | Patch the forward method of a module.
Args:
func (callable): The original forward method.
src_type (torch.dtype): Type of input arguments to be converted from.
dst_type (torch.dtype): Type of input arguments to be converted to.
convert_output (bool): Whether to convert the output ba... | Patch the forward method of a module. | def patch_forward_method(func, src_type, dst_type, convert_output=True):
"""Patch the forward method of a module.
Args:
func (callable): The original forward method.
src_type (torch.dtype): Type of input arguments to be converted from.
dst_type (torch.dtype): Type of input arguments to ... | [
"def",
"patch_forward_method",
"(",
"func",
",",
"src_type",
",",
"dst_type",
",",
"convert_output",
"=",
"True",
")",
":",
"def",
"new_forward",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"output",
"=",
"func",
"(",
"*",
"cast_tensor_type",
"(... | [
145,
0
] | [
165,
22
] | python | en | ['en', 'en', 'en'] | True |
Fp16OptimizerHook.before_run | (self, runner) | Preparing steps before Mixed Precision Training.
1. Make a master copy of fp32 weights for optimization.
2. Convert the main model from fp32 to fp16.
Args:
runner (:obj:`mmcv.Runner`): The underlines training runner.
| Preparing steps before Mixed Precision Training. | def before_run(self, runner):
"""Preparing steps before Mixed Precision Training.
1. Make a master copy of fp32 weights for optimization.
2. Convert the main model from fp32 to fp16.
Args:
runner (:obj:`mmcv.Runner`): The underlines training runner.
"""
# ke... | [
"def",
"before_run",
"(",
"self",
",",
"runner",
")",
":",
"# keep a copy of fp32 weights",
"runner",
".",
"optimizer",
".",
"param_groups",
"=",
"copy",
".",
"deepcopy",
"(",
"runner",
".",
"optimizer",
".",
"param_groups",
")",
"# convert model to fp16",
"wrap_f... | [
39,
4
] | [
52,
37
] | python | en | ['it', 'en', 'en'] | True |
Fp16OptimizerHook.copy_grads_to_fp32 | (fp16_net, fp32_weights) | Copy gradients from fp16 model to fp32 weight copy. | Copy gradients from fp16 model to fp32 weight copy. | def copy_grads_to_fp32(fp16_net, fp32_weights):
"""Copy gradients from fp16 model to fp32 weight copy."""
for fp32_param, fp16_param in zip(fp32_weights, fp16_net.parameters()):
if fp16_param.grad is not None:
if fp32_param.grad is None:
fp32_param.grad = ... | [
"def",
"copy_grads_to_fp32",
"(",
"fp16_net",
",",
"fp32_weights",
")",
":",
"for",
"fp32_param",
",",
"fp16_param",
"in",
"zip",
"(",
"fp32_weights",
",",
"fp16_net",
".",
"parameters",
"(",
")",
")",
":",
"if",
"fp16_param",
".",
"grad",
"is",
"not",
"No... | [
55,
4
] | [
61,
54
] | python | en | ['en', 'en', 'en'] | True |
Fp16OptimizerHook.copy_params_to_fp16 | (fp16_net, fp32_weights) | Copy updated params from fp32 weight copy to fp16 model. | Copy updated params from fp32 weight copy to fp16 model. | def copy_params_to_fp16(fp16_net, fp32_weights):
"""Copy updated params from fp32 weight copy to fp16 model."""
for fp16_param, fp32_param in zip(fp16_net.parameters(), fp32_weights):
fp16_param.data.copy_(fp32_param.data) | [
"def",
"copy_params_to_fp16",
"(",
"fp16_net",
",",
"fp32_weights",
")",
":",
"for",
"fp16_param",
",",
"fp32_param",
"in",
"zip",
"(",
"fp16_net",
".",
"parameters",
"(",
")",
",",
"fp32_weights",
")",
":",
"fp16_param",
".",
"data",
".",
"copy_",
"(",
"f... | [
64,
4
] | [
67,
50
] | python | en | ['en', 'en', 'en'] | True |
Fp16OptimizerHook.after_train_iter | (self, runner) | Backward optimization steps for Mixed Precision Training.
1. Scale the loss by a scale factor.
2. Backward the loss to obtain the gradients (fp16).
3. Copy gradients from the model to the fp32 weight copy.
4. Scale the gradients back and update the fp32 weight copy.
5. Copy back... | Backward optimization steps for Mixed Precision Training. | def after_train_iter(self, runner):
"""Backward optimization steps for Mixed Precision Training.
1. Scale the loss by a scale factor.
2. Backward the loss to obtain the gradients (fp16).
3. Copy gradients from the model to the fp32 weight copy.
4. Scale the gradients back and up... | [
"def",
"after_train_iter",
"(",
"self",
",",
"runner",
")",
":",
"# clear grads of last iteration",
"runner",
".",
"model",
".",
"zero_grad",
"(",
")",
"runner",
".",
"optimizer",
".",
"zero_grad",
"(",
")",
"# scale the loss value",
"scaled_loss",
"=",
"runner",
... | [
69,
4
] | [
104,
60
] | python | en | ['en', 'en', 'en'] | True |
accuracy | (
preds: torch.Tensor,
target: torch.Tensor,
threshold: float = 0.5,
top_k: Optional[int] = None,
subset_accuracy: bool = False,
) | r"""Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`_:
.. math::
\text{Accuracy} = \frac{1}{N}\sum_i^N 1(y_i = \hat{y}_i)
Where :math:`y` is a tensor of target values, and :math:`\hat{y}` is a
tensor of predictions.
For multi-class and multi-dimensional multi-class d... | r"""Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`_: | def accuracy(
preds: torch.Tensor,
target: torch.Tensor,
threshold: float = 0.5,
top_k: Optional[int] = None,
subset_accuracy: bool = False,
) -> torch.Tensor:
r"""Computes `Accuracy <https://en.wikipedia.org/wiki/Accuracy_and_precision>`_:
.. math::
\text{Accuracy} = \frac{1}{N}\su... | [
"def",
"accuracy",
"(",
"preds",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
",",
"threshold",
":",
"float",
"=",
"0.5",
",",
"top_k",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"subset_accuracy",
":",
"bool",
"=... | [
50,
0
] | [
119,
44
] | python | de | ['de', 'en', 'it'] | False |
CpmBlock.forward | (self, x) | Model forward function. | Model forward function. | def forward(self, x):
"""Model forward function."""
out = self.model(x)
return out | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"out",
"=",
"self",
".",
"model",
"(",
"x",
")",
"return",
"out"
] | [
33,
4
] | [
36,
18
] | python | en | ['en', 'no', 'en'] | True |
rule_variable | (field_type, label=None, options=None) | Decorator to make a function into a rule variable | Decorator to make a function into a rule variable | def rule_variable(field_type, label=None, options=None):
"""Decorator to make a function into a rule variable"""
options = options or []
def wrapper(func):
if not (type(field_type) == type and issubclass(field_type, BaseType)):
raise AssertionError("{0} is not instance of BaseType in" "... | [
"def",
"rule_variable",
"(",
"field_type",
",",
"label",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"options",
"=",
"options",
"or",
"[",
"]",
"def",
"wrapper",
"(",
"func",
")",
":",
"if",
"not",
"(",
"type",
"(",
"field_type",
")",
"==",
... | [
28,
0
] | [
41,
18
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.on_gpu | (self) | Returns whether the current process is done on GPU | Returns whether the current process is done on GPU | def on_gpu(self) -> bool:
"""Returns whether the current process is done on GPU""" | [
"def",
"on_gpu",
"(",
"self",
")",
"->",
"bool",
":"
] | [
39,
4
] | [
40,
64
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.root_device | (self) | Returns the root device | Returns the root device | def root_device(self) -> torch.device:
"""Returns the root device""" | [
"def",
"root_device",
"(",
"self",
")",
"->",
"torch",
".",
"device",
":"
] | [
44,
4
] | [
45,
37
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.model_to_device | (self) | Moves the model to the correct device | Moves the model to the correct device | def model_to_device(self) -> None:
"""Moves the model to the correct device""" | [
"def",
"model_to_device",
"(",
"self",
")",
"->",
"None",
":"
] | [
48,
4
] | [
49,
51
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.is_global_zero | (self) | Whether the current process is the rank zero process not only on the local node, but for all nodes. | Whether the current process is the rank zero process not only on the local node, but for all nodes. | def is_global_zero(self) -> bool:
"""Whether the current process is the rank zero process not only on the local node, but for all nodes.""" | [
"def",
"is_global_zero",
"(",
"self",
")",
"->",
"bool",
":"
] | [
53,
4
] | [
54,
113
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.reduce | (self, tensor: Union[torch.Tensor, Any], *args: Any, **kwargs: Any) |
Reduces the given tensor (e.g. across GPUs/processes).
Args:
tensor: the tensor to sync and reduce
*args: plugin-specific positional arguments
**kwargs: plugin-specific keyword arguments
|
Reduces the given tensor (e.g. across GPUs/processes). | def reduce(self, tensor: Union[torch.Tensor, Any], *args: Any, **kwargs: Any) -> Union[torch.Tensor, Any]:
"""
Reduces the given tensor (e.g. across GPUs/processes).
Args:
tensor: the tensor to sync and reduce
*args: plugin-specific positional arguments
**kwa... | [
"def",
"reduce",
"(",
"self",
",",
"tensor",
":",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"Any",
"]",
",",
"*",
"args",
":",
"Any",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"Union",
"[",
"torch",
".",
"Tensor",
",",
"Any",
"]",
":"
] | [
57,
4
] | [
65,
11
] | python | en | ['en', 'error', 'th'] | False |
TrainingTypePlugin.barrier | (self, name: Optional[str] = None) | Forces all possibly joined processes to wait for each other | Forces all possibly joined processes to wait for each other | def barrier(self, name: Optional[str] = None) -> None:
"""Forces all possibly joined processes to wait for each other""" | [
"def",
"barrier",
"(",
"self",
",",
"name",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":"
] | [
68,
4
] | [
69,
73
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.broadcast | (self, obj: object, src: int = 0) | Broadcasts an object to all processes | Broadcasts an object to all processes | def broadcast(self, obj: object, src: int = 0) -> object:
"""Broadcasts an object to all processes""" | [
"def",
"broadcast",
"(",
"self",
",",
"obj",
":",
"object",
",",
"src",
":",
"int",
"=",
"0",
")",
"->",
"object",
":"
] | [
72,
4
] | [
73,
51
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.reduce_early_stopping_decision | (self, should_stop: bool) | Reduce the early stopping decision across all possibly spawned processes | Reduce the early stopping decision across all possibly spawned processes | def reduce_early_stopping_decision(self, should_stop: bool) -> bool:
"""Reduce the early stopping decision across all possibly spawned processes"""
return should_stop | [
"def",
"reduce_early_stopping_decision",
"(",
"self",
",",
"should_stop",
":",
"bool",
")",
"->",
"bool",
":",
"return",
"should_stop"
] | [
75,
4
] | [
77,
26
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.pre_backward | (self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int) | Run before precision plugin executes backward | Run before precision plugin executes backward | def pre_backward(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int):
"""Run before precision plugin executes backward""" | [
"def",
"pre_backward",
"(",
"self",
",",
"closure_loss",
":",
"torch",
".",
"Tensor",
",",
"should_accumulate",
":",
"bool",
",",
"optimizer",
":",
"Optimizer",
",",
"opt_idx",
":",
"int",
")",
":"
] | [
79,
4
] | [
80,
59
] | python | en | ['eu', 'gl', 'en'] | False |
TrainingTypePlugin.post_backward | (self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int) | Run after precision plugin executes backward | Run after precision plugin executes backward | def post_backward(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int):
"""Run after precision plugin executes backward""" | [
"def",
"post_backward",
"(",
"self",
",",
"closure_loss",
":",
"torch",
".",
"Tensor",
",",
"should_accumulate",
":",
"bool",
",",
"optimizer",
":",
"Optimizer",
",",
"opt_idx",
":",
"int",
")",
":"
] | [
82,
4
] | [
83,
58
] | python | en | ['ro', 'su', 'en'] | False |
TrainingTypePlugin.post_optimizer_step | (self, optimizer: Optimizer, optimizer_idx: int, **kwargs) | Hook to do something after each optimizer step. | Hook to do something after each optimizer step. | def post_optimizer_step(self, optimizer: Optimizer, optimizer_idx: int, **kwargs) -> None:
"""Hook to do something after each optimizer step.""" | [
"def",
"post_optimizer_step",
"(",
"self",
",",
"optimizer",
":",
"Optimizer",
",",
"optimizer_idx",
":",
"int",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":"
] | [
85,
4
] | [
86,
61
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.model | (self) | Returns the potentially wrapped LightningModule | Returns the potentially wrapped LightningModule | def model(self) -> Module:
"""Returns the potentially wrapped LightningModule"""
return self._model | [
"def",
"model",
"(",
"self",
")",
"->",
"Module",
":",
"return",
"self",
".",
"_model"
] | [
89,
4
] | [
91,
26
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.lightning_module | (self) | Returns the pure LightningModule without potential wrappers | Returns the pure LightningModule without potential wrappers | def lightning_module(self) -> Optional[LightningModule]:
"""Returns the pure LightningModule without potential wrappers"""
return unwrap_lightning_module(self._model) | [
"def",
"lightning_module",
"(",
"self",
")",
"->",
"Optional",
"[",
"LightningModule",
"]",
":",
"return",
"unwrap_lightning_module",
"(",
"self",
".",
"_model",
")"
] | [
98,
4
] | [
100,
51
] | python | en | ['en', 'en', 'en'] | True |
TrainingTypePlugin.results | (self) |
The results of the last training/testing run will be cached here.
In distributed training, we make sure to transfer the results to the appropriate master process.
|
The results of the last training/testing run will be cached here.
In distributed training, we make sure to transfer the results to the appropriate master process.
| def results(self) -> Any:
"""
The results of the last training/testing run will be cached here.
In distributed training, we make sure to transfer the results to the appropriate master process.
"""
# TODO: improve these docs
return self._results | [
"def",
"results",
"(",
"self",
")",
"->",
"Any",
":",
"# TODO: improve these docs",
"return",
"self",
".",
"_results"
] | [
103,
4
] | [
109,
28
] | python | en | ['en', 'error', 'th'] | False |
TrainingTypePlugin.process_dataloader | (self, dataloader: Union[Iterable, DataLoader]) | Wraps the dataloader if necessary
Args:
dataloader: iterable. Ideally of type: :class:`torch.utils.data.DataLoader`
| Wraps the dataloader if necessary | def process_dataloader(self, dataloader: Union[Iterable, DataLoader]) -> Union[Iterable, DataLoader]:
"""Wraps the dataloader if necessary
Args:
dataloader: iterable. Ideally of type: :class:`torch.utils.data.DataLoader`
"""
return dataloader | [
"def",
"process_dataloader",
"(",
"self",
",",
"dataloader",
":",
"Union",
"[",
"Iterable",
",",
"DataLoader",
"]",
")",
"->",
"Union",
"[",
"Iterable",
",",
"DataLoader",
"]",
":",
"return",
"dataloader"
] | [
154,
4
] | [
160,
25
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.__init__ | (self) | Create an instance of the HpDNN class. | Create an instance of the HpDNN class. | def __init__(self):
"""Create an instance of the HpDNN class."""
self.best_model = None
self.test_set = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"best_model",
"=",
"None",
"self",
".",
"test_set",
"=",
"None"
] | [
34,
4
] | [
37,
28
] | python | en | ['en', 'lb', 'en'] | True |
HpDNN.timed | (func) | Print the execution time for the decorated function. | Print the execution time for the decorated function. | def timed(func):
"""Print the execution time for the decorated function."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
logger.debug(
"{} ran in {}s".format(func._... | [
"def",
"timed",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"result",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",... | [
39,
4
] | [
52,
22
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.create_random_network | (
m: int,
n_classes: int,
metrics: str = "accuracy",
layers: tuple = (1, 5),
n: tuple = (10, 20),
activation: tuple = ("relu", "sigmoid"),
lr: tuple = (1e-5, 1e-3),
optimizer: keras.optimizers.Optimizer = keras.optimizers.Adam,
loss: str = "categor... | Return a deep neural network model with pseudo-random hyperparameters according to its arguments, each time it is called.
:param m: Number of input variables which will enter in the neural network
:type m: int
:param n_classes: Number of classes to be classificated
:type n_classes: int
... | Return a deep neural network model with pseudo-random hyperparameters according to its arguments, each time it is called. | def create_random_network(
m: int,
n_classes: int,
metrics: str = "accuracy",
layers: tuple = (1, 5),
n: tuple = (10, 20),
activation: tuple = ("relu", "sigmoid"),
lr: tuple = (1e-5, 1e-3),
optimizer: keras.optimizers.Optimizer = keras.optimizers.Adam,
... | [
"def",
"create_random_network",
"(",
"m",
":",
"int",
",",
"n_classes",
":",
"int",
",",
"metrics",
":",
"str",
"=",
"\"accuracy\"",
",",
"layers",
":",
"tuple",
"=",
"(",
"1",
",",
"5",
")",
",",
"n",
":",
"tuple",
"=",
"(",
"10",
",",
"20",
")"... | [
55,
4
] | [
118,
37
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.get_hyperparams | (
model: keras.models.Sequential,
) | Return the hyperparams of the model passed as an argument.
:param model: A keras.models.Sequential neural network model
:type model: keras.models.Sequential
:return: A tuple with a pandas Dataframe with the hyperparameters of the neural network and a pandas Dataframe with the parameters of the ... | Return the hyperparams of the model passed as an argument. | def get_hyperparams(
model: keras.models.Sequential,
) -> tuple((pd.DataFrame, pd.DataFrame)):
"""Return the hyperparams of the model passed as an argument.
:param model: A keras.models.Sequential neural network model
:type model: keras.models.Sequential
:return: A tuple wit... | [
"def",
"get_hyperparams",
"(",
"model",
":",
"keras",
".",
"models",
".",
"Sequential",
",",
")",
"->",
"tuple",
"(",
"(",
"pd",
".",
"DataFrame",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"neurons",
"=",
"[",
"]",
"activation",
"=",
"[",
"]",
"l... | [
121,
4
] | [
149,
31
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.split_history_metrics | (historial: list) | Transform the given list which contains the history results to a dictionary with the metrics organized.
:param historial: A list with the historical results of the trained model
:type historial: list
:return: A dictionary with the metrics obtained from the trained model
:rtype: dict
... | Transform the given list which contains the history results to a dictionary with the metrics organized. | def split_history_metrics(historial: list) -> dict:
"""Transform the given list which contains the history results to a dictionary with the metrics organized.
:param historial: A list with the historical results of the trained model
:type historial: list
:return: A dictionary with the m... | [
"def",
"split_history_metrics",
"(",
"historial",
":",
"list",
")",
"->",
"dict",
":",
"d",
"=",
"{",
"}",
"for",
"k",
"in",
"historial",
"[",
"0",
"]",
".",
"keys",
"(",
")",
":",
"d",
"[",
"k",
"]",
"=",
"[",
"d",
"[",
"k",
"]",
"for",
"d",... | [
152,
4
] | [
163,
16
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.perform_optimizing_DNN | (
self,
X: np.ndarray,
t: np.ndarray,
kfolds: int = 10,
train_size: float = 0.8,
trials: int = 5,
epochs: int = 50,
batch_size: int = 40,
metrics: tuple = (
"accuracy",
"Recall",
cm.specificity,
"Prec... | Train the current model using cross validation and register its score comparing with new ones in each trial.
:param X: Characteristic matrix numpy array of the dataset which will be evaluated
:type X: np.ndarray
:param t: Vector labels numpy array of the dataset which will be evaluated
... | Train the current model using cross validation and register its score comparing with new ones in each trial. | def perform_optimizing_DNN(
self,
X: np.ndarray,
t: np.ndarray,
kfolds: int = 10,
train_size: float = 0.8,
trials: int = 5,
epochs: int = 50,
batch_size: int = 40,
metrics: tuple = (
"accuracy",
"Recall",
cm.spec... | [
"def",
"perform_optimizing_DNN",
"(",
"self",
",",
"X",
":",
"np",
".",
"ndarray",
",",
"t",
":",
"np",
".",
"ndarray",
",",
"kfolds",
":",
"int",
"=",
"10",
",",
"train_size",
":",
"float",
"=",
"0.8",
",",
"trials",
":",
"int",
"=",
"5",
",",
"... | [
166,
4
] | [
278,
33
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.optimize_DNN | (self, *args, **kwargs) | Log the time of the perform_optimizing_DNN method.
:return: A tuple containing the return of the called function and its time log.
:rtype: tuple
| Log the time of the perform_optimizing_DNN method. | def optimize_DNN(self, *args, **kwargs) -> tuple:
"""Log the time of the perform_optimizing_DNN method.
:return: A tuple containing the return of the called function and its time log.
:rtype: tuple
"""
timeDNN_seq = self.perform_optimizing_DNN(*args, **kwargs)
return (se... | [
"def",
"optimize_DNN",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"tuple",
":",
"timeDNN_seq",
"=",
"self",
".",
"perform_optimizing_DNN",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"(",
"self",
".",
"best_model",... | [
280,
4
] | [
287,
60
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.perform_optimize_DNN_multithread | (
self,
X: np.ndarray,
t: np.ndarray,
kfolds: int = 10,
train_size: float = 0.8,
trials: int = 5,
epochs: int = 50,
batch_size: int = 40,
metrics: tuple = (
"accuracy",
"Recall",
cm.specificity,
"Prec... | Train the current model using cross validation and multithreading and register its score comparing with new ones in each trial.
:param X: Characteristic matrix numpy array of the dataset which will be evaluated
:type X: np.ndarray
:param t: Vector labels numpy array of the dataset which will be... | Train the current model using cross validation and multithreading and register its score comparing with new ones in each trial. | def perform_optimize_DNN_multithread(
self,
X: np.ndarray,
t: np.ndarray,
kfolds: int = 10,
train_size: float = 0.8,
trials: int = 5,
epochs: int = 50,
batch_size: int = 40,
metrics: tuple = (
"accuracy",
"Recall",
... | [
"def",
"perform_optimize_DNN_multithread",
"(",
"self",
",",
"X",
":",
"np",
".",
"ndarray",
",",
"t",
":",
"np",
".",
"ndarray",
",",
"kfolds",
":",
"int",
"=",
"10",
",",
"train_size",
":",
"float",
"=",
"0.8",
",",
"trials",
":",
"int",
"=",
"5",
... | [
290,
4
] | [
406,
33
] | python | en | ['en', 'en', 'en'] | True |
HpDNN.optimize_DNN_multithread | (self, *args, **kwargs) | Log the time of the perform_optimize_DNN_multithread method.
:return: A tuple containing the return of the called function and its time log.
:rtype: tuple
| Log the time of the perform_optimize_DNN_multithread method. | def optimize_DNN_multithread(self, *args, **kwargs) -> tuple:
"""Log the time of the perform_optimize_DNN_multithread method.
:return: A tuple containing the return of the called function and its time log.
:rtype: tuple
"""
timeDNN_thr = self.perform_optimize_DNN_multithread(*ar... | [
"def",
"optimize_DNN_multithread",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"tuple",
":",
"timeDNN_thr",
"=",
"self",
".",
"perform_optimize_DNN_multithread",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"(",
"self",
... | [
408,
4
] | [
415,
60
] | python | en | ['en', 'en', 'en'] | True |
search4 | () | Returns the results of a call to 'search4letters' to the browser. | Returns the results of a call to 'search4letters' to the browser. | def search4() -> str:
"""Returns the results of a call to 'search4letters' to the browser."""
return str(search4letters('life, the universe, and everything', 'xyz')) | [
"def",
"search4",
"(",
")",
"->",
"str",
":",
"return",
"str",
"(",
"search4letters",
"(",
"'life, the universe, and everything'",
",",
"'xyz'",
")",
")"
] | [
7,
0
] | [
9,
75
] | python | en | ['en', 'en', 'en'] | True |
entry_page | () | Returns the entry page to browser. | Returns the entry page to browser. | def entry_page() -> 'html':
"""Returns the entry page to browser."""
return render_template('entry.html',
the_title='Welcome to search4letters on the web!') | [
"def",
"entry_page",
"(",
")",
"->",
"'html'",
":",
"return",
"render_template",
"(",
"'entry.html'",
",",
"the_title",
"=",
"'Welcome to search4letters on the web!'",
")"
] | [
12,
0
] | [
15,
77
] | python | en | ['en', 'en', 'en'] | True |
BaseBackbone.init_weights | (self, pretrained=None) | Init backbone weights.
Args:
pretrained (str | None): If pretrained is a string, then it
initializes backbone weights by loading the pretrained
checkpoint. If pretrained is None, then it follows default
initializer or customized initializer in subclas... | Init backbone weights. | def init_weights(self, pretrained=None):
"""Init backbone weights.
Args:
pretrained (str | None): If pretrained is a string, then it
initializes backbone weights by loading the pretrained
checkpoint. If pretrained is None, then it follows default
... | [
"def",
"init_weights",
"(",
"self",
",",
"pretrained",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"pretrained",
",",
"str",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"load_checkpoint",
"(",
"self",
",",
"pretrained",
",",
"stri... | [
15,
4
] | [
32,
65
] | python | en | ['en', 'ne', 'en'] | True |
BaseBackbone.forward | (self, x) | Forward function.
Args:
x (tensor | tuple[tensor]): x could be a Torch.tensor or a tuple of
Torch.tensor, containing input data for forward computation.
| Forward function. | def forward(self, x):
"""Forward function.
Args:
x (tensor | tuple[tensor]): x could be a Torch.tensor or a tuple of
Torch.tensor, containing input data for forward computation.
""" | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":"
] | [
35,
4
] | [
41,
11
] | python | en | ['en', 'cy', 'en'] | False |
LightningOptimizer.toggle_model | (self, sync_grad: bool = True) |
This function is just a helper for advanced users.
Considering the current optimizer as A and all other optimizers as B.
Toggling means all parameters from B exclusive to A will have ``requires_grad`` set to False.
When performing gradient accumulation, there is no need to perform gr... |
This function is just a helper for advanced users. | def toggle_model(self, sync_grad: bool = True):
"""
This function is just a helper for advanced users.
Considering the current optimizer as A and all other optimizers as B.
Toggling means all parameters from B exclusive to A will have ``requires_grad`` set to False.
When perfo... | [
"def",
"toggle_model",
"(",
"self",
",",
"sync_grad",
":",
"bool",
"=",
"True",
")",
":",
"with",
"self",
".",
"_trainer",
".",
"train_loop",
".",
"block_ddp_sync_behaviour",
"(",
"not",
"sync_grad",
")",
":",
"self",
".",
"_toggle_model",
"(",
")",
"yield... | [
111,
4
] | [
126,
34
] | python | en | ['en', 'error', 'th'] | False |
LightningOptimizer.step | (self, *args, closure: Optional[Callable] = None, **kwargs) |
Call this directly from your training_step when doing optimizations manually.
By using this we can ensure that all the proper scaling when using 16-bit, accelerator etc
is been done properly for you.
.. note:: In Manual Optimization, the user is expected to know when to call zero_grad,... |
Call this directly from your training_step when doing optimizations manually.
By using this we can ensure that all the proper scaling when using 16-bit, accelerator etc
is been done properly for you. | def step(self, *args, closure: Optional[Callable] = None, **kwargs):
"""
Call this directly from your training_step when doing optimizations manually.
By using this we can ensure that all the proper scaling when using 16-bit, accelerator etc
is been done properly for you.
.. not... | [
"def",
"step",
"(",
"self",
",",
"*",
"args",
",",
"closure",
":",
"Optional",
"[",
"Callable",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"closure",
"is",
"None",
":",
"profiler_name",
"=",
"\"closure_{self._optimizer_idx}\"",
"closure",
... | [
140,
4
] | [
219,
45
] | python | en | ['en', 'error', 'th'] | False |
is_list | (text) | Validate whether the provided string can be converted to python list | Validate whether the provided string can be converted to python list | def is_list(text):
"""Validate whether the provided string can be converted to python list"""
text = text.strip()
try:
text_as_list = json.loads(text)
except ValueError:
logging.debug("Could not convert string to python object: {0}".format(text))
return False
return isinstan... | [
"def",
"is_list",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"try",
":",
"text_as_list",
"=",
"json",
".",
"loads",
"(",
"text",
")",
"except",
"ValueError",
":",
"logging",
".",
"debug",
"(",
"\"Could not convert string to python ... | [
14,
0
] | [
23,
41
] | python | en | ['en', 'en', 'en'] | True |
is_str | (text) | Validate whether the input is a non-blank python string | Validate whether the input is a non-blank python string | def is_str(text):
"""Validate whether the input is a non-blank python string"""
return isinstance(text, basestring) and len(text) > 0 | [
"def",
"is_str",
"(",
"text",
")",
":",
"return",
"isinstance",
"(",
"text",
",",
"basestring",
")",
"and",
"len",
"(",
"text",
")",
">",
"0"
] | [
26,
0
] | [
28,
57
] | python | en | ['en', 'en', 'en'] | True |
is_numeric | (text) | Validate whether the string represents a number (including unicode) | Validate whether the string represents a number (including unicode) | def is_numeric(text):
"""Validate whether the string represents a number (including unicode)"""
try:
float(text)
return True
except ValueError:
return False | [
"def",
"is_numeric",
"(",
"text",
")",
":",
"try",
":",
"float",
"(",
"text",
")",
"return",
"True",
"except",
"ValueError",
":",
"return",
"False"
] | [
31,
0
] | [
37,
20
] | python | en | ['en', 'en', 'en'] | True |
strip_attrs | (s) | Strip attributes of the form {.name} from a markdown title string | Strip attributes of the form {.name} from a markdown title string | def strip_attrs(s):
"""Strip attributes of the form {.name} from a markdown title string"""
return re.sub(r"\s\{\..*?\}", "", s) | [
"def",
"strip_attrs",
"(",
"s",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r\"\\s\\{\\..*?\\}\"",
",",
"\"\"",
",",
"s",
")"
] | [
41,
0
] | [
43,
40
] | python | en | ['en', 'en', 'en'] | True |
get_css_class | (s) | Return any and all CSS classes (when a line is suffixed by {.classname})
Returns empty list when | Return any and all CSS classes (when a line is suffixed by {.classname})
Returns empty list when | def get_css_class(s):
"""Return any and all CSS classes (when a line is suffixed by {.classname})
Returns empty list when """
return re.findall("\{\.(.*?)\}", s) | [
"def",
"get_css_class",
"(",
"s",
")",
":",
"return",
"re",
".",
"findall",
"(",
"\"\\{\\.(.*?)\\}\"",
",",
"s",
")"
] | [
46,
0
] | [
49,
39
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.get_doc_header_title | (self) | Helper method for SWC templates: get the document title from
the YAML headers | Helper method for SWC templates: get the document title from
the YAML headers | def get_doc_header_title(self):
"""Helper method for SWC templates: get the document title from
the YAML headers"""
doc_headers = self.data.children[1] # Throw index error if none found
for s in doc_headers.strings:
label, contents = s.split(":", 1)
if label.low... | [
"def",
"get_doc_header_title",
"(",
"self",
")",
":",
"doc_headers",
"=",
"self",
".",
"data",
".",
"children",
"[",
"1",
"]",
"# Throw index error if none found",
"for",
"s",
"in",
"doc_headers",
".",
"strings",
":",
"label",
",",
"contents",
"=",
"s",
".",... | [
60,
4
] | [
71,
17
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.get_doc_header_subtitle | (self) | Helper method for SWC templates: get the document title from
the YAML headers | Helper method for SWC templates: get the document title from
the YAML headers | def get_doc_header_subtitle(self):
"""Helper method for SWC templates: get the document title from
the YAML headers"""
doc_headers = self.data.children[1] # Throw index error if none found
for s in doc_headers.strings:
label, contents = s.split(":", 1)
if label.... | [
"def",
"get_doc_header_subtitle",
"(",
"self",
")",
":",
"doc_headers",
"=",
"self",
".",
"data",
".",
"children",
"[",
"1",
"]",
"# Throw index error if none found",
"for",
"s",
"in",
"doc_headers",
".",
"strings",
":",
"label",
",",
"contents",
"=",
"s",
"... | [
73,
4
] | [
84,
17
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.get_block_titled | (self, title, heading_level=2, ast_node=None) | Examine children. Return all children of the given node that:
a) are blockquoted elements, and
b) contain a heading with the specified text, at the specified level.
For example, this can be used to find the "Prerequisites" section
in index.md
Returns empty list if no appropr... | Examine children. Return all children of the given node that:
a) are blockquoted elements, and
b) contain a heading with the specified text, at the specified level.
For example, this can be used to find the "Prerequisites" section
in index.md | def get_block_titled(self, title, heading_level=2, ast_node=None):
"""Examine children. Return all children of the given node that:
a) are blockquoted elements, and
b) contain a heading with the specified text, at the specified level.
For example, this can be used to find the "Prerequisi... | [
"def",
"get_block_titled",
"(",
"self",
",",
"title",
",",
"heading_level",
"=",
"2",
",",
"ast_node",
"=",
"None",
")",
":",
"# TODO: Deprecate in favor of callout validator",
"if",
"ast_node",
"is",
"None",
":",
"ast_node",
"=",
"self",
".",
"data",
"return",
... | [
86,
4
] | [
104,
36
] | python | en | ['en', 'no', 'en'] | True |
CommonMarkHelper.get_section_headings | (self, ast_node=None) | Returns a list of ast nodes that are headings | Returns a list of ast nodes that are headings | def get_section_headings(self, ast_node=None):
"""Returns a list of ast nodes that are headings"""
if ast_node is None:
ast_node = self.data
return [n for n in ast_node.children if self.is_heading(n)] | [
"def",
"get_section_headings",
"(",
"self",
",",
"ast_node",
"=",
"None",
")",
":",
"if",
"ast_node",
"is",
"None",
":",
"ast_node",
"=",
"self",
".",
"data",
"return",
"[",
"n",
"for",
"n",
"in",
"ast_node",
".",
"children",
"if",
"self",
".",
"is_hea... | [
107,
4
] | [
111,
67
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.find_external_links | (self, ast_node=None, parent_crit=None) | Recursive function that locates all references to external content
under specified node. (links or images) | Recursive function that locates all references to external content
under specified node. (links or images) | def find_external_links(self, ast_node=None, parent_crit=None):
"""Recursive function that locates all references to external content
under specified node. (links or images)"""
ast_node = ast_node or self.data
if parent_crit is None:
# User can optionally provide a function ... | [
"def",
"find_external_links",
"(",
"self",
",",
"ast_node",
"=",
"None",
",",
"parent_crit",
"=",
"None",
")",
":",
"ast_node",
"=",
"ast_node",
"or",
"self",
".",
"data",
"if",
"parent_crit",
"is",
"None",
":",
"# User can optionally provide a function to filter ... | [
118,
4
] | [
140,
20
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.get_link_info | (self, link_node) | Given a link node, return the link title and destination | Given a link node, return the link title and destination | def get_link_info(self, link_node):
"""Given a link node, return the link title and destination"""
if not self.is_external(link_node):
raise TypeError("Cannot apply this method to something that is not a link")
dest = link_node.destination
try:
link_text = link_n... | [
"def",
"get_link_info",
"(",
"self",
",",
"link_node",
")",
":",
"if",
"not",
"self",
".",
"is_external",
"(",
"link_node",
")",
":",
"raise",
"TypeError",
"(",
"\"Cannot apply this method to something that is not a link\"",
")",
"dest",
"=",
"link_node",
".",
"de... | [
143,
4
] | [
154,
30
] | python | en | ['en', 'da', 'en'] | True |
CommonMarkHelper.get_heading_info | (self, heading_node) | Get heading text and list of all css styles applied | Get heading text and list of all css styles applied | def get_heading_info(self, heading_node):
"""Get heading text and list of all css styles applied"""
heading = heading_node.strings[0]
text = strip_attrs(heading)
css = get_css_class(heading)
return text, css | [
"def",
"get_heading_info",
"(",
"self",
",",
"heading_node",
")",
":",
"heading",
"=",
"heading_node",
".",
"strings",
"[",
"0",
"]",
"text",
"=",
"strip_attrs",
"(",
"heading",
")",
"css",
"=",
"get_css_class",
"(",
"heading",
")",
"return",
"text",
",",
... | [
156,
4
] | [
161,
24
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.has_section_heading | (self, section_title, ast_node=None,
heading_level=2, limit=sys.maxsize, show_msg=True) | Does the section contain (<= x copies of) specified heading text?
Will strip off any CSS attributes when looking for the section title | Does the section contain (<= x copies of) specified heading text?
Will strip off any CSS attributes when looking for the section title | def has_section_heading(self, section_title, ast_node=None,
heading_level=2, limit=sys.maxsize, show_msg=True):
"""Does the section contain (<= x copies of) specified heading text?
Will strip off any CSS attributes when looking for the section title"""
if ast_node is ... | [
"def",
"has_section_heading",
"(",
"self",
",",
"section_title",
",",
"ast_node",
"=",
"None",
",",
"heading_level",
"=",
"2",
",",
"limit",
"=",
"sys",
".",
"maxsize",
",",
"show_msg",
"=",
"True",
")",
":",
"if",
"ast_node",
"is",
"None",
":",
"ast_nod... | [
164,
4
] | [
185,
39
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.has_number_children | (self, ast_node,
exact=None, minc=0, maxc=sys.maxsize) | Does the specified node (such as a bulleted list) have the expected
number of children? | Does the specified node (such as a bulleted list) have the expected
number of children? | def has_number_children(self, ast_node,
exact=None, minc=0, maxc=sys.maxsize):
"""Does the specified node (such as a bulleted list) have the expected
number of children?"""
if exact: # If specified, must have exactly this number of children
minc = maxc ... | [
"def",
"has_number_children",
"(",
"self",
",",
"ast_node",
",",
"exact",
"=",
"None",
",",
"minc",
"=",
"0",
",",
"maxc",
"=",
"sys",
".",
"maxsize",
")",
":",
"if",
"exact",
":",
"# If specified, must have exactly this number of children",
"minc",
"=",
"maxc... | [
187,
4
] | [
195,
55
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_hr | (self, ast_node) | Is the node a horizontal rule (hr)? | Is the node a horizontal rule (hr)? | def is_hr(self, ast_node):
"""Is the node a horizontal rule (hr)?"""
return ast_node.t == 'HorizontalRule' | [
"def",
"is_hr",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"==",
"'HorizontalRule'"
] | [
198,
4
] | [
200,
45
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_heading | (self, ast_node, heading_level=None) | Is the node a heading/ title? | Is the node a heading/ title? | def is_heading(self, ast_node, heading_level=None):
"""Is the node a heading/ title?"""
has_tag = ast_node.t == "ATXHeader"
if heading_level is None:
has_level = True
else:
has_level = (ast_node.level == heading_level)
return has_tag and has_level | [
"def",
"is_heading",
"(",
"self",
",",
"ast_node",
",",
"heading_level",
"=",
"None",
")",
":",
"has_tag",
"=",
"ast_node",
".",
"t",
"==",
"\"ATXHeader\"",
"if",
"heading_level",
"is",
"None",
":",
"has_level",
"=",
"True",
"else",
":",
"has_level",
"=",
... | [
202,
4
] | [
210,
36
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_paragraph | (self, ast_node) | Is the node a paragraph? | Is the node a paragraph? | def is_paragraph(self, ast_node):
"""Is the node a paragraph?"""
return ast_node.t == "Paragraph" | [
"def",
"is_paragraph",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"==",
"\"Paragraph\""
] | [
212,
4
] | [
214,
40
] | python | en | ['en', 'fr', 'en'] | True |
CommonMarkHelper.is_list | (self, ast_node) | Is the node a list? (ordered or unordered) | Is the node a list? (ordered or unordered) | def is_list(self, ast_node):
"""Is the node a list? (ordered or unordered)"""
return ast_node.t == "List" | [
"def",
"is_list",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"==",
"\"List\""
] | [
216,
4
] | [
218,
35
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_link | (self, ast_node) | Is the node a link? | Is the node a link? | def is_link(self, ast_node):
"""Is the node a link?"""
return ast_node.t == "Link" | [
"def",
"is_link",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"==",
"\"Link\""
] | [
220,
4
] | [
222,
35
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_external | (self, ast_node) | Does the node reference content outside the file? (image or link) | Does the node reference content outside the file? (image or link) | def is_external(self, ast_node):
"""Does the node reference content outside the file? (image or link)"""
return ast_node.t in ("Link", "Image") | [
"def",
"is_external",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"in",
"(",
"\"Link\"",
",",
"\"Image\"",
")"
] | [
224,
4
] | [
226,
46
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_block | (self, ast_node) | Is the node a BlockQuoted element? | Is the node a BlockQuoted element? | def is_block(self, ast_node):
"""Is the node a BlockQuoted element?"""
return ast_node.t == "BlockQuote" | [
"def",
"is_block",
"(",
"self",
",",
"ast_node",
")",
":",
"return",
"ast_node",
".",
"t",
"==",
"\"BlockQuote\""
] | [
228,
4
] | [
230,
41
] | python | en | ['en', 'en', 'en'] | True |
CommonMarkHelper.is_callout | (self, ast_node) | Composite element: "callout" elements in SWC templates are
blockquotes whose first child element is a heading | Composite element: "callout" elements in SWC templates are
blockquotes whose first child element is a heading | def is_callout(self, ast_node):
"""Composite element: "callout" elements in SWC templates are
blockquotes whose first child element is a heading"""
if len(ast_node.children) > 0 and \
self.is_heading(ast_node.children[0]):
has_heading = True
else:
... | [
"def",
"is_callout",
"(",
"self",
",",
"ast_node",
")",
":",
"if",
"len",
"(",
"ast_node",
".",
"children",
")",
">",
"0",
"and",
"self",
".",
"is_heading",
"(",
"ast_node",
".",
"children",
"[",
"0",
"]",
")",
":",
"has_heading",
"=",
"True",
"else"... | [
232,
4
] | [
241,
54
] | python | en | ['en', 'en', 'en'] | True |
UsersConfig.ready | (self) | Override this to put in:
Users system checks
Users signal registration
| Override this to put in:
Users system checks
Users signal registration
| def ready(self):
"""Override this to put in:
Users system checks
Users signal registration
"""
from .signals import user_signed_up | [
"def",
"ready",
"(",
"self",
")",
":",
"from",
".",
"signals",
"import",
"user_signed_up"
] | [
7,
4
] | [
13,
43
] | python | en | ['en', 'en', 'en'] | True |
OrphanSnapshotCleaner.get_owner_id | (self, images_json) | Return AWS owner id from a ami json list | Return AWS owner id from a ami json list | def get_owner_id(self, images_json):
""" Return AWS owner id from a ami json list """
images = images_json or []
if not images:
return None
return images[0].get("OwnerId", "") | [
"def",
"get_owner_id",
"(",
"self",
",",
"images_json",
")",
":",
"images",
"=",
"images_json",
"or",
"[",
"]",
"if",
"not",
"images",
":",
"return",
"None",
"return",
"images",
"[",
"0",
"]",
".",
"get",
"(",
"\"OwnerId\"",
",",
"\"\"",
")"
] | [
36,
4
] | [
45,
43
] | python | en | ['en', 'en', 'en'] | True |
OrphanSnapshotCleaner.fetch | (self) | retrieve orphan snapshots | retrieve orphan snapshots | def fetch(self):
""" retrieve orphan snapshots """
resp = self.ec2.describe_images(Owners=['self'])
used_snaps = [
ebs.get("Ebs", {}).get("SnapshotId")
for image in resp.get("Images")
for ebs in image.get("BlockDeviceMappings")
]
snap_filter... | [
"def",
"fetch",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"ec2",
".",
"describe_images",
"(",
"Owners",
"=",
"[",
"'self'",
"]",
")",
"used_snaps",
"=",
"[",
"ebs",
".",
"get",
"(",
"\"Ebs\"",
",",
"{",
"}",
")",
".",
"get",
"(",
"\"Snapsh... | [
47,
4
] | [
70,
53
] | python | en | ['en', 'zh', 'en'] | True |
OrphanSnapshotCleaner.clean | (self, snapshots) |
actually deletes the snapshots with an array
of snapshots ids
|
actually deletes the snapshots with an array
of snapshots ids
| def clean(self, snapshots):
"""
actually deletes the snapshots with an array
of snapshots ids
"""
count = len(snapshots)
snapshots = snapshots or []
for snap in snapshots:
try:
self.ec2.delete_snapshot(SnapshotId=snap)
ex... | [
"def",
"clean",
"(",
"self",
",",
"snapshots",
")",
":",
"count",
"=",
"len",
"(",
"snapshots",
")",
"snapshots",
"=",
"snapshots",
"or",
"[",
"]",
"for",
"snap",
"in",
"snapshots",
":",
"try",
":",
"self",
".",
"ec2",
".",
"delete_snapshot",
"(",
"S... | [
72,
4
] | [
89,
20
] | python | en | ['en', 'error', 'th'] | False |
AMICleaner.get_ami_sorting_key | (ami) | return a key for sorting array of AMIs | return a key for sorting array of AMIs | def get_ami_sorting_key(ami):
""" return a key for sorting array of AMIs """
return ami.creation_date | [
"def",
"get_ami_sorting_key",
"(",
"ami",
")",
":",
"return",
"ami",
".",
"creation_date"
] | [
101,
4
] | [
105,
32
] | python | en | ['en', 'en', 'en'] | True |
AMICleaner.remove_amis | (self, amis) |
deregister AMIs (array) and removes related snapshots
:param amis: array of AMI objects
|
deregister AMIs (array) and removes related snapshots
:param amis: array of AMI objects
| def remove_amis(self, amis):
"""
deregister AMIs (array) and removes related snapshots
:param amis: array of AMI objects
"""
failed_snapshots = []
amis = amis or []
for ami in amis:
self.ec2.deregister_image(ImageId=ami.id)
print("{0} de... | [
"def",
"remove_amis",
"(",
"self",
",",
"amis",
")",
":",
"failed_snapshots",
"=",
"[",
"]",
"amis",
"=",
"amis",
"or",
"[",
"]",
"for",
"ami",
"in",
"amis",
":",
"self",
".",
"ec2",
".",
"deregister_image",
"(",
"ImageId",
"=",
"ami",
".",
"id",
"... | [
107,
4
] | [
130,
31
] | python | en | ['en', 'error', 'th'] | False |
AMICleaner.remove_amis_from_ids | (self, ami_ids) |
takes a list of AMI ids, verify on aws and removes them
:param ami_ids: array of AMI ids
|
takes a list of AMI ids, verify on aws and removes them
:param ami_ids: array of AMI ids
| def remove_amis_from_ids(self, ami_ids):
"""
takes a list of AMI ids, verify on aws and removes them
:param ami_ids: array of AMI ids
"""
if not ami_ids:
return False
my_custom_images = self.ec2.describe_images(
Owners=['self'],
Imag... | [
"def",
"remove_amis_from_ids",
"(",
"self",
",",
"ami_ids",
")",
":",
"if",
"not",
"ami_ids",
":",
"return",
"False",
"my_custom_images",
"=",
"self",
".",
"ec2",
".",
"describe_images",
"(",
"Owners",
"=",
"[",
"'self'",
"]",
",",
"ImageIds",
"=",
"ami_id... | [
132,
4
] | [
151,
37
] | python | en | ['en', 'error', 'th'] | False |
AMICleaner.map_candidates | (self, candidates_amis=None, mapping_strategy=None) |
Given a dict of AMIs to clean, and a mapping strategy (see config.py),
this function returns a dict of grouped amis with the mapping strategy
name as a key.
example :
mapping_strategy = {"key": "name", "values": ["ubuntu", "debian"]}
or
mapping_strategy = {"key"... |
Given a dict of AMIs to clean, and a mapping strategy (see config.py),
this function returns a dict of grouped amis with the mapping strategy
name as a key. | def map_candidates(self, candidates_amis=None, mapping_strategy=None):
"""
Given a dict of AMIs to clean, and a mapping strategy (see config.py),
this function returns a dict of grouped amis with the mapping strategy
name as a key.
example :
mapping_strategy = {"key": "... | [
"def",
"map_candidates",
"(",
"self",
",",
"candidates_amis",
"=",
"None",
",",
"mapping_strategy",
"=",
"None",
")",
":",
"if",
"not",
"candidates_amis",
":",
"return",
"{",
"}",
"mapping_strategy",
"=",
"mapping_strategy",
"or",
"{",
"}",
"if",
"not",
"map... | [
153,
4
] | [
215,
29
] | python | en | ['en', 'error', 'th'] | False |
AMICleaner.tags_values_to_string | (tags, filters=None) |
filters tags(key,value) array and return a string with tags values
:tags is an array of AWSTag objects
|
filters tags(key,value) array and return a string with tags values
:tags is an array of AWSTag objects
| def tags_values_to_string(tags, filters=None):
"""
filters tags(key,value) array and return a string with tags values
:tags is an array of AWSTag objects
"""
if tags is None:
return None
tag_values = []
filters = filters or []
filters_to_str... | [
"def",
"tags_values_to_string",
"(",
"tags",
",",
"filters",
"=",
"None",
")",
":",
"if",
"tags",
"is",
"None",
":",
"return",
"None",
"tag_values",
"=",
"[",
"]",
"filters",
"=",
"filters",
"or",
"[",
"]",
"filters_to_string",
"=",
"\".\"",
".",
"join",... | [
218,
4
] | [
238,
43
] | 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.