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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
DataCriterion.string_to_config | (crit_config) |
Parse string like "avg-rt of label>100ms for 1m, continue as non-failed"
into config dict
:type crit_config: str
:rtype: dict
|
Parse string like "avg-rt of label>100ms for 1m, continue as non-failed"
into config dict | def string_to_config(crit_config):
"""
Parse string like "avg-rt of label>100ms for 1m, continue as non-failed"
into config dict
:type crit_config: str
:rtype: dict
"""
res = BetterDict.from_dict({
"subject": None,
"condition": None,
... | [
"def",
"string_to_config",
"(",
"crit_config",
")",
":",
"res",
"=",
"BetterDict",
".",
"from_dict",
"(",
"{",
"\"subject\"",
":",
"None",
",",
"\"condition\"",
":",
"None",
",",
"\"threshold\"",
":",
"None",
",",
"\"logic\"",
":",
"\"for\"",
",",
"\"timefra... | [
407,
4
] | [
462,
18
] | python | en | ['en', 'error', 'th'] | False |
PassFailWidget.__prepare_colors | (self) |
returns tuple ("color", text)
:return:
|
returns tuple ("color", text)
:return:
| def __prepare_colors(self):
"""
returns tuple ("color", text)
:return:
"""
result = []
for failing_criterion in self.failing_criteria:
if failing_criterion.window:
percent = failing_criterion.get_counting() / failing_criterion.window
... | [
"def",
"__prepare_colors",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"failing_criterion",
"in",
"self",
".",
"failing_criteria",
":",
"if",
"failing_criterion",
".",
"window",
":",
"percent",
"=",
"failing_criterion",
".",
"get_counting",
"(",
")"... | [
480,
4
] | [
500,
21
] | python | en | ['en', 'error', 'th'] | False |
PassFailWidget.update | (self) |
updates widget text
:return:
|
updates widget text
:return:
| def update(self):
"""
updates widget text
:return:
"""
self.text_widget.set_text("")
self.failing_criteria = [x for x in self.pass_fail_reporter.criteria if x.get_counting() > 0]
if self.failing_criteria:
widget_text = self.__prepare_colors()
... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"text_widget",
".",
"set_text",
"(",
"\"\"",
")",
"self",
".",
"failing_criteria",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"pass_fail_reporter",
".",
"criteria",
"if",
"x",
".",
"get_counting",
... | [
502,
4
] | [
512,
26
] | python | en | ['en', 'error', 'th'] | False |
split_dep | (dep) |
Split NOT character '!' from dependency. Used by gen_dependencies()
:param dep: Dependency list
:return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
MACRO.
|
Split NOT character '!' from dependency. Used by gen_dependencies() | def split_dep(dep):
"""
Split NOT character '!' from dependency. Used by gen_dependencies()
:param dep: Dependency list
:return: string tuple. Ex: ('!', MACRO) for !MACRO and ('', MACRO) for
MACRO.
"""
return ('!', dep[1:]) if dep[0] == '!' else ('', dep) | [
"def",
"split_dep",
"(",
"dep",
")",
":",
"return",
"(",
"'!'",
",",
"dep",
"[",
"1",
":",
"]",
")",
"if",
"dep",
"[",
"0",
"]",
"==",
"'!'",
"else",
"(",
"''",
",",
"dep",
")"
] | [
260,
0
] | [
268,
57
] | python | en | ['en', 'error', 'th'] | False |
gen_dependencies | (dependencies) |
Test suite data and functions specifies compile time dependencies.
This function generates C preprocessor code from the input
dependency list. Caller uses the generated preprocessor code to
wrap dependent code.
A dependency in the input list can have a leading '!' character
to negate a conditio... |
Test suite data and functions specifies compile time dependencies.
This function generates C preprocessor code from the input
dependency list. Caller uses the generated preprocessor code to
wrap dependent code.
A dependency in the input list can have a leading '!' character
to negate a conditio... | def gen_dependencies(dependencies):
"""
Test suite data and functions specifies compile time dependencies.
This function generates C preprocessor code from the input
dependency list. Caller uses the generated preprocessor code to
wrap dependent code.
A dependency in the input list can have a lea... | [
"def",
"gen_dependencies",
"(",
"dependencies",
")",
":",
"dep_start",
"=",
"''",
".",
"join",
"(",
"[",
"'#if %sdefined(%s)\\n'",
"%",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in",
"map",
"(",
"split_dep",
",",
"dependencies",
")",
"]",
")",
... | [
271,
0
] | [
291,
29
] | python | en | ['en', 'error', 'th'] | False |
gen_dependencies_one_line | (dependencies) |
Similar to gen_dependencies() but generates dependency checks in one line.
Useful for generating code with #else block.
:param dependencies: List of dependencies.
:return: Preprocessor check code
|
Similar to gen_dependencies() but generates dependency checks in one line.
Useful for generating code with #else block. | def gen_dependencies_one_line(dependencies):
"""
Similar to gen_dependencies() but generates dependency checks in one line.
Useful for generating code with #else block.
:param dependencies: List of dependencies.
:return: Preprocessor check code
"""
defines = '#if ' if dependencies else ''
... | [
"def",
"gen_dependencies_one_line",
"(",
"dependencies",
")",
":",
"defines",
"=",
"'#if '",
"if",
"dependencies",
"else",
"''",
"defines",
"+=",
"' && '",
".",
"join",
"(",
"[",
"'%sdefined(%s)'",
"%",
"(",
"x",
",",
"y",
")",
"for",
"x",
",",
"y",
"in"... | [
294,
0
] | [
305,
18
] | python | en | ['en', 'error', 'th'] | False |
gen_function_wrapper | (name, local_vars, args_dispatch) |
Creates test function wrapper code. A wrapper has the code to
unpack parameters from parameters[] array.
:param name: Test function name
:param local_vars: Local variables declaration code
:param args_dispatch: List of dispatch arguments.
Ex: ['(char *)params[0]', '*((int *)params[1])']... |
Creates test function wrapper code. A wrapper has the code to
unpack parameters from parameters[] array. | def gen_function_wrapper(name, local_vars, args_dispatch):
"""
Creates test function wrapper code. A wrapper has the code to
unpack parameters from parameters[] array.
:param name: Test function name
:param local_vars: Local variables declaration code
:param args_dispatch: List of dispatch argu... | [
"def",
"gen_function_wrapper",
"(",
"name",
",",
"local_vars",
",",
"args_dispatch",
")",
":",
"# Then create the wrapper",
"wrapper",
"=",
"'''\nvoid {name}_wrapper( void ** params )\n{{\n{unused_params}{locals}\n {name}( {args} );\n}}\n'''",
".",
"format",
"(",
"name",
"=",
... | [
308,
0
] | [
330,
18
] | python | en | ['en', 'error', 'th'] | False |
gen_dispatch | (name, dependencies) |
Test suite code template main_test.function defines a C function
array to contain test case functions. This function generates an
initializer entry for a function in that array. The entry is
composed of a compile time check for the test function
dependencies. At compile time the test function is as... |
Test suite code template main_test.function defines a C function
array to contain test case functions. This function generates an
initializer entry for a function in that array. The entry is
composed of a compile time check for the test function
dependencies. At compile time the test function is as... | def gen_dispatch(name, dependencies):
"""
Test suite code template main_test.function defines a C function
array to contain test case functions. This function generates an
initializer entry for a function in that array. The entry is
composed of a compile time check for the test function
dependen... | [
"def",
"gen_dispatch",
"(",
"name",
",",
"dependencies",
")",
":",
"if",
"dependencies",
":",
"preprocessor_check",
"=",
"gen_dependencies_one_line",
"(",
"dependencies",
")",
"dispatch_code",
"=",
"'''\n{preprocessor_check}\n {name}_wrapper,\n#else\n NULL,\n#endif\n'''",... | [
333,
0
] | [
360,
24
] | python | en | ['en', 'error', 'th'] | False |
parse_until_pattern | (funcs_f, end_regex) |
Matches pattern end_regex to the lines read from the file object.
Returns the lines read until end pattern is matched.
:param funcs_f: file object for .function file
:param end_regex: Pattern to stop parsing
:return: Lines read before the end pattern
|
Matches pattern end_regex to the lines read from the file object.
Returns the lines read until end pattern is matched. | def parse_until_pattern(funcs_f, end_regex):
"""
Matches pattern end_regex to the lines read from the file object.
Returns the lines read until end pattern is matched.
:param funcs_f: file object for .function file
:param end_regex: Pattern to stop parsing
:return: Lines read before the end pat... | [
"def",
"parse_until_pattern",
"(",
"funcs_f",
",",
"end_regex",
")",
":",
"headers",
"=",
"'#line %d \"%s\"\\n'",
"%",
"(",
"funcs_f",
".",
"line_no",
"+",
"1",
",",
"funcs_f",
".",
"name",
")",
"for",
"line",
"in",
"funcs_f",
":",
"if",
"re",
".",
"sear... | [
363,
0
] | [
381,
18
] | python | en | ['en', 'error', 'th'] | False |
validate_dependency | (dependency) |
Validates a C macro and raises GeneratorInputError on invalid input.
:param dependency: Input macro dependency
:return: input dependency stripped of leading & trailing white spaces.
|
Validates a C macro and raises GeneratorInputError on invalid input.
:param dependency: Input macro dependency
:return: input dependency stripped of leading & trailing white spaces.
| def validate_dependency(dependency):
"""
Validates a C macro and raises GeneratorInputError on invalid input.
:param dependency: Input macro dependency
:return: input dependency stripped of leading & trailing white spaces.
"""
dependency = dependency.strip()
if not re.match(CONDITION_REGEX, ... | [
"def",
"validate_dependency",
"(",
"dependency",
")",
":",
"dependency",
"=",
"dependency",
".",
"strip",
"(",
")",
"if",
"not",
"re",
".",
"match",
"(",
"CONDITION_REGEX",
",",
"dependency",
",",
"re",
".",
"I",
")",
":",
"raise",
"GeneratorInputError",
"... | [
384,
0
] | [
393,
21
] | python | en | ['en', 'error', 'th'] | False |
parse_dependencies | (inp_str) |
Parses dependencies out of inp_str, validates them and returns a
list of macros.
:param inp_str: Input string with macros delimited by ':'.
:return: list of dependencies
|
Parses dependencies out of inp_str, validates them and returns a
list of macros. | def parse_dependencies(inp_str):
"""
Parses dependencies out of inp_str, validates them and returns a
list of macros.
:param inp_str: Input string with macros delimited by ':'.
:return: list of dependencies
"""
dependencies = [dep for dep in map(validate_dependency,
... | [
"def",
"parse_dependencies",
"(",
"inp_str",
")",
":",
"dependencies",
"=",
"[",
"dep",
"for",
"dep",
"in",
"map",
"(",
"validate_dependency",
",",
"inp_str",
".",
"split",
"(",
"':'",
")",
")",
"]",
"return",
"dependencies"
] | [
396,
0
] | [
406,
23
] | python | en | ['en', 'error', 'th'] | False |
parse_suite_dependencies | (funcs_f) |
Parses test suite dependencies specified at the top of a
.function file, that starts with pattern BEGIN_DEPENDENCIES
and end with END_DEPENDENCIES. Dependencies are specified
after pattern 'depends_on:' and are delimited by ':'.
:param funcs_f: file object for .function file
:return: List of t... |
Parses test suite dependencies specified at the top of a
.function file, that starts with pattern BEGIN_DEPENDENCIES
and end with END_DEPENDENCIES. Dependencies are specified
after pattern 'depends_on:' and are delimited by ':'. | def parse_suite_dependencies(funcs_f):
"""
Parses test suite dependencies specified at the top of a
.function file, that starts with pattern BEGIN_DEPENDENCIES
and end with END_DEPENDENCIES. Dependencies are specified
after pattern 'depends_on:' and are delimited by ':'.
:param funcs_f: file ob... | [
"def",
"parse_suite_dependencies",
"(",
"funcs_f",
")",
":",
"dependencies",
"=",
"[",
"]",
"for",
"line",
"in",
"funcs_f",
":",
"match",
"=",
"re",
".",
"search",
"(",
"DEPENDENCY_REGEX",
",",
"line",
".",
"strip",
"(",
")",
")",
"if",
"match",
":",
"... | [
409,
0
] | [
435,
23
] | python | en | ['en', 'error', 'th'] | False |
parse_function_dependencies | (line) |
Parses function dependencies, that are in the same line as
comment BEGIN_CASE. Dependencies are specified after pattern
'depends_on:' and are delimited by ':'.
:param line: Line from .function file that has dependencies.
:return: List of dependencies.
|
Parses function dependencies, that are in the same line as
comment BEGIN_CASE. Dependencies are specified after pattern
'depends_on:' and are delimited by ':'. | def parse_function_dependencies(line):
"""
Parses function dependencies, that are in the same line as
comment BEGIN_CASE. Dependencies are specified after pattern
'depends_on:' and are delimited by ':'.
:param line: Line from .function file that has dependencies.
:return: List of dependencies.
... | [
"def",
"parse_function_dependencies",
"(",
"line",
")",
":",
"dependencies",
"=",
"[",
"]",
"match",
"=",
"re",
".",
"search",
"(",
"BEGIN_CASE_REGEX",
",",
"line",
")",
"dep_str",
"=",
"match",
".",
"group",
"(",
"'depends_on'",
")",
"if",
"dep_str",
":",... | [
438,
0
] | [
455,
23
] | python | en | ['en', 'error', 'th'] | False |
parse_function_arguments | (line) |
Parses test function signature for validation and generates
a dispatch wrapper function that translates input test vectors
read from the data file into test function arguments.
:param line: Line from .function file that has a function
signature.
:return: argument list, local varia... |
Parses test function signature for validation and generates
a dispatch wrapper function that translates input test vectors
read from the data file into test function arguments. | def parse_function_arguments(line):
"""
Parses test function signature for validation and generates
a dispatch wrapper function that translates input test vectors
read from the data file into test function arguments.
:param line: Line from .function file that has a function
signatu... | [
"def",
"parse_function_arguments",
"(",
"line",
")",
":",
"args",
"=",
"[",
"]",
"local_vars",
"=",
"''",
"args_dispatch",
"=",
"[",
"]",
"arg_idx",
"=",
"0",
"# Remove characters before arguments",
"line",
"=",
"line",
"[",
"line",
".",
"find",
"(",
"'('",
... | [
458,
0
] | [
504,
42
] | python | en | ['en', 'error', 'th'] | False |
generate_function_code | (name, code, local_vars, args_dispatch,
dependencies) |
Generate function code with preprocessor checks and parameter dispatch
wrapper.
:param name: Function name
:param code: Function code
:param local_vars: Local variables for function wrapper
:param args_dispatch: Argument dispatch code
:param dependencies: Preprocessor dependencies list
... |
Generate function code with preprocessor checks and parameter dispatch
wrapper. | def generate_function_code(name, code, local_vars, args_dispatch,
dependencies):
"""
Generate function code with preprocessor checks and parameter dispatch
wrapper.
:param name: Function name
:param code: Function code
:param local_vars: Local variables for function w... | [
"def",
"generate_function_code",
"(",
"name",
",",
"code",
",",
"local_vars",
",",
"args_dispatch",
",",
"dependencies",
")",
":",
"# Add exit label if not present",
"if",
"code",
".",
"find",
"(",
"'exit:'",
")",
"==",
"-",
"1",
":",
"split_code",
"=",
"code"... | [
507,
0
] | [
531,
67
] | python | en | ['en', 'error', 'th'] | False |
parse_function_code | (funcs_f, dependencies, suite_dependencies) |
Parses out a function from function file object and generates
function and dispatch code.
:param funcs_f: file object of the functions file.
:param dependencies: List of dependencies
:param suite_dependencies: List of test suite dependencies
:return: Function name, arguments, function code and... |
Parses out a function from function file object and generates
function and dispatch code. | def parse_function_code(funcs_f, dependencies, suite_dependencies):
"""
Parses out a function from function file object and generates
function and dispatch code.
:param funcs_f: file object of the functions file.
:param dependencies: List of dependencies
:param suite_dependencies: List of test ... | [
"def",
"parse_function_code",
"(",
"funcs_f",
",",
"dependencies",
",",
"suite_dependencies",
")",
":",
"line_directive",
"=",
"'#line %d \"%s\"\\n'",
"%",
"(",
"funcs_f",
".",
"line_no",
"+",
"1",
",",
"funcs_f",
".",
"name",
")",
"code",
"=",
"''",
"has_exit... | [
534,
0
] | [
591,
44
] | python | en | ['en', 'error', 'th'] | False |
parse_functions | (funcs_f) |
Parses a test_suite_xxx.function file and returns information
for generating a C source file for the test suite.
:param funcs_f: file object of the functions file.
:return: List of test suite dependencies, test function dispatch
code, function code and a dict with function identifiers
... |
Parses a test_suite_xxx.function file and returns information
for generating a C source file for the test suite. | def parse_functions(funcs_f):
"""
Parses a test_suite_xxx.function file and returns information
for generating a C source file for the test suite.
:param funcs_f: file object of the functions file.
:return: List of test suite dependencies, test function dispatch
code, function code and... | [
"def",
"parse_functions",
"(",
"funcs_f",
")",
":",
"suite_helpers",
"=",
"''",
"suite_dependencies",
"=",
"[",
"]",
"suite_functions",
"=",
"''",
"func_info",
"=",
"{",
"}",
"function_idx",
"=",
"0",
"dispatch_code",
"=",
"''",
"for",
"line",
"in",
"funcs_f... | [
594,
0
] | [
640,
66
] | python | en | ['en', 'error', 'th'] | False |
escaped_split | (inp_str, split_char) |
Split inp_str on character split_char but ignore if escaped.
Since, return value is used to write back to the intermediate
data file, any escape characters in the input are retained in the
output.
:param inp_str: String to split
:param split_char: Split character
:return: List of splits
... |
Split inp_str on character split_char but ignore if escaped.
Since, return value is used to write back to the intermediate
data file, any escape characters in the input are retained in the
output. | def escaped_split(inp_str, split_char):
"""
Split inp_str on character split_char but ignore if escaped.
Since, return value is used to write back to the intermediate
data file, any escape characters in the input are retained in the
output.
:param inp_str: String to split
:param split_char:... | [
"def",
"escaped_split",
"(",
"inp_str",
",",
"split_char",
")",
":",
"if",
"len",
"(",
"split_char",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Expected split character. Found string!'",
")",
"out",
"=",
"re",
".",
"sub",
"(",
"r'(\\\\.)|'",
"+",
"spl... | [
643,
0
] | [
660,
14
] | python | en | ['en', 'error', 'th'] | False |
parse_test_data | (data_f) |
Parses .data file for each test case name, test function name,
test dependencies and test arguments. This information is
correlated with the test functions file for generating an
intermediate data file replacing the strings for test function
names, dependencies and integer constant expressions with... |
Parses .data file for each test case name, test function name,
test dependencies and test arguments. This information is
correlated with the test functions file for generating an
intermediate data file replacing the strings for test function
names, dependencies and integer constant expressions with... | def parse_test_data(data_f):
"""
Parses .data file for each test case name, test function name,
test dependencies and test arguments. This information is
correlated with the test functions file for generating an
intermediate data file replacing the strings for test function
names, dependencies a... | [
"def",
"parse_test_data",
"(",
"data_f",
")",
":",
"__state_read_name",
"=",
"0",
"__state_read_args",
"=",
"1",
"state",
"=",
"__state_read_name",
"dependencies",
"=",
"[",
"]",
"name",
"=",
"''",
"for",
"line",
"in",
"data_f",
":",
"line",
"=",
"line",
"... | [
663,
0
] | [
723,
77
] | python | en | ['en', 'error', 'th'] | False |
gen_dep_check | (dep_id, dep) |
Generate code for checking dependency with the associated
identifier.
:param dep_id: Dependency identifier
:param dep: Dependency macro
:return: Dependency check code
|
Generate code for checking dependency with the associated
identifier. | def gen_dep_check(dep_id, dep):
"""
Generate code for checking dependency with the associated
identifier.
:param dep_id: Dependency identifier
:param dep: Dependency macro
:return: Dependency check code
"""
if dep_id < 0:
raise GeneratorInputError("Dependency Id should be a posi... | [
"def",
"gen_dep_check",
"(",
"dep_id",
",",
"dep",
")",
":",
"if",
"dep_id",
"<",
"0",
":",
"raise",
"GeneratorInputError",
"(",
"\"Dependency Id should be a positive \"",
"\"integer.\"",
")",
"_not",
",",
"dep",
"=",
"(",
"'!'",
",",
"dep",
"[",
"1",
":",
... | [
726,
0
] | [
762,
20
] | python | en | ['en', 'error', 'th'] | False |
gen_expression_check | (exp_id, exp) |
Generates code for evaluating an integer expression using
associated expression Id.
:param exp_id: Expression Identifier
:param exp: Expression/Macro
:return: Expression check code
|
Generates code for evaluating an integer expression using
associated expression Id. | def gen_expression_check(exp_id, exp):
"""
Generates code for evaluating an integer expression using
associated expression Id.
:param exp_id: Expression Identifier
:param exp: Expression/Macro
:return: Expression check code
"""
if exp_id < 0:
raise GeneratorInputError("Expressio... | [
"def",
"gen_expression_check",
"(",
"exp_id",
",",
"exp",
")",
":",
"if",
"exp_id",
"<",
"0",
":",
"raise",
"GeneratorInputError",
"(",
"\"Expression Id should be a positive \"",
"\"integer.\"",
")",
"if",
"not",
"exp",
":",
"raise",
"GeneratorInputError",
"(",
"\... | [
765,
0
] | [
785,
19
] | python | en | ['en', 'error', 'th'] | False |
write_dependencies | (out_data_f, test_dependencies, unique_dependencies) |
Write dependencies to intermediate test data file, replacing
the string form with identifiers. Also, generates dependency
check code.
:param out_data_f: Output intermediate data file
:param test_dependencies: Dependencies
:param unique_dependencies: Mutable list to track unique dependencies
... |
Write dependencies to intermediate test data file, replacing
the string form with identifiers. Also, generates dependency
check code. | def write_dependencies(out_data_f, test_dependencies, unique_dependencies):
"""
Write dependencies to intermediate test data file, replacing
the string form with identifiers. Also, generates dependency
check code.
:param out_data_f: Output intermediate data file
:param test_dependencies: Depend... | [
"def",
"write_dependencies",
"(",
"out_data_f",
",",
"test_dependencies",
",",
"unique_dependencies",
")",
":",
"dep_check_code",
"=",
"''",
"if",
"test_dependencies",
":",
"out_data_f",
".",
"write",
"(",
"'depends_on'",
")",
"for",
"dep",
"in",
"test_dependencies"... | [
788,
0
] | [
812,
25
] | python | en | ['en', 'error', 'th'] | False |
write_parameters | (out_data_f, test_args, func_args, unique_expressions) |
Writes test parameters to the intermediate data file, replacing
the string form with identifiers. Also, generates expression
check code.
:param out_data_f: Output intermediate data file
:param test_args: Test parameters
:param func_args: Function arguments
:param unique_expressions: Mutabl... |
Writes test parameters to the intermediate data file, replacing
the string form with identifiers. Also, generates expression
check code. | def write_parameters(out_data_f, test_args, func_args, unique_expressions):
"""
Writes test parameters to the intermediate data file, replacing
the string form with identifiers. Also, generates expression
check code.
:param out_data_f: Output intermediate data file
:param test_args: Test parame... | [
"def",
"write_parameters",
"(",
"out_data_f",
",",
"test_args",
",",
"func_args",
",",
"unique_expressions",
")",
":",
"expression_code",
"=",
"''",
"for",
"i",
",",
"_",
"in",
"enumerate",
"(",
"test_args",
")",
":",
"typ",
"=",
"func_args",
"[",
"i",
"]"... | [
815,
0
] | [
849,
26
] | python | en | ['en', 'error', 'th'] | False |
gen_suite_dep_checks | (suite_dependencies, dep_check_code, expression_code) |
Generates preprocessor checks for test suite dependencies.
:param suite_dependencies: Test suite dependencies read from the
.function file.
:param dep_check_code: Dependency check code
:param expression_code: Expression check code
:return: Dependency and expression code guarded by test... |
Generates preprocessor checks for test suite dependencies. | def gen_suite_dep_checks(suite_dependencies, dep_check_code, expression_code):
"""
Generates preprocessor checks for test suite dependencies.
:param suite_dependencies: Test suite dependencies read from the
.function file.
:param dep_check_code: Dependency check code
:param expression_c... | [
"def",
"gen_suite_dep_checks",
"(",
"suite_dependencies",
",",
"dep_check_code",
",",
"expression_code",
")",
":",
"if",
"suite_dependencies",
":",
"preprocessor_check",
"=",
"gen_dependencies_one_line",
"(",
"suite_dependencies",
")",
"dep_check_code",
"=",
"'''\n{preproce... | [
852,
0
] | [
875,
42
] | python | en | ['en', 'error', 'th'] | False |
gen_from_test_data | (data_f, out_data_f, func_info, suite_dependencies) |
This function reads test case name, dependencies and test vectors
from the .data file. This information is correlated with the test
functions file for generating an intermediate data file replacing
the strings for test function names, dependencies and integer
constant expressions with identifiers. ... |
This function reads test case name, dependencies and test vectors
from the .data file. This information is correlated with the test
functions file for generating an intermediate data file replacing
the strings for test function names, dependencies and integer
constant expressions with identifiers. ... | def gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies):
"""
This function reads test case name, dependencies and test vectors
from the .data file. This information is correlated with the test
functions file for generating an intermediate data file replacing
the strings for test fu... | [
"def",
"gen_from_test_data",
"(",
"data_f",
",",
"out_data_f",
",",
"func_info",
",",
"suite_dependencies",
")",
":",
"unique_dependencies",
"=",
"[",
"]",
"unique_expressions",
"=",
"[",
"]",
"dep_check_code",
"=",
"''",
"expression_code",
"=",
"''",
"for",
"te... | [
878,
0
] | [
929,
42
] | python | en | ['en', 'error', 'th'] | False |
add_input_info | (funcs_file, data_file, template_file,
c_file, snippets) |
Add generator input info in snippets.
:param funcs_file: Functions file object
:param data_file: Data file object
:param template_file: Template file object
:param c_file: Output C file object
:param snippets: Dictionary to contain code pieces to be
substituted in the temp... |
Add generator input info in snippets. | def add_input_info(funcs_file, data_file, template_file,
c_file, snippets):
"""
Add generator input info in snippets.
:param funcs_file: Functions file object
:param data_file: Data file object
:param template_file: Template file object
:param c_file: Output C file object
... | [
"def",
"add_input_info",
"(",
"funcs_file",
",",
"data_file",
",",
"template_file",
",",
"c_file",
",",
"snippets",
")",
":",
"snippets",
"[",
"'test_file'",
"]",
"=",
"c_file",
"snippets",
"[",
"'test_main_file'",
"]",
"=",
"template_file",
"snippets",
"[",
"... | [
932,
0
] | [
948,
47
] | python | en | ['en', 'error', 'th'] | False |
read_code_from_input_files | (platform_file, helpers_file,
out_data_file, snippets) |
Read code from input files and create substitutions for replacement
strings in the template file.
:param platform_file: Platform file object
:param helpers_file: Helper functions file object
:param out_data_file: Output intermediate data file object
:param snippets: Dictionary to contain code ... |
Read code from input files and create substitutions for replacement
strings in the template file. | def read_code_from_input_files(platform_file, helpers_file,
out_data_file, snippets):
"""
Read code from input files and create substitutions for replacement
strings in the template file.
:param platform_file: Platform file object
:param helpers_file: Helper functions... | [
"def",
"read_code_from_input_files",
"(",
"platform_file",
",",
"helpers_file",
",",
"out_data_file",
",",
"snippets",
")",
":",
"# Read helpers",
"with",
"open",
"(",
"helpers_file",
",",
"'r'",
")",
"as",
"help_f",
",",
"open",
"(",
"platform_file",
",",
"'r'"... | [
951,
0
] | [
971,
61
] | python | en | ['en', 'error', 'th'] | False |
write_test_source_file | (template_file, c_file, snippets) |
Write output source file with generated source code.
:param template_file: Template file name
:param c_file: Output source file
:param snippets: Generated and code snippets
:return:
|
Write output source file with generated source code. | def write_test_source_file(template_file, c_file, snippets):
"""
Write output source file with generated source code.
:param template_file: Template file name
:param c_file: Output source file
:param snippets: Generated and code snippets
:return:
"""
with open(template_file, 'r') as tem... | [
"def",
"write_test_source_file",
"(",
"template_file",
",",
"c_file",
",",
"snippets",
")",
":",
"with",
"open",
"(",
"template_file",
",",
"'r'",
")",
"as",
"template_f",
",",
"open",
"(",
"c_file",
",",
"'w'",
")",
"as",
"c_f",
":",
"for",
"line_no",
"... | [
974,
0
] | [
988,
27
] | python | en | ['en', 'error', 'th'] | False |
parse_function_file | (funcs_file, snippets) |
Parse function file and generate function dispatch code.
:param funcs_file: Functions file name
:param snippets: Dictionary to contain code pieces to be
substituted in the template.
:return:
|
Parse function file and generate function dispatch code. | def parse_function_file(funcs_file, snippets):
"""
Parse function file and generate function dispatch code.
:param funcs_file: Functions file name
:param snippets: Dictionary to contain code pieces to be
substituted in the template.
:return:
"""
with FileWrapper(funcs_f... | [
"def",
"parse_function_file",
"(",
"funcs_file",
",",
"snippets",
")",
":",
"with",
"FileWrapper",
"(",
"funcs_file",
")",
"as",
"funcs_f",
":",
"suite_dependencies",
",",
"dispatch_code",
",",
"func_code",
",",
"func_info",
"=",
"parse_functions",
"(",
"funcs_f",... | [
991,
0
] | [
1005,
44
] | python | en | ['en', 'error', 'th'] | False |
generate_intermediate_data_file | (data_file, out_data_file,
suite_dependencies, func_info, snippets) |
Generates intermediate data file from input data file and
information read from functions file.
:param data_file: Data file name
:param out_data_file: Output/Intermediate data file
:param suite_dependencies: List of suite dependencies.
:param func_info: Function info parsed from functions file... |
Generates intermediate data file from input data file and
information read from functions file. | def generate_intermediate_data_file(data_file, out_data_file,
suite_dependencies, func_info, snippets):
"""
Generates intermediate data file from input data file and
information read from functions file.
:param data_file: Data file name
:param out_data_file: Outp... | [
"def",
"generate_intermediate_data_file",
"(",
"data_file",
",",
"out_data_file",
",",
"suite_dependencies",
",",
"func_info",
",",
"snippets",
")",
":",
"with",
"FileWrapper",
"(",
"data_file",
")",
"as",
"data_f",
",",
"open",
"(",
"out_data_file",
",",
"'w'",
... | [
1008,
0
] | [
1027,
53
] | python | en | ['en', 'error', 'th'] | False |
generate_code | (**input_info) |
Generates C source code from test suite file, data file, common
helpers file and platform file.
input_info expands to following parameters:
funcs_file: Functions file object
data_file: Data file object
template_file: Template file object
platform_file: Platform file object
helpers_file... |
Generates C source code from test suite file, data file, common
helpers file and platform file. | def generate_code(**input_info):
"""
Generates C source code from test suite file, data file, common
helpers file and platform file.
input_info expands to following parameters:
funcs_file: Functions file object
data_file: Data file object
template_file: Template file object
platform_fil... | [
"def",
"generate_code",
"(",
"*",
"*",
"input_info",
")",
":",
"funcs_file",
"=",
"input_info",
"[",
"'funcs_file'",
"]",
"data_file",
"=",
"input_info",
"[",
"'data_file'",
"]",
"template_file",
"=",
"input_info",
"[",
"'template_file'",
"]",
"platform_file",
"... | [
1030,
0
] | [
1071,
59
] | python | en | ['en', 'error', 'th'] | False |
main | () |
Command line parser.
:return:
|
Command line parser. | def main():
"""
Command line parser.
:return:
"""
parser = argparse.ArgumentParser(
description='Dynamically generate test suite code.')
parser.add_argument("-f", "--functions-file",
dest="funcs_file",
help="Functions file",
... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Dynamically generate test suite code.'",
")",
"parser",
".",
"add_argument",
"(",
"\"-f\"",
",",
"\"--functions-file\"",
",",
"dest",
"=",
"\"funcs_file\"",
... | [
1074,
0
] | [
1143,
65
] | python | en | ['en', 'error', 'th'] | False |
FileWrapper.__init__ | (self, file_name) |
Instantiate the base class and initialize the line number to 0.
:param file_name: File path to open.
|
Instantiate the base class and initialize the line number to 0. | def __init__(self, file_name):
"""
Instantiate the base class and initialize the line number to 0.
:param file_name: File path to open.
"""
super(FileWrapper, self).__init__(file_name, 'r')
self._line_no = 0 | [
"def",
"__init__",
"(",
"self",
",",
"file_name",
")",
":",
"super",
"(",
"FileWrapper",
",",
"self",
")",
".",
"__init__",
"(",
"file_name",
",",
"'r'",
")",
"self",
".",
"_line_no",
"=",
"0"
] | [
216,
4
] | [
223,
25
] | python | en | ['en', 'error', 'th'] | False |
FileWrapper.next | (self) |
Python 2 iterator method. This method overrides base class's
next method and extends the next method to count the line
numbers as each line is read.
It works for both Python 2 and Python 3 by checking iterator
method name in the base iterator object.
:return: Line read... |
Python 2 iterator method. This method overrides base class's
next method and extends the next method to count the line
numbers as each line is read. | def next(self):
"""
Python 2 iterator method. This method overrides base class's
next method and extends the next method to count the line
numbers as each line is read.
It works for both Python 2 and Python 3 by checking iterator
method name in the base iterator object.
... | [
"def",
"next",
"(",
"self",
")",
":",
"parent",
"=",
"super",
"(",
"FileWrapper",
",",
"self",
")",
"if",
"hasattr",
"(",
"parent",
",",
"'__next__'",
")",
":",
"line",
"=",
"parent",
".",
"__next__",
"(",
")",
"# Python 3",
"else",
":",
"line",
"=",... | [
225,
4
] | [
246,
19
] | python | en | ['en', 'error', 'th'] | False |
FileWrapper.get_line_no | (self) |
Gives current line number.
|
Gives current line number.
| def get_line_no(self):
"""
Gives current line number.
"""
return self._line_no | [
"def",
"get_line_no",
"(",
"self",
")",
":",
"return",
"self",
".",
"_line_no"
] | [
251,
4
] | [
255,
28
] | python | en | ['en', 'error', 'th'] | False |
WorkflowJob.failure_output_details | (self) | Special implementation of this part of assert_status so that
workflow_job.assert_successful() will give a breakdown of failure
| Special implementation of this part of assert_status so that
workflow_job.assert_successful() will give a breakdown of failure
| def failure_output_details(self):
"""Special implementation of this part of assert_status so that
workflow_job.assert_successful() will give a breakdown of failure
"""
node_list = self.related.workflow_nodes.get().results
msg = '\nNode summary:'
for node in node_list:
... | [
"def",
"failure_output_details",
"(",
"self",
")",
":",
"node_list",
"=",
"self",
".",
"related",
".",
"workflow_nodes",
".",
"get",
"(",
")",
".",
"results",
"msg",
"=",
"'\\nNode summary:'",
"for",
"node",
"in",
"node_list",
":",
"msg",
"+=",
"'\\n{}: {}'"... | [
14,
4
] | [
38,
18
] | python | en | ['en', 'en', 'en'] | True |
is_archive_file | (name) | Return True if `name` is a considered as an archive file. | Return True if `name` is a considered as an archive file. | def is_archive_file(name):
# type: (str) -> bool
"""Return True if `name` is a considered as an archive file."""
ext = splitext(name)[1].lower()
if ext in ARCHIVE_EXTENSIONS:
return True
return False | [
"def",
"is_archive_file",
"(",
"name",
")",
":",
"# type: (str) -> bool",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"return",
"True",
"return",
"False"
] | [
19,
0
] | [
25,
16
] | python | en | ['en', 'en', 'en'] | True |
link_entity | (props) |
<a linktype="page" id="1">internal page link</a>
|
<a linktype="page" id="1">internal page link</a>
| def link_entity(props):
"""
<a linktype="page" id="1">internal page link</a>
"""
id_ = props.get('id')
link_props = {}
if id_ is not None:
link_props['linktype'] = 'page'
link_props['id'] = id_
else:
link_props['href'] = check_url(props.get('url'))
return DOM.cr... | [
"def",
"link_entity",
"(",
"props",
")",
":",
"id_",
"=",
"props",
".",
"get",
"(",
"'id'",
")",
"link_props",
"=",
"{",
"}",
"if",
"id_",
"is",
"not",
"None",
":",
"link_props",
"[",
"'linktype'",
"]",
"=",
"'page'",
"link_props",
"[",
"'id'",
"]",
... | [
14,
0
] | [
27,
65
] | python | en | ['en', 'error', 'th'] | False |
MixtureDensityNetwork.fit | (self, X, Y, random_seed=None, verbose=True, eval_set=None, **kwargs) | Fits the conditional density model with provided data
Args:
X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
Y: numpy array of y targets - shape: (n_samples, n_dim_y)
eval_set: (tuple) eval/test set - tuple (X_test, Y_test)
verbose: (boolean) controls the verbosi... | Fits the conditional density model with provided data | def fit(self, X, Y, random_seed=None, verbose=True, eval_set=None, **kwargs):
""" Fits the conditional density model with provided data
Args:
X: numpy array to be conditioned on - shape: (n_samples, n_dim_x)
Y: numpy array of y targets - shape: (n_samples, n_dim_y)
eval_set: (tuple) e... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"Y",
",",
"random_seed",
"=",
"None",
",",
"verbose",
"=",
"True",
",",
"eval_set",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"X",
",",
"Y",
"=",
"self",
".",
"_handle_input_dimensionality",
"(",
"X",... | [
83,
2
] | [
108,
22
] | python | en | ['en', 'en', 'en'] | True |
MixtureDensityNetwork._build_model | (self) |
implementation of the MDN
|
implementation of the MDN
| def _build_model(self):
"""
implementation of the MDN
"""
with tf.variable_scope(self.name):
# adds placeholders, data_normalization and data_noise if desired. Also adds a placeholder for dropout probability
self.layer_in_x, self.layer_in_y = self._build_input_layers()
# create core ... | [
"def",
"_build_model",
"(",
"self",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"self",
".",
"name",
")",
":",
"# adds placeholders, data_normalization and data_noise if desired. Also adds a placeholder for dropout probability",
"self",
".",
"layer_in_x",
",",
"self... | [
110,
2
] | [
185,
51
] | python | en | ['en', 'error', 'th'] | False |
build_files | (file_defs, prefix=pathlib.Path()) | Build a set of files/directories, as described by the
file_defs dictionary. Each key/value pair in the dictionary is
interpreted as a filename/contents pair. If the contents value is a
dictionary, a directory is created, and the dictionary interpreted
as the files within it, recursively.
For exa... | Build a set of files/directories, as described by the | def build_files(file_defs, prefix=pathlib.Path()):
"""Build a set of files/directories, as described by the
file_defs dictionary. Each key/value pair in the dictionary is
interpreted as a filename/contents pair. If the contents value is a
dictionary, a directory is created, and the dictionary interpr... | [
"def",
"build_files",
"(",
"file_defs",
",",
"prefix",
"=",
"pathlib",
".",
"Path",
"(",
")",
")",
":",
"for",
"name",
",",
"contents",
"in",
"file_defs",
".",
"items",
"(",
")",
":",
"full_name",
"=",
"prefix",
"/",
"name",
"if",
"isinstance",
"(",
... | [
184,
0
] | [
215,
43
] | python | en | ['en', 'en', 'en'] | True |
DALS | (str) | Dedent and left-strip | Dedent and left-strip | def DALS(str):
"Dedent and left-strip"
return textwrap.dedent(str).lstrip() | [
"def",
"DALS",
"(",
"str",
")",
":",
"return",
"textwrap",
".",
"dedent",
"(",
"str",
")",
".",
"lstrip",
"(",
")"
] | [
224,
0
] | [
226,
40
] | python | en | ['en', 'da', 'en'] | True |
ImageEmbedHandler.get_db_attributes | (tag) |
Given a tag that we've identified as an image embed (because it has a
data-embedtype="image" attribute), return a dict of the attributes we should
have on the resulting <embed> element.
|
Given a tag that we've identified as an image embed (because it has a
data-embedtype="image" attribute), return a dict of the attributes we should
have on the resulting <embed> element.
| def get_db_attributes(tag):
"""
Given a tag that we've identified as an image embed (because it has a
data-embedtype="image" attribute), return a dict of the attributes we should
have on the resulting <embed> element.
"""
return {
'id': tag['data-id'],
... | [
"def",
"get_db_attributes",
"(",
"tag",
")",
":",
"return",
"{",
"'id'",
":",
"tag",
"[",
"'data-id'",
"]",
",",
"'format'",
":",
"tag",
"[",
"'data-format'",
"]",
",",
"'alt'",
":",
"tag",
"[",
"'data-alt'",
"]",
",",
"}"
] | [
15,
4
] | [
25,
9
] | python | en | ['en', 'error', 'th'] | False |
ImageEmbedHandler.expand_db_attributes | (attrs) |
Given a dict of attributes from the <embed> tag, return the real HTML
representation for use within the editor.
|
Given a dict of attributes from the <embed> tag, return the real HTML
representation for use within the editor.
| def expand_db_attributes(attrs):
"""
Given a dict of attributes from the <embed> tag, return the real HTML
representation for use within the editor.
"""
Image = get_image_model()
try:
image = Image.objects.get(id=attrs['id'])
except Image.DoesNotExist:... | [
"def",
"expand_db_attributes",
"(",
"attrs",
")",
":",
"Image",
"=",
"get_image_model",
"(",
")",
"try",
":",
"image",
"=",
"Image",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"attrs",
"[",
"'id'",
"]",
")",
"except",
"Image",
".",
"DoesNotExist",
":"... | [
28,
4
] | [
41,
77
] | python | en | ['en', 'error', 'th'] | False |
PyPIRCCommand._get_rc_file | (self) | Returns rc file path. | Returns rc file path. | def _get_rc_file(self):
"""Returns rc file path."""
return os.path.join(os.path.expanduser('~'), '.pypirc') | [
"def",
"_get_rc_file",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.pypirc'",
")"
] | [
37,
4
] | [
39,
63
] | python | en | ['fr', 'ja', 'en'] | False |
PyPIRCCommand._store_pypirc | (self, username, password) | Creates a default .pypirc file. | Creates a default .pypirc file. | def _store_pypirc(self, username, password):
"""Creates a default .pypirc file."""
rc = self._get_rc_file()
with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f:
f.write(DEFAULT_PYPIRC % (username, password)) | [
"def",
"_store_pypirc",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"rc",
"=",
"self",
".",
"_get_rc_file",
"(",
")",
"with",
"os",
".",
"fdopen",
"(",
"os",
".",
"open",
"(",
"rc",
",",
"os",
".",
"O_CREAT",
"|",
"os",
".",
"O_WRONLY"... | [
41,
4
] | [
45,
58
] | python | en | ['es', 'fr', 'en'] | False |
PyPIRCCommand._read_pypirc | (self) | Reads the .pypirc file. | Reads the .pypirc file. | def _read_pypirc(self):
"""Reads the .pypirc file."""
rc = self._get_rc_file()
if os.path.exists(rc):
self.announce('Using PyPI login from %s' % rc)
repository = self.repository or self.DEFAULT_REPOSITORY
config = RawConfigParser()
config.read(rc)... | [
"def",
"_read_pypirc",
"(",
"self",
")",
":",
"rc",
"=",
"self",
".",
"_get_rc_file",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"rc",
")",
":",
"self",
".",
"announce",
"(",
"'Using PyPI login from %s'",
"%",
"rc",
")",
"repository",
"=",
... | [
47,
4
] | [
109,
17
] | python | en | ['en', 'en', 'en'] | True |
PyPIRCCommand._read_pypi_response | (self, response) | Read and decode a PyPI HTTP response. | Read and decode a PyPI HTTP response. | def _read_pypi_response(self, response):
"""Read and decode a PyPI HTTP response."""
import cgi
content_type = response.getheader('content-type', 'text/plain')
encoding = cgi.parse_header(content_type)[1].get('charset', 'ascii')
return response.read().decode(encoding) | [
"def",
"_read_pypi_response",
"(",
"self",
",",
"response",
")",
":",
"import",
"cgi",
"content_type",
"=",
"response",
".",
"getheader",
"(",
"'content-type'",
",",
"'text/plain'",
")",
"encoding",
"=",
"cgi",
".",
"parse_header",
"(",
"content_type",
")",
"[... | [
111,
4
] | [
116,
47
] | python | en | ['en', 'en', 'en'] | True |
PyPIRCCommand.initialize_options | (self) | Initialize options. | Initialize options. | def initialize_options(self):
"""Initialize options."""
self.repository = None
self.realm = None
self.show_response = 0 | [
"def",
"initialize_options",
"(",
"self",
")",
":",
"self",
".",
"repository",
"=",
"None",
"self",
".",
"realm",
"=",
"None",
"self",
".",
"show_response",
"=",
"0"
] | [
118,
4
] | [
122,
30
] | python | en | ['en', 'en', 'en'] | False |
PyPIRCCommand.finalize_options | (self) | Finalizes options. | Finalizes options. | def finalize_options(self):
"""Finalizes options."""
if self.repository is None:
self.repository = self.DEFAULT_REPOSITORY
if self.realm is None:
self.realm = self.DEFAULT_REALM | [
"def",
"finalize_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"repository",
"is",
"None",
":",
"self",
".",
"repository",
"=",
"self",
".",
"DEFAULT_REPOSITORY",
"if",
"self",
".",
"realm",
"is",
"None",
":",
"self",
".",
"realm",
"=",
"self",
"... | [
124,
4
] | [
129,
43
] | python | en | ['en', 'en', 'en'] | False |
subclass_exception | (name, parents, module, attached_to=None) |
Create exception subclass. Used by ModelBase below.
If 'attached_to' is supplied, the exception will be created in a way that
allows it to be pickled, assuming the returned exception class will be added
as an attribute to the 'attached_to' class.
|
Create exception subclass. Used by ModelBase below. | def subclass_exception(name, parents, module, attached_to=None):
"""
Create exception subclass. Used by ModelBase below.
If 'attached_to' is supplied, the exception will be created in a way that
allows it to be pickled, assuming the returned exception class will be added
as an attribute to the 'att... | [
"def",
"subclass_exception",
"(",
"name",
",",
"parents",
",",
"module",
",",
"attached_to",
"=",
"None",
")",
":",
"class_dict",
"=",
"{",
"'__module__'",
":",
"module",
"}",
"if",
"attached_to",
"is",
"not",
"None",
":",
"def",
"__reduce__",
"(",
"self",... | [
54,
0
] | [
75,
42
] | python | en | ['en', 'error', 'th'] | False |
model_unpickle | (model_id) |
Used to unpickle Model subclasses with deferred fields.
|
Used to unpickle Model subclasses with deferred fields.
| def model_unpickle(model_id):
"""
Used to unpickle Model subclasses with deferred fields.
"""
if isinstance(model_id, tuple):
model = apps.get_model(*model_id)
else:
# Backwards compat - the model was cached directly in earlier versions.
model = model_id
return model.__ne... | [
"def",
"model_unpickle",
"(",
"model_id",
")",
":",
"if",
"isinstance",
"(",
"model_id",
",",
"tuple",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"*",
"model_id",
")",
"else",
":",
"# Backwards compat - the model was cached directly in earlier versions."... | [
1799,
0
] | [
1808,
31
] | python | en | ['en', 'error', 'th'] | False |
ModelBase._prepare | (cls) |
Creates some methods once self._meta has been populated.
|
Creates some methods once self._meta has been populated.
| def _prepare(cls):
"""
Creates some methods once self._meta has been populated.
"""
opts = cls._meta
opts._prepare(cls)
if opts.order_with_respect_to:
cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True)
cls.get_previous... | [
"def",
"_prepare",
"(",
"cls",
")",
":",
"opts",
"=",
"cls",
".",
"_meta",
"opts",
".",
"_prepare",
"(",
"cls",
")",
"if",
"opts",
".",
"order_with_respect_to",
":",
"cls",
".",
"get_next_in_order",
"=",
"curry",
"(",
"cls",
".",
"_get_next_or_previous_in_... | [
333,
4
] | [
372,
39
] | python | en | ['en', 'error', 'th'] | False |
Model.get_deferred_fields | (self) |
Returns a set containing names of deferred fields for this instance.
|
Returns a set containing names of deferred fields for this instance.
| def get_deferred_fields(self):
"""
Returns a set containing names of deferred fields for this instance.
"""
return {
f.attname for f in self._meta.concrete_fields
if f.attname not in self.__dict__
} | [
"def",
"get_deferred_fields",
"(",
"self",
")",
":",
"return",
"{",
"f",
".",
"attname",
"for",
"f",
"in",
"self",
".",
"_meta",
".",
"concrete_fields",
"if",
"f",
".",
"attname",
"not",
"in",
"self",
".",
"__dict__",
"}"
] | [
649,
4
] | [
656,
9
] | python | en | ['en', 'error', 'th'] | False |
Model.refresh_from_db | (self, using=None, fields=None) |
Reloads field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will override the default.
Fields can be used to specify which... |
Reloads field values from the database. | def refresh_from_db(self, using=None, fields=None):
"""
Reloads field values from the database.
By default, the reloading happens from the database this instance was
loaded from, or by the read router if this instance wasn't loaded from
any database. The using parameter will ove... | [
"def",
"refresh_from_db",
"(",
"self",
",",
"using",
"=",
"None",
",",
"fields",
"=",
"None",
")",
":",
"if",
"fields",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"fields",
")",
"==",
"0",
":",
"return",
"if",
"any",
"(",
"LOOKUP_SEP",
"in",
"f",
... | [
658,
4
] | [
708,
46
] | python | en | ['en', 'error', 'th'] | False |
Model.serializable_value | (self, field_name) |
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly.
Used to serialize a field's value (in the... |
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directly. | def serializable_value(self, field_name):
"""
Returns the value of the field name for this instance. If the field is
a foreign key, returns the id value, instead of the object. If there's
no Field object with this name on the model, the model attribute's
value is returned directl... | [
"def",
"serializable_value",
"(",
"self",
",",
"field_name",
")",
":",
"try",
":",
"field",
"=",
"self",
".",
"_meta",
".",
"get_field",
"(",
"field_name",
")",
"except",
"FieldDoesNotExist",
":",
"return",
"getattr",
"(",
"self",
",",
"field_name",
")",
"... | [
710,
4
] | [
725,
43
] | python | en | ['en', 'error', 'th'] | False |
Model.save | (self, force_insert=False, force_update=False, using=None,
update_fields=None) |
Saves the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally... |
Saves the current instance. Override this in a subclass if you want to
control the saving process. | def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
"""
Saves the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that... | [
"def",
"save",
"(",
"self",
",",
"force_insert",
"=",
"False",
",",
"force_update",
"=",
"False",
",",
"using",
"=",
"None",
",",
"update_fields",
"=",
"None",
")",
":",
"# Ensure that a model instance without a PK hasn't been assigned to",
"# a ForeignKey or OneToOneFi... | [
727,
4
] | [
805,
78
] | python | en | ['en', 'error', 'th'] | False |
Model.save_base | (self, raw=False, force_insert=False,
force_update=False, using=None, update_fields=None) |
Handles the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
The 'raw' argument is telling save_base not to save any parent
models and not to do any changes to the values before ... |
Handles the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending. | def save_base(self, raw=False, force_insert=False,
force_update=False, using=None, update_fields=None):
"""
Handles the parts of saving which should be done only once per save,
yet need to be done in raw saves, too. This includes some sanity
checks and signal sending.
... | [
"def",
"save_base",
"(",
"self",
",",
"raw",
"=",
"False",
",",
"force_insert",
"=",
"False",
",",
"force_update",
"=",
"False",
",",
"using",
"=",
"None",
",",
"update_fields",
"=",
"None",
")",
":",
"using",
"=",
"using",
"or",
"router",
".",
"db_for... | [
808,
4
] | [
846,
13
] | python | en | ['en', 'error', 'th'] | False |
Model._save_parents | (self, cls, using, update_fields) |
Saves all the parents of cls using values from self.
|
Saves all the parents of cls using values from self.
| def _save_parents(self, cls, using, update_fields):
"""
Saves all the parents of cls using values from self.
"""
meta = cls._meta
for parent, field in meta.parents.items():
# Make sure the link fields are synced between parent and self.
if (field and getat... | [
"def",
"_save_parents",
"(",
"self",
",",
"cls",
",",
"using",
",",
"update_fields",
")",
":",
"meta",
"=",
"cls",
".",
"_meta",
"for",
"parent",
",",
"field",
"in",
"meta",
".",
"parents",
".",
"items",
"(",
")",
":",
"# Make sure the link fields are sync... | [
850,
4
] | [
872,
45
] | python | en | ['en', 'error', 'th'] | False |
Model._save_table | (self, raw=False, cls=None, force_insert=False,
force_update=False, using=None, update_fields=None) |
Does the heavy-lifting involved in saving. Updates or inserts the data
for a single table.
|
Does the heavy-lifting involved in saving. Updates or inserts the data
for a single table.
| def _save_table(self, raw=False, cls=None, force_insert=False,
force_update=False, using=None, update_fields=None):
"""
Does the heavy-lifting involved in saving. Updates or inserts the data
for a single table.
"""
meta = cls._meta
non_pks = [f for f i... | [
"def",
"_save_table",
"(",
"self",
",",
"raw",
"=",
"False",
",",
"cls",
"=",
"None",
",",
"force_insert",
"=",
"False",
",",
"force_update",
"=",
"False",
",",
"using",
"=",
"None",
",",
"update_fields",
"=",
"None",
")",
":",
"meta",
"=",
"cls",
".... | [
874,
4
] | [
924,
22
] | python | en | ['en', 'error', 'th'] | False |
Model._do_update | (self, base_qs, using, pk_val, values, update_fields, forced_update) |
This method will try to update the model. If the model was updated (in
the sense that an update query was done and a matching row was found
from the DB) the method will return True.
|
This method will try to update the model. If the model was updated (in
the sense that an update query was done and a matching row was found
from the DB) the method will return True.
| def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
"""
This method will try to update the model. If the model was updated (in
the sense that an update query was done and a matching row was found
from the DB) the method will return True.
"""
... | [
"def",
"_do_update",
"(",
"self",
",",
"base_qs",
",",
"using",
",",
"pk_val",
",",
"values",
",",
"update_fields",
",",
"forced_update",
")",
":",
"filtered",
"=",
"base_qs",
".",
"filter",
"(",
"pk",
"=",
"pk_val",
")",
"if",
"not",
"values",
":",
"#... | [
926,
4
] | [
952,
43
] | python | en | ['en', 'error', 'th'] | False |
Model._do_insert | (self, manager, using, fields, update_pk, raw) |
Do an INSERT. If update_pk is defined then this method should return
the new pk for the model.
|
Do an INSERT. If update_pk is defined then this method should return
the new pk for the model.
| def _do_insert(self, manager, using, fields, update_pk, raw):
"""
Do an INSERT. If update_pk is defined then this method should return
the new pk for the model.
"""
return manager._insert([self], fields=fields, return_id=update_pk,
using=using, raw=... | [
"def",
"_do_insert",
"(",
"self",
",",
"manager",
",",
"using",
",",
"fields",
",",
"update_pk",
",",
"raw",
")",
":",
"return",
"manager",
".",
"_insert",
"(",
"[",
"self",
"]",
",",
"fields",
"=",
"fields",
",",
"return_id",
"=",
"update_pk",
",",
... | [
954,
4
] | [
960,
52
] | python | en | ['en', 'error', 'th'] | False |
Model.clean | (self) |
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.... |
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field defined by NON_FIELD_ERRORS.... | def clean(self):
"""
Hook for doing any extra model-wide validation after clean() has been
called on every field by self.clean_fields. Any ValidationError raised
by this method will not be associated with a particular field; it will
have a special-case association with the field ... | [
"def",
"clean",
"(",
"self",
")",
":",
"pass"
] | [
1015,
4
] | [
1022,
12
] | python | en | ['en', 'error', 'th'] | False |
Model.validate_unique | (self, exclude=None) |
Checks unique constraints on the model and raises ``ValidationError``
if any failed.
|
Checks unique constraints on the model and raises ``ValidationError``
if any failed.
| def validate_unique(self, exclude=None):
"""
Checks unique constraints on the model and raises ``ValidationError``
if any failed.
"""
unique_checks, date_checks = self._get_unique_checks(exclude=exclude)
errors = self._perform_unique_checks(unique_checks)
date_er... | [
"def",
"validate_unique",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"unique_checks",
",",
"date_checks",
"=",
"self",
".",
"_get_unique_checks",
"(",
"exclude",
"=",
"exclude",
")",
"errors",
"=",
"self",
".",
"_perform_unique_checks",
"(",
"unique_c... | [
1024,
4
] | [
1038,
41
] | python | en | ['en', 'error', 'th'] | False |
Model._get_unique_checks | (self, exclude=None) |
Gather a list of checks to perform. Since validate_unique could be
called from a ModelForm, some fields may have been excluded; we can't
perform a unique check on a model that is missing fields involved
in that check.
Fields that did not validate should also be excluded, but the... |
Gather a list of checks to perform. Since validate_unique could be
called from a ModelForm, some fields may have been excluded; we can't
perform a unique check on a model that is missing fields involved
in that check.
Fields that did not validate should also be excluded, but the... | def _get_unique_checks(self, exclude=None):
"""
Gather a list of checks to perform. Since validate_unique could be
called from a ModelForm, some fields may have been excluded; we can't
perform a unique check on a model that is missing fields involved
in that check.
Fields... | [
"def",
"_get_unique_checks",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"unique_checks",
"=",
"[",
"]",
"unique_togethers",
"=",
"[",
"(",
"self",
".",
"__class__",
",",
"self",
"."... | [
1040,
4
] | [
1090,
41
] | python | en | ['en', 'error', 'th'] | False |
Model.full_clean | (self, exclude=None, validate_unique=True) |
Calls clean_fields, clean, and validate_unique, on the model,
and raises a ``ValidationError`` for any errors that occurred.
|
Calls clean_fields, clean, and validate_unique, on the model,
and raises a ``ValidationError`` for any errors that occurred.
| def full_clean(self, exclude=None, validate_unique=True):
"""
Calls clean_fields, clean, and validate_unique, on the model,
and raises a ``ValidationError`` for any errors that occurred.
"""
errors = {}
if exclude is None:
exclude = []
else:
... | [
"def",
"full_clean",
"(",
"self",
",",
"exclude",
"=",
"None",
",",
"validate_unique",
"=",
"True",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"else",
":",
"exclude",
"=",
"list",
"(",
"exclude",
... | [
1213,
4
] | [
1247,
41
] | python | en | ['en', 'error', 'th'] | False |
Model.clean_fields | (self, exclude=None) |
Cleans all fields and raises a ValidationError containing a dict
of all validation errors if any occur.
|
Cleans all fields and raises a ValidationError containing a dict
of all validation errors if any occur.
| def clean_fields(self, exclude=None):
"""
Cleans all fields and raises a ValidationError containing a dict
of all validation errors if any occur.
"""
if exclude is None:
exclude = []
errors = {}
for f in self._meta.fields:
if f.name in exc... | [
"def",
"clean_fields",
"(",
"self",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"[",
"]",
"errors",
"=",
"{",
"}",
"for",
"f",
"in",
"self",
".",
"_meta",
".",
"fields",
":",
"if",
"f",
".",
"name",
... | [
1249,
4
] | [
1272,
41
] | python | en | ['en', 'error', 'th'] | False |
Model._check_swappable | (cls) | Check if the swapped model exists. | Check if the swapped model exists. | def _check_swappable(cls):
""" Check if the swapped model exists. """
errors = []
if cls._meta.swapped:
try:
apps.get_model(cls._meta.swapped)
except ValueError:
errors.append(
checks.Error(
"'%s... | [
"def",
"_check_swappable",
"(",
"cls",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"cls",
".",
"_meta",
".",
"swapped",
":",
"try",
":",
"apps",
".",
"get_model",
"(",
"cls",
".",
"_meta",
".",
"swapped",
")",
"except",
"ValueError",
":",
"errors",
".",... | [
1301,
4
] | [
1326,
21
] | python | en | ['en', 'en', 'en'] | True |
Model._check_managers | (cls, **kwargs) | Perform all manager checks. | Perform all manager checks. | def _check_managers(cls, **kwargs):
""" Perform all manager checks. """
errors = []
for manager in cls._meta.managers:
errors.extend(manager.check(**kwargs))
return errors | [
"def",
"_check_managers",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"manager",
"in",
"cls",
".",
"_meta",
".",
"managers",
":",
"errors",
".",
"extend",
"(",
"manager",
".",
"check",
"(",
"*",
"*",
"kwargs",
")"... | [
1342,
4
] | [
1348,
21
] | python | en | ['en', 'en', 'en'] | True |
Model._check_fields | (cls, **kwargs) | Perform all field checks. | Perform all field checks. | def _check_fields(cls, **kwargs):
""" Perform all field checks. """
errors = []
for field in cls._meta.local_fields:
errors.extend(field.check(**kwargs))
for field in cls._meta.local_many_to_many:
errors.extend(field.check(from_model=cls, **kwargs))
retur... | [
"def",
"_check_fields",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"[",
"]",
"for",
"field",
"in",
"cls",
".",
"_meta",
".",
"local_fields",
":",
"errors",
".",
"extend",
"(",
"field",
".",
"check",
"(",
"*",
"*",
"kwargs",
")",
... | [
1351,
4
] | [
1359,
21
] | python | en | ['en', 'sk', 'en'] | True |
Model._check_m2m_through_same_relationship | (cls) | Check if no relationship model is used by more than one m2m field.
| Check if no relationship model is used by more than one m2m field.
| def _check_m2m_through_same_relationship(cls):
""" Check if no relationship model is used by more than one m2m field.
"""
errors = []
seen_intermediary_signatures = []
fields = cls._meta.local_many_to_many
# Skip when the target model wasn't found.
fields = (f ... | [
"def",
"_check_m2m_through_same_relationship",
"(",
"cls",
")",
":",
"errors",
"=",
"[",
"]",
"seen_intermediary_signatures",
"=",
"[",
"]",
"fields",
"=",
"cls",
".",
"_meta",
".",
"local_many_to_many",
"# Skip when the target model wasn't found.",
"fields",
"=",
"("... | [
1362,
4
] | [
1390,
21
] | python | en | ['en', 'en', 'en'] | True |
Model._check_id_field | (cls) | Check if `id` field is a primary key. | Check if `id` field is a primary key. | def _check_id_field(cls):
""" Check if `id` field is a primary key. """
fields = list(f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk)
# fields is empty or consists of the invalid "id" field
if fields and not fields[0].primary_key and cls._meta.pk.name == 'id':
... | [
"def",
"_check_id_field",
"(",
"cls",
")",
":",
"fields",
"=",
"list",
"(",
"f",
"for",
"f",
"in",
"cls",
".",
"_meta",
".",
"local_fields",
"if",
"f",
".",
"name",
"==",
"'id'",
"and",
"f",
"!=",
"cls",
".",
"_meta",
".",
"pk",
")",
"# fields is e... | [
1393,
4
] | [
1407,
21
] | python | en | ['en', 'en', 'en'] | True |
Model._check_field_name_clashes | (cls) | Ref #17673. | Ref #17673. | def _check_field_name_clashes(cls):
""" Ref #17673. """
errors = []
used_fields = {} # name or attname -> field
# Check that multi-inheritance doesn't cause field name shadowing.
for parent in cls._meta.get_parent_list():
for f in parent._meta.local_fields:
... | [
"def",
"_check_field_name_clashes",
"(",
"cls",
")",
":",
"errors",
"=",
"[",
"]",
"used_fields",
"=",
"{",
"}",
"# name or attname -> field",
"# Check that multi-inheritance doesn't cause field name shadowing.",
"for",
"parent",
"in",
"cls",
".",
"_meta",
".",
"get_par... | [
1410,
4
] | [
1465,
21
] | python | en | ['en', 'kk', 'ur'] | False |
Model._check_index_together | (cls) | Check the value of "index_together" option. | Check the value of "index_together" option. | def _check_index_together(cls):
""" Check the value of "index_together" option. """
if not isinstance(cls._meta.index_together, (tuple, list)):
return [
checks.Error(
"'index_together' must be a list or tuple.",
obj=cls,
... | [
"def",
"_check_index_together",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
".",
"_meta",
".",
"index_together",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"[",
"checks",
".",
"Error",
"(",
"\"'index_together' must be a list or... | [
1517,
4
] | [
1541,
25
] | python | en | ['en', 'en', 'en'] | True |
Model._check_unique_together | (cls) | Check the value of "unique_together" option. | Check the value of "unique_together" option. | def _check_unique_together(cls):
""" Check the value of "unique_together" option. """
if not isinstance(cls._meta.unique_together, (tuple, list)):
return [
checks.Error(
"'unique_together' must be a list or tuple.",
obj=cls,
... | [
"def",
"_check_unique_together",
"(",
"cls",
")",
":",
"if",
"not",
"isinstance",
"(",
"cls",
".",
"_meta",
".",
"unique_together",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"return",
"[",
"checks",
".",
"Error",
"(",
"\"'unique_together' must be a list... | [
1544,
4
] | [
1568,
25
] | python | en | ['en', 'en', 'en'] | True |
Model._check_ordering | (cls) | Check "ordering" option -- is it a list of strings and do all fields
exist? | Check "ordering" option -- is it a list of strings and do all fields
exist? | def _check_ordering(cls):
""" Check "ordering" option -- is it a list of strings and do all fields
exist? """
if cls._meta._ordering_clash:
return [
checks.Error(
"'ordering' and 'order_with_respect_to' cannot be used together.",
... | [
"def",
"_check_ordering",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"_meta",
".",
"_ordering_clash",
":",
"return",
"[",
"checks",
".",
"Error",
"(",
"\"'ordering' and 'order_with_respect_to' cannot be used together.\"",
",",
"obj",
"=",
"cls",
",",
"id",
"=",
"'m... | [
1619,
4
] | [
1681,
21
] | python | en | ['en', 'en', 'en'] | True |
Model._check_long_column_names | (cls) |
Check that any auto-generated column names are shorter than the limits
for each database in which the model will be created.
|
Check that any auto-generated column names are shorter than the limits
for each database in which the model will be created.
| def _check_long_column_names(cls):
"""
Check that any auto-generated column names are shorter than the limits
for each database in which the model will be created.
"""
errors = []
allowed_len = None
db_alias = None
# Find the minimum max allowed length am... | [
"def",
"_check_long_column_names",
"(",
"cls",
")",
":",
"errors",
"=",
"[",
"]",
"allowed_len",
"=",
"None",
"db_alias",
"=",
"None",
"# Find the minimum max allowed length among all specified db_aliases.",
"for",
"db",
"in",
"settings",
".",
"DATABASES",
".",
"keys"... | [
1684,
4
] | [
1754,
21
] | python | en | ['en', 'error', 'th'] | False |
AWXProfiler.__init__ | (self, name, dest='/var/log/tower/profile', dot_enabled=True) |
Try to do as little as possible in init. Instead, do the init
only when the profiling is started.
|
Try to do as little as possible in init. Instead, do the init
only when the profiling is started.
| def __init__(self, name, dest='/var/log/tower/profile', dot_enabled=True):
"""
Try to do as little as possible in init. Instead, do the init
only when the profiling is started.
"""
super().__init__(name, dest)
self.started = False
self.dot_enabled = dot_enabled
... | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"dest",
"=",
"'/var/log/tower/profile'",
",",
"dot_enabled",
"=",
"True",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"name",
",",
"dest",
")",
"self",
".",
"started",
"=",
"False",
"self",
".",
... | [
73,
4
] | [
83,
9
] | python | en | ['en', 'error', 'th'] | False |
str_to_display | (data, desc=None) |
For display or logging purposes, convert a bytes object (or text) to
text (e.g. unicode in Python 2) safe for output.
:param desc: An optional phrase describing the input data, for use in
the log message if a warning is logged. Defaults to "Bytes object".
This function should never error out ... |
For display or logging purposes, convert a bytes object (or text) to
text (e.g. unicode in Python 2) safe for output. | def str_to_display(data, desc=None):
# type: (Union[bytes, Text], Optional[str]) -> Text
"""
For display or logging purposes, convert a bytes object (or text) to
text (e.g. unicode in Python 2) safe for output.
:param desc: An optional phrase describing the input data, for use in
the log me... | [
"def",
"str_to_display",
"(",
"data",
",",
"desc",
"=",
"None",
")",
":",
"# type: (Union[bytes, Text], Optional[str]) -> Text",
"if",
"isinstance",
"(",
"data",
",",
"text_type",
")",
":",
"return",
"data",
"# Otherwise, data is a bytes object (str in Python 2).",
"# Fir... | [
97,
0
] | [
161,
23
] | python | en | ['en', 'error', 'th'] | False |
console_to_str | (data) | Return a string, safe for output, of subprocess output.
| Return a string, safe for output, of subprocess output.
| def console_to_str(data):
# type: (bytes) -> Text
"""Return a string, safe for output, of subprocess output.
"""
return str_to_display(data, desc='Subprocess output') | [
"def",
"console_to_str",
"(",
"data",
")",
":",
"# type: (bytes) -> Text",
"return",
"str_to_display",
"(",
"data",
",",
"desc",
"=",
"'Subprocess output'",
")"
] | [
164,
0
] | [
168,
57
] | python | en | ['en', 'en', 'en'] | True |
get_path_uid | (path) |
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is a symlink or can't be read.
|
Return path's uid. | def get_path_uid(path):
# type: (str) -> int
"""
Return path's uid.
Does not follow symlinks:
https://github.com/pypa/pip/pull/935#discussion_r5307003
Placed this function in compat due to differences on AIX and
Jython, that should eventually go away.
:raises OSError: When path is... | [
"def",
"get_path_uid",
"(",
"path",
")",
":",
"# type: (str) -> int",
"if",
"hasattr",
"(",
"os",
",",
"'O_NOFOLLOW'",
")",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_RDONLY",
"|",
"os",
".",
"O_NOFOLLOW",
")",
"file_uid",
"=",
... | [
171,
0
] | [
199,
19
] | python | en | ['en', 'error', 'th'] | False |
expanduser | (path) |
Expand ~ and ~user constructions.
Includes a workaround for https://bugs.python.org/issue14768
|
Expand ~ and ~user constructions. | def expanduser(path):
# type: (str) -> str
"""
Expand ~ and ~user constructions.
Includes a workaround for https://bugs.python.org/issue14768
"""
expanded = os.path.expanduser(path)
if path.startswith('~/') and expanded.startswith('//'):
expanded = expanded[1:]
return expanded | [
"def",
"expanduser",
"(",
"path",
")",
":",
"# type: (str) -> str",
"expanded",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"if",
"path",
".",
"startswith",
"(",
"'~/'",
")",
"and",
"expanded",
".",
"startswith",
"(",
"'//'",
")",
":",
... | [
202,
0
] | [
212,
19
] | python | en | ['en', 'error', 'th'] | False |
samefile | (file1, file2) | Provide an alternative for os.path.samefile on Windows/Python2 | Provide an alternative for os.path.samefile on Windows/Python2 | def samefile(file1, file2):
# type: (str, str) -> bool
"""Provide an alternative for os.path.samefile on Windows/Python2"""
if hasattr(os.path, 'samefile'):
return os.path.samefile(file1, file2)
else:
path1 = os.path.normcase(os.path.abspath(file1))
path2 = os.path.normcase(os.pa... | [
"def",
"samefile",
"(",
"file1",
",",
"file2",
")",
":",
"# type: (str, str) -> bool",
"if",
"hasattr",
"(",
"os",
".",
"path",
",",
"'samefile'",
")",
":",
"return",
"os",
".",
"path",
".",
"samefile",
"(",
"file1",
",",
"file2",
")",
"else",
":",
"pa... | [
228,
0
] | [
236,
29
] | python | en | ['en', 'ga', 'en'] | True |
require_http_methods | (request_method_list) |
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note that request methods should be in uppercase.
|
Decorator to make a view only accept particular request methods. Usage:: | def require_http_methods(request_method_list):
"""
Decorator to make a view only accept particular request methods. Usage::
@require_http_methods(["GET", "POST"])
def my_view(request):
# I can assume now that only GET or POST requests make it this far
# ...
Note th... | [
"def",
"require_http_methods",
"(",
"request_method_list",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
",",
"assigned",
"=",
"available_attrs",
"(",
"func",
")",
")",
"def",
"inner",
"(",
"request",
",",
"*",
"args",
"... | [
19,
0
] | [
41,
20
] | python | en | ['en', 'error', 'th'] | False |
condition | (etag_func=None, last_modified_func=None) |
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters as the view itself. The ETag function should return a string (o... |
Decorator to support conditional retrieval (or change) for a view
function. | def condition(etag_func=None, last_modified_func=None):
"""
Decorator to support conditional retrieval (or change) for a view
function.
The parameters are callables to compute the ETag and last modified time for
the requested resource, respectively. The callables are passed the same
parameters ... | [
"def",
"condition",
"(",
"etag_func",
"=",
"None",
",",
"last_modified_func",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
",",
"assigned",
"=",
"available_attrs",
"(",
"func",
")",
")",
"def",
"inner",
"... | [
54,
0
] | [
109,
20
] | python | en | ['en', 'error', 'th'] | False |
nested_form_data | (data) |
Translates a nested dict structure into a flat form data dict
with hyphen-separated keys.
.. code-block:: python
nested_form_data({
'foo': 'bar',
'parent': {
'child': 'field',
},
})
# Returns: {'foo': 'bar', 'parent-child': 'fiel... |
Translates a nested dict structure into a flat form data dict
with hyphen-separated keys. | def nested_form_data(data):
"""
Translates a nested dict structure into a flat form data dict
with hyphen-separated keys.
.. code-block:: python
nested_form_data({
'foo': 'bar',
'parent': {
'child': 'field',
},
})
# Returns: {... | [
"def",
"nested_form_data",
"(",
"data",
")",
":",
"return",
"{",
"'-'",
".",
"join",
"(",
"key",
")",
":",
"value",
"for",
"key",
",",
"value",
"in",
"_nested_form_data",
"(",
"data",
")",
"}"
] | [
26,
0
] | [
41,
75
] | python | en | ['en', 'error', 'th'] | False |
streamfield | (items) |
Takes a list of (block_type, value) tuples and turns it in to
StreamField form data. Use this within a :func:`nested_form_data`
call, with the field name as the key.
.. code-block:: python
nested_form_data({'content': streamfield([
('text', 'Hello, world'),
])})
# ... |
Takes a list of (block_type, value) tuples and turns it in to
StreamField form data. Use this within a :func:`nested_form_data`
call, with the field name as the key. | def streamfield(items):
"""
Takes a list of (block_type, value) tuples and turns it in to
StreamField form data. Use this within a :func:`nested_form_data`
call, with the field name as the key.
.. code-block:: python
nested_form_data({'content': streamfield([
('text', 'Hello, w... | [
"def",
"streamfield",
"(",
"items",
")",
":",
"def",
"to_block",
"(",
"index",
",",
"item",
")",
":",
"block",
",",
"value",
"=",
"item",
"return",
"{",
"'type'",
":",
"block",
",",
"'value'",
":",
"value",
",",
"'deleted'",
":",
"''",
",",
"'order'"... | [
44,
0
] | [
70,
20
] | python | en | ['en', 'error', 'th'] | False |
inline_formset | (items, initial=0, min=0, max=1000) |
Takes a list of form data for an InlineFormset and translates
it in to valid POST data. Use this within a :func:`nested_form_data`
call, with the formset relation name as the key.
.. code-block:: python
nested_form_data({'lines': inline_formset([
{'text': 'Hello'},
{'t... |
Takes a list of form data for an InlineFormset and translates
it in to valid POST data. Use this within a :func:`nested_form_data`
call, with the formset relation name as the key. | def inline_formset(items, initial=0, min=0, max=1000):
"""
Takes a list of form data for an InlineFormset and translates
it in to valid POST data. Use this within a :func:`nested_form_data`
call, with the formset relation name as the key.
.. code-block:: python
nested_form_data({'lines': i... | [
"def",
"inline_formset",
"(",
"items",
",",
"initial",
"=",
"0",
",",
"min",
"=",
"0",
",",
"max",
"=",
"1000",
")",
":",
"def",
"to_form",
"(",
"index",
",",
"item",
")",
":",
"defaults",
"=",
"{",
"'ORDER'",
":",
"str",
"(",
"index",
")",
",",
... | [
73,
0
] | [
116,
20
] | python | en | ['en', 'error', 'th'] | False |
rich_text | (value, editor='default', features=None) |
Converts an HTML-like rich text string to the data format required by
the currently active rich text editor.
:param editor: An alternative editor name as defined in ``WAGTAILADMIN_RICH_TEXT_EDITORS``
:param features: A list of features allowed in the rich text content (see :ref:`rich_text_features`)
... |
Converts an HTML-like rich text string to the data format required by
the currently active rich text editor. | def rich_text(value, editor='default', features=None):
"""
Converts an HTML-like rich text string to the data format required by
the currently active rich text editor.
:param editor: An alternative editor name as defined in ``WAGTAILADMIN_RICH_TEXT_EDITORS``
:param features: A list of features allo... | [
"def",
"rich_text",
"(",
"value",
",",
"editor",
"=",
"'default'",
",",
"features",
"=",
"None",
")",
":",
"widget",
"=",
"get_rich_text_editor_widget",
"(",
"editor",
",",
"features",
")",
"return",
"widget",
".",
"format_value",
"(",
"value",
")"
] | [
119,
0
] | [
135,
37
] | python | en | ['en', 'error', 'th'] | False |
group_models_by_index | (backend, models) |
This takes a search backend and a list of models. By calling the
get_index_for_model method on the search backend, it groups the models into
the indices that they will be indexed into.
It returns an ordered mapping of indices to lists of models within each
index.
For example, Elasticsearch 2 ... |
This takes a search backend and a list of models. By calling the
get_index_for_model method on the search backend, it groups the models into
the indices that they will be indexed into. | def group_models_by_index(backend, models):
"""
This takes a search backend and a list of models. By calling the
get_index_for_model method on the search backend, it groups the models into
the indices that they will be indexed into.
It returns an ordered mapping of indices to lists of models within... | [
"def",
"group_models_by_index",
"(",
"backend",
",",
"models",
")",
":",
"indices",
"=",
"{",
"}",
"models_by_index",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"for",
"model",
"in",
"models",
":",
"index",
"=",
"backend",
".",
"get_index_for_model",
... | [
13,
0
] | [
51,
6
] | python | en | ['en', 'error', 'th'] | False |
Command.print_iter_progress | (self, iterable) |
Print a progress meter while iterating over an iterable. Use it as part
of a ``for`` loop::
for item in self.print_iter_progress(big_long_list):
self.do_expensive_computation(item)
A ``.`` character is printed for every value in the iterable,
a space every ... |
Print a progress meter while iterating over an iterable. Use it as part
of a ``for`` loop:: | def print_iter_progress(self, iterable):
"""
Print a progress meter while iterating over an iterable. Use it as part
of a ``for`` loop::
for item in self.print_iter_progress(big_long_list):
self.do_expensive_computation(item)
A ``.`` character is printed for... | [
"def",
"print_iter_progress",
"(",
"self",
",",
"iterable",
")",
":",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"iterable",
",",
"start",
"=",
"1",
")",
":",
"yield",
"value",
"self",
".",
"stdout",
".",
"write",
"(",
"'.'",
",",
"ending",
"=... | [
131,
4
] | [
152,
31
] | python | en | ['en', 'error', 'th'] | False |
Command.queryset_chunks | (self, qs, chunk_size=DEFAULT_CHUNK_SIZE) |
Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded
will be a list, not a queryset. Iterating over the chunks is done in a
transaction so that the order and count of items in the queryset
remains stable.
|
Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded
will be a list, not a queryset. Iterating over the chunks is done in a
transaction so that the order and count of items in the queryset
remains stable.
| def queryset_chunks(self, qs, chunk_size=DEFAULT_CHUNK_SIZE):
"""
Yield a queryset in chunks of at most ``chunk_size``. The chunk yielded
will be a list, not a queryset. Iterating over the chunks is done in a
transaction so that the order and count of items in the queryset
remain... | [
"def",
"queryset_chunks",
"(",
"self",
",",
"qs",
",",
"chunk_size",
"=",
"DEFAULT_CHUNK_SIZE",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"items",
"=",
"list",
"(",
"qs",
"[",
"i",
"*",
"chunk_size",
":",
"]",
"[",
":",
"chunk_size",
"]",
")",
... | [
156,
4
] | [
169,
18
] | python | en | ['en', 'error', 'th'] | False |
PageLinkHandler.get_db_attributes | (tag) |
Given an <a> tag that we've identified as a page link embed (because it has a
data-linktype="page" attribute), return a dict of the attributes we should
have on the resulting <a linktype="page"> element.
|
Given an <a> tag that we've identified as a page link embed (because it has a
data-linktype="page" attribute), return a dict of the attributes we should
have on the resulting <a linktype="page"> element.
| def get_db_attributes(tag):
"""
Given an <a> tag that we've identified as a page link embed (because it has a
data-linktype="page" attribute), return a dict of the attributes we should
have on the resulting <a linktype="page"> element.
"""
return {'id': tag['data-id']} | [
"def",
"get_db_attributes",
"(",
"tag",
")",
":",
"return",
"{",
"'id'",
":",
"tag",
"[",
"'data-id'",
"]",
"}"
] | [
158,
4
] | [
164,
37
] | python | en | ['en', 'error', 'th'] | False |
setup_two_nodes | (consensus_constants: ConsensusConstants) |
Setup and teardown of two full nodes, with blockchains and separate DBs.
|
Setup and teardown of two full nodes, with blockchains and separate DBs.
| async def setup_two_nodes(consensus_constants: ConsensusConstants):
"""
Setup and teardown of two full nodes, with blockchains and separate DBs.
"""
node_iters = [
setup_full_node(
consensus_constants, "blockchain_test.db", 21234, BlockTools(constants=test_constants), simulator=False... | [
"async",
"def",
"setup_two_nodes",
"(",
"consensus_constants",
":",
"ConsensusConstants",
")",
":",
"node_iters",
"=",
"[",
"setup_full_node",
"(",
"consensus_constants",
",",
"\"blockchain_test.db\"",
",",
"21234",
",",
"BlockTools",
"(",
"constants",
"=",
"test_cons... | [
311,
0
] | [
329,
37
] | python | en | ['en', 'error', 'th'] | False |
setup_n_nodes | (consensus_constants: ConsensusConstants, n: int) |
Setup and teardown of two full nodes, with blockchains and separate DBs.
|
Setup and teardown of two full nodes, with blockchains and separate DBs.
| async def setup_n_nodes(consensus_constants: ConsensusConstants, n: int):
"""
Setup and teardown of two full nodes, with blockchains and separate DBs.
"""
port_start = 21244
node_iters = []
for i in range(n):
node_iters.append(
setup_full_node(
consensus_const... | [
"async",
"def",
"setup_n_nodes",
"(",
"consensus_constants",
":",
"ConsensusConstants",
",",
"n",
":",
"int",
")",
":",
"port_start",
"=",
"21244",
"node_iters",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"node_iters",
".",
"append",
"... | [
332,
0
] | [
354,
37
] | python | en | ['en', 'error', 'th'] | False |
Site.find_for_request | (request) |
Find the site object responsible for responding to this HTTP
request object. Try:
* unique hostname first
* then hostname and port
* if there is no matching hostname at all, or no matching
hostname:port combination, fall back to the unique default site,
or r... |
Find the site object responsible for responding to this HTTP
request object. Try: | def find_for_request(request):
"""
Find the site object responsible for responding to this HTTP
request object. Try:
* unique hostname first
* then hostname and port
* if there is no matching hostname at all, or no matching
hostname:port combination, fall back ... | [
"def",
"find_for_request",
"(",
"request",
")",
":",
"if",
"request",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"request",
",",
"'_wagtail_site'",
")",
":",
"site",
"=",
"Site",
".",
"_find_for_request",
"(",
"request",
")",
"setatt... | [
75,
4
] | [
98,
36
] | python | en | ['en', 'error', 'th'] | False |
Site.get_site_root_paths | () |
Return a list of `SiteRootPath` instances, most specific path
first - used to translate url_paths into actual URLs with hostnames
Each root path is an instance of the `SiteRootPath` named tuple,
and have the following attributes:
- `site_id` - The ID of the Site record
... |
Return a list of `SiteRootPath` instances, most specific path
first - used to translate url_paths into actual URLs with hostnames | def get_site_root_paths():
"""
Return a list of `SiteRootPath` instances, most specific path
first - used to translate url_paths into actual URLs with hostnames
Each root path is an instance of the `SiteRootPath` named tuple,
and have the following attributes:
- `site_i... | [
"def",
"get_site_root_paths",
"(",
")",
":",
"result",
"=",
"cache",
".",
"get",
"(",
"'wagtail_site_root_paths'",
")",
"# Wagtail 2.11 changed the way site root paths were stored. This can cause an upgraded 2.11",
"# site to break when loading cached site root paths that were cached wit... | [
143,
4
] | [
176,
21
] | python | en | ['en', 'error', 'th'] | False |
FieldsFilter.filter_queryset | (self, request, queryset, view) |
This performs field level filtering on the result set
Eg: ?title=James Joyce
|
This performs field level filtering on the result set
Eg: ?title=James Joyce
| def filter_queryset(self, request, queryset, view):
"""
This performs field level filtering on the result set
Eg: ?title=James Joyce
"""
fields = set(view.get_available_fields(queryset.model, db_fields_only=True))
# Locale is a database field, but we provide a separate f... | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"fields",
"=",
"set",
"(",
"view",
".",
"get_available_fields",
"(",
"queryset",
".",
"model",
",",
"db_fields_only",
"=",
"True",
")",
")",
"# Locale is a databas... | [
14,
4
] | [
58,
23
] | python | en | ['en', 'error', 'th'] | False |
OrderingFilter.filter_queryset | (self, request, queryset, view) |
This applies ordering to the result set
Eg: ?order=title
It also supports reverse ordering
Eg: ?order=-title
And random ordering
Eg: ?order=random
|
This applies ordering to the result set
Eg: ?order=title | def filter_queryset(self, request, queryset, view):
"""
This applies ordering to the result set
Eg: ?order=title
It also supports reverse ordering
Eg: ?order=-title
And random ordering
Eg: ?order=random
"""
if 'order' in request.GET:
... | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"if",
"'order'",
"in",
"request",
".",
"GET",
":",
"order_by",
"=",
"request",
".",
"GET",
"[",
"'order'",
"]",
"# Random ordering",
"if",
"order_by",
"==",
"'... | [
62,
4
] | [
102,
23
] | python | en | ['en', 'error', 'th'] | False |
SearchFilter.filter_queryset | (self, request, queryset, view) |
This performs a full-text search on the result set
Eg: ?search=James Joyce
|
This performs a full-text search on the result set
Eg: ?search=James Joyce
| def filter_queryset(self, request, queryset, view):
"""
This performs a full-text search on the result set
Eg: ?search=James Joyce
"""
search_enabled = getattr(settings, 'WAGTAILAPI_SEARCH_ENABLED', True)
if 'search' in request.GET:
if not search_enabled:
... | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"search_enabled",
"=",
"getattr",
"(",
"settings",
",",
"'WAGTAILAPI_SEARCH_ENABLED'",
",",
"True",
")",
"if",
"'search'",
"in",
"request",
".",
"GET",
":",
"if",
... | [
106,
4
] | [
133,
23
] | 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.