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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
is_double_callable | (application) |
Tests to see if an application is a legacy-style (double-callable) application.
|
Tests to see if an application is a legacy-style (double-callable) application.
| def is_double_callable(application):
"""
Tests to see if an application is a legacy-style (double-callable) application.
"""
# Look for a hint on the object first
if getattr(application, "_asgi_single_callable", False):
return False
if getattr(application, "_asgi_double_callable", False)... | [
"def",
"is_double_callable",
"(",
"application",
")",
":",
"# Look for a hint on the object first",
"if",
"getattr",
"(",
"application",
",",
"\"_asgi_single_callable\"",
",",
"False",
")",
":",
"return",
"False",
"if",
"getattr",
"(",
"application",
",",
"\"_asgi_dou... | [
4,
0
] | [
23,
55
] | python | en | ['en', 'error', 'th'] | False |
double_to_single_callable | (application) |
Transforms a double-callable ASGI application into a single-callable one.
|
Transforms a double-callable ASGI application into a single-callable one.
| def double_to_single_callable(application):
"""
Transforms a double-callable ASGI application into a single-callable one.
"""
async def new_application(scope, receive, send):
instance = application(scope)
return await instance(receive, send)
return new_application | [
"def",
"double_to_single_callable",
"(",
"application",
")",
":",
"async",
"def",
"new_application",
"(",
"scope",
",",
"receive",
",",
"send",
")",
":",
"instance",
"=",
"application",
"(",
"scope",
")",
"return",
"await",
"instance",
"(",
"receive",
",",
"... | [
26,
0
] | [
35,
26
] | python | en | ['en', 'error', 'th'] | False |
guarantee_single_callable | (application) |
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
|
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
| def guarantee_single_callable(application):
"""
Takes either a single- or double-callable application and always returns it
in single-callable style. Use this to add backwards compatibility for ASGI
2.0 applications to your server/test harness/etc.
"""
if is_double_callable(application):
... | [
"def",
"guarantee_single_callable",
"(",
"application",
")",
":",
"if",
"is_double_callable",
"(",
"application",
")",
":",
"application",
"=",
"double_to_single_callable",
"(",
"application",
")",
"return",
"application"
] | [
38,
0
] | [
46,
22
] | python | en | ['en', 'error', 'th'] | False |
capture | (args, env=None) | capture(command) - Run the given command (or argv list) in a shell and
return the standard output. Raises a CalledProcessError if the command
exits with a non-zero status. | capture(command) - Run the given command (or argv list) in a shell and
return the standard output. Raises a CalledProcessError if the command
exits with a non-zero status. | def capture(args, env=None):
"""capture(command) - Run the given command (or argv list) in a shell and
return the standard output. Raises a CalledProcessError if the command
exits with a non-zero status."""
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
... | [
"def",
"capture",
"(",
"args",
",",
"env",
"=",
"None",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"env",
"=",
"env",
")",
"out",
... | [
84,
0
] | [
97,
14
] | python | en | ['en', 'en', 'en'] | True |
which | (command, paths = None) | which(command, [paths]) - Look up the given command in the paths string
(or the PATH environment variable, if unspecified). | which(command, [paths]) - Look up the given command in the paths string
(or the PATH environment variable, if unspecified). | def which(command, paths = None):
"""which(command, [paths]) - Look up the given command in the paths string
(or the PATH environment variable, if unspecified)."""
if paths is None:
paths = os.environ.get('PATH','')
# Check for absolute match first.
if os.path.isfile(command):
retu... | [
"def",
"which",
"(",
"command",
",",
"paths",
"=",
"None",
")",
":",
"if",
"paths",
"is",
"None",
":",
"paths",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
"# Check for absolute match first.",
"if",
"os",
".",
"path",
".",
"... | [
100,
0
] | [
129,
15
] | python | en | ['en', 'en', 'en'] | True |
mkdir_p | (path) | mkdir_p(path) - Make the "path" directory, if it does not exist; this
will also make directories for any missing parent directories. | mkdir_p(path) - Make the "path" directory, if it does not exist; this
will also make directories for any missing parent directories. | def mkdir_p(path):
"""mkdir_p(path) - Make the "path" directory, if it does not exist; this
will also make directories for any missing parent directories."""
if not path or os.path.exists(path):
return
parent = os.path.dirname(path)
if parent != path:
mkdir_p(parent)
try:
... | [
"def",
"mkdir_p",
"(",
"path",
")",
":",
"if",
"not",
"path",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"parent",
"!=",
"path",
":",
"mkdir_p... | [
145,
0
] | [
161,
17
] | python | en | ['en', 'en', 'en'] | True |
executeCommand | (command, cwd=None, env=None, input=None, timeout=0) |
Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input... |
Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
* Input to the command ``input`` (str), use string to pass
no input... | def executeCommand(command, cwd=None, env=None, input=None, timeout=0):
"""
Execute command ``command`` (list of arguments or string)
with
* working directory ``cwd`` (str), use None to use the current
working directory
* environment ``env`` (dict), use None for none
... | [
"def",
"executeCommand",
"(",
"command",
",",
"cwd",
"=",
"None",
",",
"env",
"=",
"None",
",",
"input",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"if",
"input",
"is",
"not",
"None",
":",
"input",
"=",
"to_bytes",
"(",
"input",
")",
"p",
"... | [
178,
0
] | [
243,
29
] | python | en | ['en', 'error', 'th'] | False |
killProcessAndChildren | (pid) |
This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation.
TODO: Reimplement this without using psutil so we can
remove our dependency on it.
|
This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation. | def killProcessAndChildren(pid):
"""
This function kills a process with ``pid`` and all its
running children (recursively). It is currently implemented
using the psutil module which provides a simple platform
neutral implementation.
TODO: Reimplement this without using psutil so we can
... | [
"def",
"killProcessAndChildren",
"(",
"pid",
")",
":",
"import",
"psutil",
"try",
":",
"psutilProc",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"# Handle the different psutil API versions",
"try",
":",
"# psutil >= 2.x",
"children_iterator",
"=",
"psutilProc",
... | [
246,
0
] | [
273,
12
] | python | en | ['en', 'error', 'th'] | False |
executeCommandVerbose | (cmd, *args, **kwargs) |
Execute a command and print its output on failure.
|
Execute a command and print its output on failure.
| def executeCommandVerbose(cmd, *args, **kwargs):
"""
Execute a command and print its output on failure.
"""
out, err, exitCode = executeCommand(cmd, *args, **kwargs)
if exitCode != 0:
report = makeReport(cmd, out, err, exitCode)
report += "\n\nFailed!"
sys.stderr.write('%s\n'... | [
"def",
"executeCommandVerbose",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
",",
"err",
",",
"exitCode",
"=",
"executeCommand",
"(",
"cmd",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"exitCode",
"!=",
"0",
":"... | [
276,
0
] | [
285,
29
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.__init__ | (self, args) |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, args):
"""
TODO: Write Comment
"""
Attack.__init__(self, args)
self.set_ES(args.evolutionary_strategy)
self.POPSIZE = self.args.pop_size
self.MAXITER = self.args.max_iter
self.THRESHOLD = self.args.thresho... | [
"def",
"__init__",
"(",
"self",
",",
"args",
")",
":",
"Attack",
".",
"__init__",
"(",
"self",
",",
"args",
")",
"self",
".",
"set_ES",
"(",
"args",
".",
"evolutionary_strategy",
")",
"self",
".",
"POPSIZE",
"=",
"self",
".",
"args",
".",
"pop_size",
... | [
16,
4
] | [
27,
44
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.set_ES | (self, no=1) |
TODO: Write Comment
|
TODO: Write Comment
| def set_ES(self, no=1):
"""
TODO: Write Comment
"""
if no == 0:
self.DE, self.CMAES = True, False
self.attack_name += '_DE'
elif no == 1:
self.DE, self.CMAES = False, True
self.attack_name... | [
"def",
"set_ES",
"(",
"self",
",",
"no",
"=",
"1",
")",
":",
"if",
"no",
"==",
"0",
":",
"self",
".",
"DE",
",",
"self",
".",
"CMAES",
"=",
"True",
",",
"False",
"self",
".",
"attack_name",
"+=",
"'_DE'",
"elif",
"no",
"==",
"1",
":",
"self",
... | [
29,
4
] | [
44,
98
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.predict_classes | (self, xs, target_class) |
TODO: Write Comment
|
TODO: Write Comment
| def predict_classes(self, xs, target_class):
"""
TODO: Write Comment
"""
predictions = self.model.predict(self.perturb_image(xs))[:,target_class]
return predictions if not self.TARGETED else 1 - predictions | [
"def",
"predict_classes",
"(",
"self",
",",
"xs",
",",
"target_class",
")",
":",
"predictions",
"=",
"self",
".",
"model",
".",
"predict",
"(",
"self",
".",
"perturb_image",
"(",
"xs",
")",
")",
"[",
":",
",",
"target_class",
"]",
"return",
"predictions"... | [
47,
4
] | [
53,
68
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.attack_success | (self, xs, target_class) |
TODO: Write Comment
|
TODO: Write Comment
| def attack_success(self, xs, target_class):
"""
TODO: Write Comment
"""
predicted_class = np.argmax(self.model.predict(self.perturb_image(xs))[0])
if ((self.TARGETED and predicted_class == target_class) or (not self.TARGETED and predicted_class != target_class))... | [
"def",
"attack_success",
"(",
"self",
",",
"xs",
",",
"target_class",
")",
":",
"predicted_class",
"=",
"np",
".",
"argmax",
"(",
"self",
".",
"model",
".",
"predict",
"(",
"self",
".",
"perturb_image",
"(",
"xs",
")",
")",
"[",
"0",
"]",
")",
"if",
... | [
56,
4
] | [
63,
136
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.attack | (self, target_class, th) |
TODO: Write Comment
|
TODO: Write Comment
| def attack(self, target_class, th):
"""
TODO: Write Comment
"""
bounds, initial = self.get_bounds(th)
predict_fn = lambda xs: self.predict_classes(xs, target_class)
if self.DE:
callback_f... | [
"def",
"attack",
"(",
"self",
",",
"target_class",
",",
"th",
")",
":",
"bounds",
",",
"initial",
"=",
"self",
".",
"get_bounds",
"(",
"th",
")",
"predict_fn",
"=",
"lambda",
"xs",
":",
"self",
".",
"predict_classes",
"(",
"xs",
",",
"target_class",
")... | [
66,
4
] | [
120,
21
] | python | en | ['en', 'error', 'th'] | False |
OurAttack.attack_image | (self, target_class) |
TODO: Write Comment
|
TODO: Write Comment
| def attack_image(self, target_class):
"""
TODO: Write Comment
"""
image_results = []
if self.THRESHOLD == -1:
start, end = 1, 255
while True:
threshold = (start + end) // 2
if self.VERBOSE: print(f"[#][.]At... | [
"def",
"attack_image",
"(",
"self",
",",
"target_class",
")",
":",
"image_results",
"=",
"[",
"]",
"if",
"self",
".",
"THRESHOLD",
"==",
"-",
"1",
":",
"start",
",",
"end",
"=",
"1",
",",
"255",
"while",
"True",
":",
"threshold",
"=",
"(",
"start",
... | [
123,
4
] | [
159,
28
] | python | en | ['en', 'error', 'th'] | False |
PixelAttack.__init__ | (self, args) |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, args):
"""
TODO: Write Comment
"""
OurAttack.__init__(self, args) | [
"def",
"__init__",
"(",
"self",
",",
"args",
")",
":",
"OurAttack",
".",
"__init__",
"(",
"self",
",",
"args",
")"
] | [
167,
4
] | [
172,
38
] | python | en | ['en', 'error', 'th'] | False |
PixelAttack.set_attack_name | (self) |
TODO: Write Comment
|
TODO: Write Comment
| def set_attack_name(self):
"""
TODO: Write Comment
"""
self.attack_name = "Pixel" | [
"def",
"set_attack_name",
"(",
"self",
")",
":",
"self",
".",
"attack_name",
"=",
"\"Pixel\""
] | [
174,
4
] | [
179,
34
] | python | en | ['en', 'error', 'th'] | False |
PixelAttack.get_bounds | (self, th) |
TODO: Write Comment
|
TODO: Write Comment
| def get_bounds(self, th):
"""
TODO: Write Comment
"""
initial = []
if self.DE:
bounds = [(0, self.x.shape[-3]), (0, self.x.shape[-2])]
for _ in range(self.x.shape[-1]):
bounds += [(0,255)]
bounds = bounds * th
... | [
"def",
"get_bounds",
"(",
"self",
",",
"th",
")",
":",
"initial",
"=",
"[",
"]",
"if",
"self",
".",
"DE",
":",
"bounds",
"=",
"[",
"(",
"0",
",",
"self",
".",
"x",
".",
"shape",
"[",
"-",
"3",
"]",
")",
",",
"(",
"0",
",",
"self",
".",
"x... | [
181,
4
] | [
223,
30
] | python | en | ['en', 'error', 'th'] | False |
PixelAttack.perturb_image | (self, x) |
TODO: Write Comment
|
TODO: Write Comment
| def perturb_image(self, x):
"""
TODO: Write Comment
"""
if x.ndim < 2:
x = np.array([x])
imgs = np.tile(self.x, [len(x)] + [1] * (x.ndim + 1))
x = x.astype(int)
for adv, image in zip(x, imgs):
for pixel in np.split(adv, len(adv) //... | [
"def",
"perturb_image",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
".",
"ndim",
"<",
"2",
":",
"x",
"=",
"np",
".",
"array",
"(",
"[",
"x",
"]",
")",
"imgs",
"=",
"np",
".",
"tile",
"(",
"self",
".",
"x",
",",
"[",
"len",
"(",
"x",
")",
... | [
225,
4
] | [
240,
19
] | python | en | ['en', 'error', 'th'] | False |
ThresholdAttack.__init__ | (self, args) |
TODO: Write Comment
|
TODO: Write Comment
| def __init__(self, args):
"""
TODO: Write Comment
"""
OurAttack.__init__(self, args) | [
"def",
"__init__",
"(",
"self",
",",
"args",
")",
":",
"OurAttack",
".",
"__init__",
"(",
"self",
",",
"args",
")"
] | [
248,
4
] | [
252,
38
] | python | en | ['en', 'error', 'th'] | False |
ThresholdAttack.set_attack_name | (self) |
TODO: Write Comment
|
TODO: Write Comment
| def set_attack_name(self):
"""
TODO: Write Comment
"""
self.attack_name = "Threshold" | [
"def",
"set_attack_name",
"(",
"self",
")",
":",
"self",
".",
"attack_name",
"=",
"\"Threshold\""
] | [
255,
4
] | [
260,
38
] | python | en | ['en', 'error', 'th'] | False |
Marker.evaluate | (self, environment=None) | Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.
| Evaluate a marker. | def evaluate(self, environment=None):
# type: (Optional[Dict[str, str]]) -> bool
"""Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
... | [
"def",
"evaluate",
"(",
"self",
",",
"environment",
"=",
"None",
")",
":",
"# type: (Optional[Dict[str, str]]) -> bool",
"current_environment",
"=",
"default_environment",
"(",
")",
"if",
"environment",
"is",
"not",
"None",
":",
"current_environment",
".",
"update",
... | [
313,
4
] | [
327,
68
] | python | en | ['en', 'en', 'en'] | True |
RedisCache.clear | (self) | Helper for clearing all the keys in a database. Use with
caution! | Helper for clearing all the keys in a database. Use with
caution! | def clear(self):
"""Helper for clearing all the keys in a database. Use with
caution!"""
for key in self.conn.keys():
self.conn.delete(key) | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"conn",
".",
"keys",
"(",
")",
":",
"self",
".",
"conn",
".",
"delete",
"(",
"key",
")"
] | [
24,
4
] | [
28,
33
] | python | en | ['en', 'en', 'en'] | True |
RedisCache.close | (self) | Redis uses connection pooling, no need to close the connection. | Redis uses connection pooling, no need to close the connection. | def close(self):
"""Redis uses connection pooling, no need to close the connection."""
pass | [
"def",
"close",
"(",
"self",
")",
":",
"pass"
] | [
30,
4
] | [
32,
12
] | python | en | ['en', 'en', 'en'] | True |
_cf_data_from_bytes | (bytestring) |
Given a bytestring, create a CFData object from it. This CFData object must
be CFReleased by the caller.
|
Given a bytestring, create a CFData object from it. This CFData object must
be CFReleased by the caller.
| def _cf_data_from_bytes(bytestring):
"""
Given a bytestring, create a CFData object from it. This CFData object must
be CFReleased by the caller.
"""
return CoreFoundation.CFDataCreate(
CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)
) | [
"def",
"_cf_data_from_bytes",
"(",
"bytestring",
")",
":",
"return",
"CoreFoundation",
".",
"CFDataCreate",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"bytestring",
",",
"len",
"(",
"bytestring",
")",
")"
] | [
26,
0
] | [
33,
5
] | python | en | ['en', 'error', 'th'] | False |
_cf_dictionary_from_tuples | (tuples) |
Given a list of Python tuples, create an associated CFDictionary.
|
Given a list of Python tuples, create an associated CFDictionary.
| def _cf_dictionary_from_tuples(tuples):
"""
Given a list of Python tuples, create an associated CFDictionary.
"""
dictionary_size = len(tuples)
# We need to get the dictionary keys and values out in the same order.
keys = (t[0] for t in tuples)
values = (t[1] for t in tuples)
cf_keys = ... | [
"def",
"_cf_dictionary_from_tuples",
"(",
"tuples",
")",
":",
"dictionary_size",
"=",
"len",
"(",
"tuples",
")",
"# We need to get the dictionary keys and values out in the same order.",
"keys",
"=",
"(",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"tuples",
")",
"values"... | [
36,
0
] | [
55,
5
] | python | en | ['en', 'error', 'th'] | False |
_cfstr | (py_bstr) |
Given a Python binary data, create a CFString.
The string must be CFReleased by the caller.
|
Given a Python binary data, create a CFString.
The string must be CFReleased by the caller.
| def _cfstr(py_bstr):
"""
Given a Python binary data, create a CFString.
The string must be CFReleased by the caller.
"""
c_str = ctypes.c_char_p(py_bstr)
cf_str = CoreFoundation.CFStringCreateWithCString(
CoreFoundation.kCFAllocatorDefault,
c_str,
CFConst.kCFStringEncodin... | [
"def",
"_cfstr",
"(",
"py_bstr",
")",
":",
"c_str",
"=",
"ctypes",
".",
"c_char_p",
"(",
"py_bstr",
")",
"cf_str",
"=",
"CoreFoundation",
".",
"CFStringCreateWithCString",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"c_str",
",",
"CFConst",
".",
"k... | [
58,
0
] | [
69,
17
] | python | en | ['en', 'error', 'th'] | False |
_create_cfstring_array | (lst) |
Given a list of Python binary data, create an associated CFMutableArray.
The array must be CFReleased by the caller.
Raises an ssl.SSLError on failure.
|
Given a list of Python binary data, create an associated CFMutableArray.
The array must be CFReleased by the caller. | def _create_cfstring_array(lst):
"""
Given a list of Python binary data, create an associated CFMutableArray.
The array must be CFReleased by the caller.
Raises an ssl.SSLError on failure.
"""
cf_arr = None
try:
cf_arr = CoreFoundation.CFArrayCreateMutable(
CoreFoundatio... | [
"def",
"_create_cfstring_array",
"(",
"lst",
")",
":",
"cf_arr",
"=",
"None",
"try",
":",
"cf_arr",
"=",
"CoreFoundation",
".",
"CFArrayCreateMutable",
"(",
"CoreFoundation",
".",
"kCFAllocatorDefault",
",",
"0",
",",
"ctypes",
".",
"byref",
"(",
"CoreFoundation... | [
72,
0
] | [
100,
17
] | python | en | ['en', 'error', 'th'] | False |
_cf_string_to_unicode | (value) |
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
|
Creates a Unicode string from a CFString object. Used entirely for error
reporting. | def _cf_string_to_unicode(value):
"""
Creates a Unicode string from a CFString object. Used entirely for error
reporting.
Yes, it annoys me quite a lot that this function is this complex.
"""
value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))
string = CoreFoundation.CFSt... | [
"def",
"_cf_string_to_unicode",
"(",
"value",
")",
":",
"value_as_void_p",
"=",
"ctypes",
".",
"cast",
"(",
"value",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_void_p",
")",
")",
"string",
"=",
"CoreFoundation",
".",
"CFStringGetCStringPtr",
"(",
... | [
103,
0
] | [
125,
17
] | python | en | ['en', 'error', 'th'] | False |
_assert_no_error | (error, exception_class=None) |
Checks the return code and throws an exception if there is an error to
report
|
Checks the return code and throws an exception if there is an error to
report
| def _assert_no_error(error, exception_class=None):
"""
Checks the return code and throws an exception if there is an error to
report
"""
if error == 0:
return
cf_error_string = Security.SecCopyErrorMessageString(error, None)
output = _cf_string_to_unicode(cf_error_string)
CoreFo... | [
"def",
"_assert_no_error",
"(",
"error",
",",
"exception_class",
"=",
"None",
")",
":",
"if",
"error",
"==",
"0",
":",
"return",
"cf_error_string",
"=",
"Security",
".",
"SecCopyErrorMessageString",
"(",
"error",
",",
"None",
")",
"output",
"=",
"_cf_string_to... | [
128,
0
] | [
146,
33
] | python | en | ['en', 'error', 'th'] | False |
_cert_array_from_pem | (pem_bundle) |
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
|
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
| def _cert_array_from_pem(pem_bundle):
"""
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
"""
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decod... | [
"def",
"_cert_array_from_pem",
"(",
"pem_bundle",
")",
":",
"# Normalize the PEM bundle's line endings.",
"pem_bundle",
"=",
"pem_bundle",
".",
"replace",
"(",
"b\"\\r\\n\"",
",",
"b\"\\n\"",
")",
"der_certs",
"=",
"[",
"base64",
".",
"b64decode",
"(",
"match",
".",... | [
149,
0
] | [
191,
21
] | python | en | ['en', 'error', 'th'] | False |
_is_cert | (item) |
Returns True if a given CFTypeRef is a certificate.
|
Returns True if a given CFTypeRef is a certificate.
| def _is_cert(item):
"""
Returns True if a given CFTypeRef is a certificate.
"""
expected = Security.SecCertificateGetTypeID()
return CoreFoundation.CFGetTypeID(item) == expected | [
"def",
"_is_cert",
"(",
"item",
")",
":",
"expected",
"=",
"Security",
".",
"SecCertificateGetTypeID",
"(",
")",
"return",
"CoreFoundation",
".",
"CFGetTypeID",
"(",
"item",
")",
"==",
"expected"
] | [
194,
0
] | [
199,
55
] | python | en | ['en', 'error', 'th'] | False |
_is_identity | (item) |
Returns True if a given CFTypeRef is an identity.
|
Returns True if a given CFTypeRef is an identity.
| def _is_identity(item):
"""
Returns True if a given CFTypeRef is an identity.
"""
expected = Security.SecIdentityGetTypeID()
return CoreFoundation.CFGetTypeID(item) == expected | [
"def",
"_is_identity",
"(",
"item",
")",
":",
"expected",
"=",
"Security",
".",
"SecIdentityGetTypeID",
"(",
")",
"return",
"CoreFoundation",
".",
"CFGetTypeID",
"(",
"item",
")",
"==",
"expected"
] | [
202,
0
] | [
207,
55
] | python | en | ['en', 'error', 'th'] | False |
_temporary_keychain | () |
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDe... |
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, including calling
SecKeychainDe... | def _temporary_keychain():
"""
This function creates a temporary Mac keychain that we can use to work with
credentials. This keychain uses a one-time password and a temporary file to
store the data. We expect to have one keychain per socket. The returned
SecKeychainRef must be freed by the caller, i... | [
"def",
"_temporary_keychain",
"(",
")",
":",
"# Unfortunately, SecKeychainCreate requires a path to a keychain. This",
"# means we cannot use mkstemp to use a generic temporary file. Instead,",
"# we're going to create a temporary directory and a filename to use there.",
"# This filename will be 8 r... | [
210,
0
] | [
242,
34
] | python | en | ['en', 'error', 'th'] | False |
_load_items_from_file | (keychain, path) |
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
|
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
| def _load_items_from_file(keychain, path):
"""
Given a single file, loads all the trust objects from it into arrays and
the keychain.
Returns a tuple of lists: the first list is a list of identities, the
second a list of certs.
"""
certificates = []
identities = []
result_array = Non... | [
"def",
"_load_items_from_file",
"(",
"keychain",
",",
"path",
")",
":",
"certificates",
"=",
"[",
"]",
"identities",
"=",
"[",
"]",
"result_array",
"=",
"None",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"raw_filedata",
"=",
"f",
... | [
245,
0
] | [
297,
37
] | python | en | ['en', 'error', 'th'] | False |
_load_client_cert_chain | (keychain, *paths) |
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
|
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
| def _load_client_cert_chain(keychain, *paths):
"""
Load certificates and maybe keys from a number of files. Has the end goal
of returning a CFArray containing one SecIdentityRef, and then zero or more
SecCertificateRef objects, suitable for use as a client certificate trust
chain.
"""
# Ok, ... | [
"def",
"_load_client_cert_chain",
"(",
"keychain",
",",
"*",
"paths",
")",
":",
"# Ok, the strategy.",
"#",
"# This relies on knowing that macOS will not give you a SecIdentityRef",
"# unless you have imported a key into a keychain. This is a somewhat",
"# artificial limitation of macOS (f... | [
300,
0
] | [
372,
41
] | python | en | ['en', 'error', 'th'] | False |
_build_tls_unknown_ca_alert | (version) |
Builds a TLS alert record for an unknown CA.
|
Builds a TLS alert record for an unknown CA.
| def _build_tls_unknown_ca_alert(version):
"""
Builds a TLS alert record for an unknown CA.
"""
ver_maj, ver_min = TLS_PROTOCOL_VERSIONS[version]
severity_fatal = 0x02
description_unknown_ca = 0x30
msg = struct.pack(">BB", severity_fatal, description_unknown_ca)
msg_len = len(msg)
rec... | [
"def",
"_build_tls_unknown_ca_alert",
"(",
"version",
")",
":",
"ver_maj",
",",
"ver_min",
"=",
"TLS_PROTOCOL_VERSIONS",
"[",
"version",
"]",
"severity_fatal",
"=",
"0x02",
"description_unknown_ca",
"=",
"0x30",
"msg",
"=",
"struct",
".",
"pack",
"(",
"\">BB\"",
... | [
384,
0
] | [
395,
17
] | python | en | ['en', 'error', 'th'] | False |
test_admin_not_member | (team) | Test to ensure we don't add admin_role as a parent to team.member_role, as
this creates a cycle with organization administration, which we've decided
to remove support for
(2016-06-16) I think this might have been resolved. I'm asserting
this to be true in the mean time.
| Test to ensure we don't add admin_role as a parent to team.member_role, as
this creates a cycle with organization administration, which we've decided
to remove support for | def test_admin_not_member(team):
"""Test to ensure we don't add admin_role as a parent to team.member_role, as
this creates a cycle with organization administration, which we've decided
to remove support for
(2016-06-16) I think this might have been resolved. I'm asserting
this to be true in the me... | [
"def",
"test_admin_not_member",
"(",
"team",
")",
":",
"assert",
"team",
".",
"admin_role",
".",
"is_ancestor_of",
"(",
"team",
".",
"member_role",
")",
"is",
"True"
] | [
4,
0
] | [
13,
67
] | python | en | ['en', 'en', 'en'] | True |
parse | (sql, encoding=None) | Parse sql and return a list of statements.
:param sql: A string containing one or more SQL statements.
:param encoding: The encoding of the statement (optional).
:returns: A tuple of :class:`~sqlparse.sql.Statement` instances.
| Parse sql and return a list of statements. | def parse(sql, encoding=None):
"""Parse sql and return a list of statements.
:param sql: A string containing one or more SQL statements.
:param encoding: The encoding of the statement (optional).
:returns: A tuple of :class:`~sqlparse.sql.Statement` instances.
"""
return tuple(parsestream(sql, ... | [
"def",
"parse",
"(",
"sql",
",",
"encoding",
"=",
"None",
")",
":",
"return",
"tuple",
"(",
"parsestream",
"(",
"sql",
",",
"encoding",
")",
")"
] | [
22,
0
] | [
29,
44
] | python | en | ['en', 'en', 'en'] | True |
parsestream | (stream, encoding=None) | Parses sql statements from file-like object.
:param stream: A file-like object.
:param encoding: The encoding of the stream contents (optional).
:returns: A generator of :class:`~sqlparse.sql.Statement` instances.
| Parses sql statements from file-like object. | def parsestream(stream, encoding=None):
"""Parses sql statements from file-like object.
:param stream: A file-like object.
:param encoding: The encoding of the stream contents (optional).
:returns: A generator of :class:`~sqlparse.sql.Statement` instances.
"""
stack = engine.FilterStack()
s... | [
"def",
"parsestream",
"(",
"stream",
",",
"encoding",
"=",
"None",
")",
":",
"stack",
"=",
"engine",
".",
"FilterStack",
"(",
")",
"stack",
".",
"enable_grouping",
"(",
")",
"return",
"stack",
".",
"run",
"(",
"stream",
",",
"encoding",
")"
] | [
32,
0
] | [
41,
38
] | python | en | ['en', 'en', 'en'] | True |
format | (sql, encoding=None, **options) | Format *sql* according to *options*.
Available options are documented in :ref:`formatting`.
In addition to the formatting options this function accepts the
keyword "encoding" which determines the encoding of the statement.
:returns: The formatted SQL statement as string.
| Format *sql* according to *options*. | def format(sql, encoding=None, **options):
"""Format *sql* according to *options*.
Available options are documented in :ref:`formatting`.
In addition to the formatting options this function accepts the
keyword "encoding" which determines the encoding of the statement.
:returns: The formatted SQL ... | [
"def",
"format",
"(",
"sql",
",",
"encoding",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"stack",
"=",
"engine",
".",
"FilterStack",
"(",
")",
"options",
"=",
"formatter",
".",
"validate_options",
"(",
"options",
")",
"stack",
"=",
"formatter",
"... | [
44,
0
] | [
58,
44
] | python | en | ['en', 'en', 'en'] | True |
split | (sql, encoding=None) | Split *sql* into single statements.
:param sql: A string containing one or more SQL statements.
:param encoding: The encoding of the statement (optional).
:returns: A list of strings.
| Split *sql* into single statements. | def split(sql, encoding=None):
"""Split *sql* into single statements.
:param sql: A string containing one or more SQL statements.
:param encoding: The encoding of the statement (optional).
:returns: A list of strings.
"""
stack = engine.FilterStack()
return [str(stmt).strip() for stmt in st... | [
"def",
"split",
"(",
"sql",
",",
"encoding",
"=",
"None",
")",
":",
"stack",
"=",
"engine",
".",
"FilterStack",
"(",
")",
"return",
"[",
"str",
"(",
"stmt",
")",
".",
"strip",
"(",
")",
"for",
"stmt",
"in",
"stack",
".",
"run",
"(",
"sql",
",",
... | [
61,
0
] | [
69,
67
] | python | en | ['it', 'sl', 'en'] | False |
AppConfig._path_from_module | (self, module) | Attempt to determine app's filesystem path from its module. | Attempt to determine app's filesystem path from its module. | def _path_from_module(self, module):
"""Attempt to determine app's filesystem path from its module."""
# See #21874 for extended discussion of the behavior of this method in
# various cases.
# Convert paths to list because Python 3's _NamespacePath does not
# support indexing.
... | [
"def",
"_path_from_module",
"(",
"self",
",",
"module",
")",
":",
"# See #21874 for extended discussion of the behavior of this method in",
"# various cases.",
"# Convert paths to list because Python 3's _NamespacePath does not",
"# support indexing.",
"paths",
"=",
"list",
"(",
"get... | [
57,
4
] | [
82,
30
] | python | en | ['en', 'en', 'en'] | True |
AppConfig.create | (cls, entry) |
Factory that creates an app config from an entry in INSTALLED_APPS.
|
Factory that creates an app config from an entry in INSTALLED_APPS.
| def create(cls, entry):
"""
Factory that creates an app config from an entry in INSTALLED_APPS.
"""
try:
# If import_module succeeds, entry is a path to an app module,
# which may specify an app config class with default_app_config.
# Otherwise, entry ... | [
"def",
"create",
"(",
"cls",
",",
"entry",
")",
":",
"try",
":",
"# If import_module succeeds, entry is a path to an app module,",
"# which may specify an app config class with default_app_config.",
"# Otherwise, entry is a path to an app config class or an error.",
"module",
"=",
"imp... | [
85,
4
] | [
155,
40
] | python | en | ['en', 'error', 'th'] | False |
AppConfig.get_model | (self, model_name, require_ready=True) |
Returns the model with the given case-insensitive model_name.
Raises LookupError if no model exists with this name.
|
Returns the model with the given case-insensitive model_name. | def get_model(self, model_name, require_ready=True):
"""
Returns the model with the given case-insensitive model_name.
Raises LookupError if no model exists with this name.
"""
if require_ready:
self.apps.check_models_ready()
else:
self.apps.check... | [
"def",
"get_model",
"(",
"self",
",",
"model_name",
",",
"require_ready",
"=",
"True",
")",
":",
"if",
"require_ready",
":",
"self",
".",
"apps",
".",
"check_models_ready",
"(",
")",
"else",
":",
"self",
".",
"apps",
".",
"check_apps_ready",
"(",
")",
"t... | [
157,
4
] | [
171,
81
] | python | en | ['en', 'error', 'th'] | False |
AppConfig.get_models | (self, include_auto_created=False, include_swapped=False) |
Returns an iterable of models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have been swapped out.
Set the corresponding keyword argument to True to include s... |
Returns an iterable of models. | def get_models(self, include_auto_created=False, include_swapped=False):
"""
Returns an iterable of models.
By default, the following models aren't included:
- auto-created models for many-to-many relations without
an explicit intermediate table,
- models that have be... | [
"def",
"get_models",
"(",
"self",
",",
"include_auto_created",
"=",
"False",
",",
"include_swapped",
"=",
"False",
")",
":",
"self",
".",
"apps",
".",
"check_models_ready",
"(",
")",
"for",
"model",
"in",
"self",
".",
"models",
".",
"values",
"(",
")",
"... | [
173,
4
] | [
192,
23
] | python | en | ['en', 'error', 'th'] | False |
AppConfig.ready | (self) |
Override this method in subclasses to run code when Django starts.
|
Override this method in subclasses to run code when Django starts.
| def ready(self):
"""
Override this method in subclasses to run code when Django starts.
""" | [
"def",
"ready",
"(",
"self",
")",
":"
] | [
203,
4
] | [
206,
11
] | python | en | ['en', 'error', 'th'] | False |
build_py.get_data_files | (self) | Generate list of '(package,src_dir,build_dir,filenames)' tuples | Generate list of '(package,src_dir,build_dir,filenames)' tuples | def get_data_files(self):
"""Generate list of '(package,src_dir,build_dir,filenames)' tuples"""
data = []
if not self.packages:
return data
for package in self.packages:
# Locate package source directory
src_dir = self.get_package_dir(package)
... | [
"def",
"get_data_files",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"packages",
":",
"return",
"data",
"for",
"package",
"in",
"self",
".",
"packages",
":",
"# Locate package source directory",
"src_dir",
"=",
"self",
".",
"get... | [
96,
4
] | [
118,
19
] | python | en | ['en', 'af', 'en'] | True |
build_py.find_data_files | (self, package, src_dir) | Return filenames for package's data files in 'src_dir | Return filenames for package's data files in 'src_dir | def find_data_files(self, package, src_dir):
"""Return filenames for package's data files in 'src_dir'"""
globs = (self.package_data.get('', [])
+ self.package_data.get(package, []))
files = []
for pattern in globs:
# Each pattern has to be converted to a pla... | [
"def",
"find_data_files",
"(",
"self",
",",
"package",
",",
"src_dir",
")",
":",
"globs",
"=",
"(",
"self",
".",
"package_data",
".",
"get",
"(",
"''",
",",
"[",
"]",
")",
"+",
"self",
".",
"package_data",
".",
"get",
"(",
"package",
",",
"[",
"]",... | [
120,
4
] | [
131,
20
] | python | en | ['en', 'no', 'en'] | True |
build_py.build_package_data | (self) | Copy data files into build directory | Copy data files into build directory | def build_package_data(self):
"""Copy data files into build directory"""
lastdir = None
for package, src_dir, build_dir, filenames in self.data_files:
for filename in filenames:
target = os.path.join(build_dir, filename)
self.mkpath(os.path.dirname(tar... | [
"def",
"build_package_data",
"(",
"self",
")",
":",
"lastdir",
"=",
"None",
"for",
"package",
",",
"src_dir",
",",
"build_dir",
",",
"filenames",
"in",
"self",
".",
"data_files",
":",
"for",
"filename",
"in",
"filenames",
":",
"target",
"=",
"os",
".",
"... | [
133,
4
] | [
141,
51
] | python | en | ['en', 'en', 'en'] | True |
build_py.get_package_dir | (self, package) | Return the directory, relative to the top of the source
distribution, where package 'package' should be found
(at least according to the 'package_dir' option, if any). | Return the directory, relative to the top of the source
distribution, where package 'package' should be found
(at least according to the 'package_dir' option, if any). | def get_package_dir(self, package):
"""Return the directory, relative to the top of the source
distribution, where package 'package' should be found
(at least according to the 'package_dir' option, if any)."""
path = package.split('.')
if not self.package_dir:
... | [
"def",
"get_package_dir",
"(",
"self",
",",
"package",
")",
":",
"path",
"=",
"package",
".",
"split",
"(",
"'.'",
")",
"if",
"not",
"self",
".",
"package_dir",
":",
"if",
"path",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"*",
"path",
")"... | [
143,
4
] | [
180,
29
] | python | en | ['en', 'en', 'en'] | True |
build_py.find_modules | (self) | Finds individually-specified Python modules, ie. those listed by
module name in 'self.py_modules'. Returns a list of tuples (package,
module_base, filename): 'package' is a tuple of the path through
package-space to the module; 'module_base' is the bare (no
packages, no dots) module nam... | Finds individually-specified Python modules, ie. those listed by
module name in 'self.py_modules'. Returns a list of tuples (package,
module_base, filename): 'package' is a tuple of the path through
package-space to the module; 'module_base' is the bare (no
packages, no dots) module nam... | def find_modules(self):
"""Finds individually-specified Python modules, ie. those listed by
module name in 'self.py_modules'. Returns a list of tuples (package,
module_base, filename): 'package' is a tuple of the path through
package-space to the module; 'module_base' is the bare (no
... | [
"def",
"find_modules",
"(",
"self",
")",
":",
"# Map package names to tuples of useful info about the package:",
"# (package_dir, checked)",
"# package_dir - the directory where we'll find source files for",
"# this package",
"# checked - true if we have checked that the package directory",... | [
231,
4
] | [
281,
22
] | python | en | ['en', 'en', 'en'] | True |
build_py.find_all_modules | (self) | Compute the list of all modules that will be built, whether
they are specified one-module-at-a-time ('self.py_modules') or
by whole packages ('self.packages'). Return a list of tuples
(package, module, module_file), just like 'find_modules()' and
'find_package_modules()' do. | Compute the list of all modules that will be built, whether
they are specified one-module-at-a-time ('self.py_modules') or
by whole packages ('self.packages'). Return a list of tuples
(package, module, module_file), just like 'find_modules()' and
'find_package_modules()' do. | def find_all_modules(self):
"""Compute the list of all modules that will be built, whether
they are specified one-module-at-a-time ('self.py_modules') or
by whole packages ('self.packages'). Return a list of tuples
(package, module, module_file), just like 'find_modules()' and
'... | [
"def",
"find_all_modules",
"(",
"self",
")",
":",
"modules",
"=",
"[",
"]",
"if",
"self",
".",
"py_modules",
":",
"modules",
".",
"extend",
"(",
"self",
".",
"find_modules",
"(",
")",
")",
"if",
"self",
".",
"packages",
":",
"for",
"package",
"in",
"... | [
283,
4
] | [
297,
22
] | python | en | ['en', 'en', 'en'] | True |
BaseHandler.load_middleware | (self) |
Populate middleware lists from settings.MIDDLEWARE (or the deprecated
MIDDLEWARE_CLASSES).
Must be called after the environment is fixed (see __call__ in subclasses).
|
Populate middleware lists from settings.MIDDLEWARE (or the deprecated
MIDDLEWARE_CLASSES). | def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE (or the deprecated
MIDDLEWARE_CLASSES).
Must be called after the environment is fixed (see __call__ in subclasses).
"""
self._request_middleware = []
self._view_middleware = []
... | [
"def",
"load_middleware",
"(",
"self",
")",
":",
"self",
".",
"_request_middleware",
"=",
"[",
"]",
"self",
".",
"_view_middleware",
"=",
"[",
"]",
"self",
".",
"_template_response_middleware",
"=",
"[",
"]",
"self",
".",
"_response_middleware",
"=",
"[",
"]... | [
34,
4
] | [
106,
40
] | python | en | ['en', 'error', 'th'] | False |
BaseHandler.get_response | (self, request) | Return an HttpResponse object for the given HttpRequest. | Return an HttpResponse object for the given HttpRequest. | def get_response(self, request):
"""Return an HttpResponse object for the given HttpRequest."""
# Setup default url resolver for this thread
set_urlconf(settings.ROOT_URLCONF)
response = self._middleware_chain(request)
# This block is only needed for legacy MIDDLEWARE_CLASSES; ... | [
"def",
"get_response",
"(",
"self",
",",
"request",
")",
":",
"# Setup default url resolver for this thread",
"set_urlconf",
"(",
"settings",
".",
"ROOT_URLCONF",
")",
"response",
"=",
"self",
".",
"_middleware_chain",
"(",
"request",
")",
"# This block is only needed f... | [
118,
4
] | [
154,
23
] | python | en | ['en', 'en', 'en'] | True |
BaseHandler._get_response | (self, request) |
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
|
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
| def _get_response(self, request):
"""
Resolve and call the view, then apply view, exception, and
template_response middleware. This method is everything that happens
inside the request/response middleware.
"""
response = None
if hasattr(request, 'urlconf'):
... | [
"def",
"_get_response",
"(",
"self",
",",
"request",
")",
":",
"response",
"=",
"None",
"if",
"hasattr",
"(",
"request",
",",
"'urlconf'",
")",
":",
"urlconf",
"=",
"request",
".",
"urlconf",
"set_urlconf",
"(",
"urlconf",
")",
"resolver",
"=",
"get_resolv... | [
156,
4
] | [
218,
23
] | python | en | ['en', 'error', 'th'] | False |
BaseHandler.process_exception_by_middleware | (self, exception, request) |
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
|
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
| def process_exception_by_middleware(self, exception, request):
"""
Pass the exception to the exception middleware. If no middleware
return a response for this exception, raise it.
"""
for middleware_method in self._exception_middleware:
response = middleware_method(re... | [
"def",
"process_exception_by_middleware",
"(",
"self",
",",
"exception",
",",
"request",
")",
":",
"for",
"middleware_method",
"in",
"self",
".",
"_exception_middleware",
":",
"response",
"=",
"middleware_method",
"(",
"request",
",",
"exception",
")",
"if",
"resp... | [
220,
4
] | [
229,
13
] | python | en | ['en', 'error', 'th'] | False |
BaseHandler.handle_uncaught_exception | (self, request, resolver, exc_info) | Allow subclasses to override uncaught exception handling. | Allow subclasses to override uncaught exception handling. | def handle_uncaught_exception(self, request, resolver, exc_info):
"""Allow subclasses to override uncaught exception handling."""
return handle_uncaught_exception(request, resolver, exc_info) | [
"def",
"handle_uncaught_exception",
"(",
"self",
",",
"request",
",",
"resolver",
",",
"exc_info",
")",
":",
"return",
"handle_uncaught_exception",
"(",
"request",
",",
"resolver",
",",
"exc_info",
")"
] | [
231,
4
] | [
233,
69
] | python | en | ['en', 'en', 'en'] | True |
BaseHandler._legacy_get_response | (self, request) |
Apply process_request() middleware and call the main _get_response(),
if needed. Used only for legacy MIDDLEWARE_CLASSES.
|
Apply process_request() middleware and call the main _get_response(),
if needed. Used only for legacy MIDDLEWARE_CLASSES.
| def _legacy_get_response(self, request):
"""
Apply process_request() middleware and call the main _get_response(),
if needed. Used only for legacy MIDDLEWARE_CLASSES.
"""
response = None
# Apply request middleware
for middleware_method in self._request_middleware:... | [
"def",
"_legacy_get_response",
"(",
"self",
",",
"request",
")",
":",
"response",
"=",
"None",
"# Apply request middleware",
"for",
"middleware_method",
"in",
"self",
".",
"_request_middleware",
":",
"response",
"=",
"middleware_method",
"(",
"request",
")",
"if",
... | [
235,
4
] | [
249,
23
] | python | en | ['en', 'error', 'th'] | False |
TestChoosePubDate.test_choose_date_sent_large_tot_messages | (self) |
Test for a bug that was present, where specifying a large amount of messages to generate
would cause each message to have date_sent set to timezone_now(), instead of the date_sents
being distributed across the span of several days.
|
Test for a bug that was present, where specifying a large amount of messages to generate
would cause each message to have date_sent set to timezone_now(), instead of the date_sents
being distributed across the span of several days.
| def test_choose_date_sent_large_tot_messages(self) -> None:
"""
Test for a bug that was present, where specifying a large amount of messages to generate
would cause each message to have date_sent set to timezone_now(), instead of the date_sents
being distributed across the span of severa... | [
"def",
"test_choose_date_sent_large_tot_messages",
"(",
"self",
")",
"->",
"None",
":",
"tot_messages",
"=",
"1000000",
"datetimes_list",
"=",
"[",
"choose_date_sent",
"(",
"i",
",",
"tot_messages",
",",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"t... | [
7,
4
] | [
23,
13
] | python | en | ['en', 'error', 'th'] | False |
interpret | (marker, execution_context=None) |
Interpret a marker and return a result depending on environment.
:param marker: The marker to interpret.
:type marker: str
:param execution_context: The context used for name lookup.
:type execution_context: mapping
|
Interpret a marker and return a result depending on environment. | def interpret(marker, execution_context=None):
"""
Interpret a marker and return a result depending on environment.
:param marker: The marker to interpret.
:type marker: str
:param execution_context: The context used for name lookup.
:type execution_context: mapping
"""
try:
exp... | [
"def",
"interpret",
"(",
"marker",
",",
"execution_context",
"=",
"None",
")",
":",
"try",
":",
"expr",
",",
"rest",
"=",
"parse_marker",
"(",
"marker",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"SyntaxError",
"(",
"'Unable to interpret marker synta... | [
112,
0
] | [
130,
44
] | python | en | ['en', 'error', 'th'] | False |
Evaluator.evaluate | (self, expr, context) |
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
|
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
| def evaluate(self, expr, context):
"""
Evaluate a marker expression returned by the :func:`parse_requirement`
function in the specified context.
"""
if isinstance(expr, string_types):
if expr[0] in '\'"':
result = expr[1:-1]
else:
... | [
"def",
"evaluate",
"(",
"self",
",",
"expr",
",",
"context",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"string_types",
")",
":",
"if",
"expr",
"[",
"0",
"]",
"in",
"'\\'\"'",
":",
"result",
"=",
"expr",
"[",
"1",
":",
"-",
"1",
"]",
"else",... | [
49,
4
] | [
74,
21
] | python | en | ['en', 'error', 'th'] | False |
api_dev_fetch_api_key | (request: HttpRequest, username: str = REQ()) | This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
| This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
| def api_dev_fetch_api_key(request: HttpRequest, username: str = REQ()) -> HttpResponse:
"""This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
"""
... | [
"def",
"api_dev_fetch_api_key",
"(",
"request",
":",
"HttpRequest",
",",
"username",
":",
"str",
"=",
"REQ",
"(",
")",
")",
"->",
"HttpResponse",
":",
"check_dev_auth_backend",
"(",
")",
"# Django invokes authenticate methods by matching arguments, and this",
"# authentic... | [
91,
0
] | [
124,
83
] | python | en | ['en', 'en', 'en'] | True |
TemplateCommand.handle_template | (self, template, subdir) |
Determines where the app or project templates are.
Use django.__path__[0] as the default because we don't
know into which directory Django has been installed.
|
Determines where the app or project templates are.
Use django.__path__[0] as the default because we don't
know into which directory Django has been installed.
| def handle_template(self, template, subdir):
"""
Determines where the app or project templates are.
Use django.__path__[0] as the default because we don't
know into which directory Django has been installed.
"""
if template is None:
return path.join(django.__p... | [
"def",
"handle_template",
"(",
"self",
",",
"template",
",",
"subdir",
")",
":",
"if",
"template",
"is",
"None",
":",
"return",
"path",
".",
"join",
"(",
"django",
".",
"__path__",
"[",
"0",
"]",
",",
"'conf'",
",",
"subdir",
")",
"else",
":",
"if",
... | [
191,
4
] | [
215,
59
] | python | en | ['en', 'error', 'th'] | False |
TemplateCommand.download | (self, url) |
Downloads the given URL and returns the file name.
|
Downloads the given URL and returns the file name.
| def download(self, url):
"""
Downloads the given URL and returns the file name.
"""
def cleanup_url(url):
tmp = url.rstrip('/')
filename = tmp.split('/')[-1]
if url.endswith('/'):
display_url = tmp + '/'
else:
... | [
"def",
"download",
"(",
"self",
",",
"url",
")",
":",
"def",
"cleanup_url",
"(",
"url",
")",
":",
"tmp",
"=",
"url",
".",
"rstrip",
"(",
"'/'",
")",
"filename",
"=",
"tmp",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"if",
"url",
".",
... | [
238,
4
] | [
290,
23
] | python | en | ['en', 'error', 'th'] | False |
TemplateCommand.splitext | (self, the_path) |
Like os.path.splitext, but takes off .tar, too
|
Like os.path.splitext, but takes off .tar, too
| def splitext(self, the_path):
"""
Like os.path.splitext, but takes off .tar, too
"""
base, ext = posixpath.splitext(the_path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | [
"def",
"splitext",
"(",
"self",
",",
"the_path",
")",
":",
"base",
",",
"ext",
"=",
"posixpath",
".",
"splitext",
"(",
"the_path",
")",
"if",
"base",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"'.tar'",
")",
":",
"ext",
"=",
"base",
"[",
"-",
... | [
292,
4
] | [
300,
24
] | python | en | ['en', 'error', 'th'] | False |
TemplateCommand.extract | (self, filename) |
Extracts the given file to a temporarily and returns
the path of the directory with the extracted content.
|
Extracts the given file to a temporarily and returns
the path of the directory with the extracted content.
| def extract(self, filename):
"""
Extracts the given file to a temporarily and returns
the path of the directory with the extracted content.
"""
prefix = 'django_%s_template_' % self.app_or_project
tempdir = tempfile.mkdtemp(prefix=prefix, suffix='_extract')
self.p... | [
"def",
"extract",
"(",
"self",
",",
"filename",
")",
":",
"prefix",
"=",
"'django_%s_template_'",
"%",
"self",
".",
"app_or_project",
"tempdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
"prefix",
"=",
"prefix",
",",
"suffix",
"=",
"'_extract'",
")",
"self",
"... | [
302,
4
] | [
317,
54
] | python | en | ['en', 'error', 'th'] | False |
TemplateCommand.is_url | (self, template) |
Returns True if the name looks like a URL
|
Returns True if the name looks like a URL
| def is_url(self, template):
"""
Returns True if the name looks like a URL
"""
if ':' not in template:
return False
scheme = template.split(':', 1)[0].lower()
return scheme in self.url_schemes | [
"def",
"is_url",
"(",
"self",
",",
"template",
")",
":",
"if",
"':'",
"not",
"in",
"template",
":",
"return",
"False",
"scheme",
"=",
"template",
".",
"split",
"(",
"':'",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"return",
"scheme",
... | [
319,
4
] | [
326,
41
] | python | en | ['en', 'error', 'th'] | False |
TemplateCommand.make_writeable | (self, filename) |
Make sure that the file is writeable.
Useful if our source is read-only.
|
Make sure that the file is writeable.
Useful if our source is read-only.
| def make_writeable(self, filename):
"""
Make sure that the file is writeable.
Useful if our source is read-only.
"""
if sys.platform.startswith('java'):
# On Jython there is no os.access()
return
if not os.access(filename, os.W_OK):
st ... | [
"def",
"make_writeable",
"(",
"self",
",",
"filename",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'java'",
")",
":",
"# On Jython there is no os.access()",
"return",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".",
"... | [
328,
4
] | [
339,
47
] | python | en | ['en', 'error', 'th'] | False |
create_single_football_env | (iprocess) | Creates gfootball environment. | Creates gfootball environment. | def create_single_football_env(iprocess):
"""Creates gfootball environment."""
env = football_env.create_environment(
env_name=FLAGS.level, stacked=('stacked' in FLAGS.state),
rewards=FLAGS.reward_experiment,
logdir=logger.get_dir(),
write_goal_dumps=FLAGS.dump_scores and (iprocess == 0),
... | [
"def",
"create_single_football_env",
"(",
"iprocess",
")",
":",
"env",
"=",
"football_env",
".",
"create_environment",
"(",
"env_name",
"=",
"FLAGS",
".",
"level",
",",
"stacked",
"=",
"(",
"'stacked'",
"in",
"FLAGS",
".",
"state",
")",
",",
"rewards",
"=",
... | [
69,
0
] | [
81,
12
] | python | en | ['en', 'gl', 'en'] | True |
train | (_) | Trains a PPO2 policy. | Trains a PPO2 policy. | def train(_):
"""Trains a PPO2 policy."""
vec_env = SubprocVecEnv([
(lambda _i=i: create_single_football_env(_i))
for i in range(FLAGS.num_envs)
], context=None)
# Import tensorflow after we create environments. TF is not fork sake, and
# we could be using TF as part of environment if one of the ... | [
"def",
"train",
"(",
"_",
")",
":",
"vec_env",
"=",
"SubprocVecEnv",
"(",
"[",
"(",
"lambda",
"_i",
"=",
"i",
":",
"create_single_football_env",
"(",
"_i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"FLAGS",
".",
"num_envs",
")",
"]",
",",
"context",
... | [
84,
0
] | [
116,
39
] | python | en | ['en', 'en', 'en'] | True |
LofarCasaImage.open_subtables | (self, table) | open all subtables defined in the LOFAR format
args:
table: a casacore table handler to a LOFAR CASA table
returns:
a dict containing all LOFAR CASA subtables
| open all subtables defined in the LOFAR format
args:
table: a casacore table handler to a LOFAR CASA table
returns:
a dict containing all LOFAR CASA subtables
| def open_subtables(self, table):
"""open all subtables defined in the LOFAR format
args:
table: a casacore table handler to a LOFAR CASA table
returns:
a dict containing all LOFAR CASA subtables
"""
subtables = {}
for subtable in subtable_names:
... | [
"def",
"open_subtables",
"(",
"self",
",",
"table",
")",
":",
"subtables",
"=",
"{",
"}",
"for",
"subtable",
"in",
"subtable_names",
":",
"subtable_location",
"=",
"table",
".",
"getkeyword",
"(",
"\"ATTRGROUPS\"",
")",
"[",
"subtable",
"]",
"subtables",
"["... | [
55,
4
] | [
66,
24
] | python | en | ['en', 'en', 'en'] | True |
LofarCasaImage.parse_taustartts | (self, subtables) | extract image start time from CASA table header
| extract image start time from CASA table header
| def parse_taustartts(self, subtables):
""" extract image start time from CASA table header
"""
# Note that we sort the table in order of ascending start time then
# choose the first value to ensure we get the earliest possible
# starting time.
observation_table = subtable... | [
"def",
"parse_taustartts",
"(",
"self",
",",
"subtables",
")",
":",
"# Note that we sort the table in order of ascending start time then",
"# choose the first value to ensure we get the earliest possible",
"# starting time.",
"observation_table",
"=",
"subtables",
"[",
"'LOFAR_OBSERVAT... | [
68,
4
] | [
81,
26
] | python | en | ['en', 'en', 'en'] | True |
LofarCasaImage.non_overlapping_time | (series) |
Returns the sum of total ranges without overlap.
series: a list of 2 item tuples representing ranges.
|
Returns the sum of total ranges without overlap. | def non_overlapping_time(series):
"""
Returns the sum of total ranges without overlap.
series: a list of 2 item tuples representing ranges.
"""
series.sort()
overlap = total = 0
for n, (start, end) in enumerate(series):
total += end - start
... | [
"def",
"non_overlapping_time",
"(",
"series",
")",
":",
"series",
".",
"sort",
"(",
")",
"overlap",
"=",
"total",
"=",
"0",
"for",
"n",
",",
"(",
"start",
",",
"end",
")",
"in",
"enumerate",
"(",
"series",
")",
":",
"total",
"+=",
"end",
"-",
"star... | [
84,
4
] | [
101,
30
] | python | en | ['en', 'error', 'th'] | False |
LofarCasaImage.parse_tautime | (self, subtables) |
Returns the total on-sky time for this image.
|
Returns the total on-sky time for this image.
| def parse_tautime(self, subtables):
"""
Returns the total on-sky time for this image.
"""
origin_table = subtables['LOFAR_ORIGIN']
startcol = origin_table.col('START')
endcol = origin_table.col('END')
series = [(int(start), int(end)) for start, end in zip(startcol... | [
"def",
"parse_tautime",
"(",
"self",
",",
"subtables",
")",
":",
"origin_table",
"=",
"subtables",
"[",
"'LOFAR_ORIGIN'",
"]",
"startcol",
"=",
"origin_table",
".",
"col",
"(",
"'START'",
")",
"endcol",
"=",
"origin_table",
".",
"col",
"(",
"'END'",
")",
"... | [
103,
4
] | [
112,
23
] | python | en | ['en', 'error', 'th'] | False |
LofarCasaImage.parse_stations | (self, subtables) | Extract number of specific LOFAR stations used
returns:
(number of core stations, remote stations, international stations)
| Extract number of specific LOFAR stations used
returns:
(number of core stations, remote stations, international stations)
| def parse_stations(self, subtables):
"""Extract number of specific LOFAR stations used
returns:
(number of core stations, remote stations, international stations)
"""
observation_table = subtables['LOFAR_OBSERVATION']
antenna_table = subtables['LOFAR_ANTENNA']
... | [
"def",
"parse_stations",
"(",
"self",
",",
"subtables",
")",
":",
"observation_table",
"=",
"subtables",
"[",
"'LOFAR_OBSERVATION'",
"]",
"antenna_table",
"=",
"subtables",
"[",
"'LOFAR_ANTENNA'",
"]",
"nvis_used",
"=",
"observation_table",
".",
"getcol",
"(",
"'N... | [
153,
4
] | [
173,
36
] | python | en | ['en', 'en', 'en'] | True |
f | (x) | Noise free objective. | Noise free objective. | def f(x):
"""Noise free objective."""
return np.sin(10 * x) * x * 100 | [
"def",
"f",
"(",
"x",
")",
":",
"return",
"np",
".",
"sin",
"(",
"10",
"*",
"x",
")",
"*",
"x",
"*",
"100"
] | [
23,
0
] | [
26,
35
] | python | en | ['en', 'en', 'en'] | True |
LocalMonitor._calc_resource_stats | (self, interval) |
Get local resource stats
:return: dict
|
Get local resource stats | def _calc_resource_stats(self, interval):
"""
Get local resource stats
:return: dict
"""
result = {}
if 'mem' in self.metrics:
result['mem'] = self.__get_mem_info()
if 'disk-space' in self.metrics:
result['disk-space'] = self.__get_disk_... | [
"def",
"_calc_resource_stats",
"(",
"self",
",",
"interval",
")",
":",
"result",
"=",
"{",
"}",
"if",
"'mem'",
"in",
"self",
".",
"metrics",
":",
"result",
"[",
"'mem'",
"]",
"=",
"self",
".",
"__get_mem_info",
"(",
")",
"if",
"'disk-space'",
"in",
"se... | [
243,
4
] | [
304,
21
] | python | en | ['en', 'error', 'th'] | False |
ServerAgentClient.__init__ | (self, parent_log, label, config, engine) |
:type parent_log: logging.Logger
:type config: dict
|
:type parent_log: logging.Logger
:type config: dict
| def __init__(self, parent_log, label, config, engine):
"""
:type parent_log: logging.Logger
:type config: dict
"""
super(ServerAgentClient, self).__init__(parent_log, engine)
self.host_label = label
exc = TaurusConfigError('ServerAgent client requires address para... | [
"def",
"__init__",
"(",
"self",
",",
"parent_log",
",",
"label",
",",
"config",
",",
"engine",
")",
":",
"super",
"(",
"ServerAgentClient",
",",
"self",
")",
".",
"__init__",
"(",
"parent_log",
",",
"engine",
")",
"self",
".",
"host_label",
"=",
"label",... | [
446,
4
] | [
475,
74
] | python | en | ['en', 'error', 'th'] | False |
ServerAgentClient.get_data | (self) |
:rtype: list[dict]
|
:rtype: list[dict]
| def get_data(self):
"""
:rtype: list[dict]
"""
now = time.time()
readable, writable, errored = self.select([self.socket], [self.socket], [self.socket], 0)
self.log.debug("Stream states: %s / %s / %s", readable, writable, errored)
for _ in errored:
self... | [
"def",
"get_data",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"readable",
",",
"writable",
",",
"errored",
"=",
"self",
".",
"select",
"(",
"[",
"self",
".",
"socket",
"]",
",",
"[",
"self",
".",
"socket",
"]",
",",
"[",
... | [
512,
4
] | [
543,
18
] | python | en | ['en', 'error', 'th'] | False |
MonitoringCriteria.__init__ | (self, config, owner) |
:type config: bzt.utils.BetterDict
:type owner: bzt.engine.EngineModule
|
:type config: bzt.utils.BetterDict
:type owner: bzt.engine.EngineModule
| def __init__(self, config, owner):
"""
:type config: bzt.utils.BetterDict
:type owner: bzt.engine.EngineModule
"""
super(MonitoringCriteria, self).__init__(config, owner)
for service in self.owner.engine.services:
if isinstance(service, Monitoring):
... | [
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"owner",
")",
":",
"super",
"(",
"MonitoringCriteria",
",",
"self",
")",
".",
"__init__",
"(",
"config",
",",
"owner",
")",
"for",
"service",
"in",
"self",
".",
"owner",
".",
"engine",
".",
"services"... | [
593,
4
] | [
601,
42
] | python | en | ['en', 'error', 'th'] | False |
ObjFile.__init__ | (self, filename, swapyz=False) | Loads a Wavefront OBJ file. | Loads a Wavefront OBJ file. | def __init__(self, filename, swapyz=False):
"""Loads a Wavefront OBJ file. """
self.objects = {}
self.vertices = []
self.normals = []
self.texcoords = []
self.faces = []
self._current_object = None
material = None
for line in open(filename, "r"):... | [
"def",
"__init__",
"(",
"self",
",",
"filename",
",",
"swapyz",
"=",
"False",
")",
":",
"self",
".",
"objects",
"=",
"{",
"}",
"self",
".",
"vertices",
"=",
"[",
"]",
"self",
".",
"normals",
"=",
"[",
"]",
"self",
".",
"texcoords",
"=",
"[",
"]",... | [
74,
4
] | [
128,
28
] | python | en | ['en', 'da', 'en'] | True |
_basic_auth_str | (username, password) | Returns a Basic Auth string. | Returns a Basic Auth string. | def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
# "I want us to put a big-ol' comment on top of it that
# says that this behaviour is dumb but we need to preserve
# it because people are relying on it."
# - Lukasa
#
# These are here solely to maintain backward... | [
"def",
"_basic_auth_str",
"(",
"username",
",",
"password",
")",
":",
"# \"I want us to put a big-ol' comment on top of it that",
"# says that this behaviour is dumb but we need to preserve",
"# it because people are relying on it.\"",
"# - Lukasa",
"#",
"# These are here solely to main... | [
27,
0
] | [
68,
18
] | python | en | ['en', 'en', 'en'] | True |
HTTPDigestAuth.build_digest_header | (self, method, url) |
:rtype: str
|
:rtype: str
| def build_digest_header(self, method, url):
"""
:rtype: str
"""
realm = self._thread_local.chal['realm']
nonce = self._thread_local.chal['nonce']
qop = self._thread_local.chal.get('qop')
algorithm = self._thread_local.chal.get('algorithm')
opaque = self._... | [
"def",
"build_digest_header",
"(",
"self",
",",
"method",
",",
"url",
")",
":",
"realm",
"=",
"self",
".",
"_thread_local",
".",
"chal",
"[",
"'realm'",
"]",
"nonce",
"=",
"self",
".",
"_thread_local",
".",
"chal",
"[",
"'nonce'",
"]",
"qop",
"=",
"sel... | [
126,
4
] | [
226,
35
] | python | en | ['en', 'error', 'th'] | False |
HTTPDigestAuth.handle_redirect | (self, r, **kwargs) | Reset num_401_calls counter on redirects. | Reset num_401_calls counter on redirects. | def handle_redirect(self, r, **kwargs):
"""Reset num_401_calls counter on redirects."""
if r.is_redirect:
self._thread_local.num_401_calls = 1 | [
"def",
"handle_redirect",
"(",
"self",
",",
"r",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"r",
".",
"is_redirect",
":",
"self",
".",
"_thread_local",
".",
"num_401_calls",
"=",
"1"
] | [
228,
4
] | [
231,
48
] | python | en | ['en', 'en', 'en'] | True |
HTTPDigestAuth.handle_401 | (self, r, **kwargs) |
Takes the given response and tries digest-auth, if needed.
:rtype: requests.Response
|
Takes the given response and tries digest-auth, if needed. | def handle_401(self, r, **kwargs):
"""
Takes the given response and tries digest-auth, if needed.
:rtype: requests.Response
"""
# If response is not 4xx, do not auth
# See https://github.com/psf/requests/issues/3772
if not 400 <= r.status_code < 500:
... | [
"def",
"handle_401",
"(",
"self",
",",
"r",
",",
"*",
"*",
"kwargs",
")",
":",
"# If response is not 4xx, do not auth",
"# See https://github.com/psf/requests/issues/3772",
"if",
"not",
"400",
"<=",
"r",
".",
"status_code",
"<",
"500",
":",
"self",
".",
"_thread_l... | [
233,
4
] | [
275,
16
] | python | en | ['en', 'error', 'th'] | False |
routablepageurl | (context, page, url_name, *args, **kwargs) |
``routablepageurl`` is similar to ``pageurl``, but works with
pages using ``RoutablePageMixin``. It behaves like a hybrid between the built-in
``reverse``, and ``pageurl`` from Wagtail.
``page`` is the RoutablePage that URLs will be generated from.
``url_name`` is a URL name defined in ``page.sub... |
``routablepageurl`` is similar to ``pageurl``, but works with
pages using ``RoutablePageMixin``. It behaves like a hybrid between the built-in
``reverse``, and ``pageurl`` from Wagtail. | def routablepageurl(context, page, url_name, *args, **kwargs):
"""
``routablepageurl`` is similar to ``pageurl``, but works with
pages using ``RoutablePageMixin``. It behaves like a hybrid between the built-in
``reverse``, and ``pageurl`` from Wagtail.
``page`` is the RoutablePage that URLs will be... | [
"def",
"routablepageurl",
"(",
"context",
",",
"page",
",",
"url_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"context",
"[",
"'request'",
"]",
"site",
"=",
"Site",
".",
"find_for_request",
"(",
"request",
")",
"base_url",
... | [
9,
0
] | [
28,
32
] | python | en | ['en', 'error', 'th'] | False |
TestScenarioBuilder.test_old_jmeter | (self) | versions before 3.0 must use JSON plugin for extracting purposes | versions before 3.0 must use JSON plugin for extracting purposes | def test_old_jmeter(self):
""" versions before 3.0 must use JSON plugin for extracting purposes """
self.configure(scenario={"requests": [{
"url": "http://blazedemo.com",
"extract-jsonpath": {
"IP": "$.net[0].ip",
"URL": {
"json... | [
"def",
"test_old_jmeter",
"(",
"self",
")",
":",
"self",
".",
"configure",
"(",
"scenario",
"=",
"{",
"\"requests\"",
":",
"[",
"{",
"\"url\"",
":",
"\"http://blazedemo.com\"",
",",
"\"extract-jsonpath\"",
":",
"{",
"\"IP\"",
":",
"\"$.net[0].ip\"",
",",
"\"UR... | [
107,
4
] | [
125,
37
] | python | en | ['en', 'en', 'en'] | True |
TestScenarioBuilder.test_new_extractor | (self) | versions after 3.0 use integrated JSON extractor | versions after 3.0 use integrated JSON extractor | def test_new_extractor(self):
""" versions after 3.0 use integrated JSON extractor """
self.configure(scenario={"requests": [{
"url": "http://blazedemo.com",
"extract-jsonpath": {
"IP": "$.net[0].ip",
"URL": {"jsonpath": "$.url[1]", "default": "d1"... | [
"def",
"test_new_extractor",
"(",
"self",
")",
":",
"self",
".",
"configure",
"(",
"scenario",
"=",
"{",
"\"requests\"",
":",
"[",
"{",
"\"url\"",
":",
"\"http://blazedemo.com\"",
",",
"\"extract-jsonpath\"",
":",
"{",
"\"IP\"",
":",
"\"$.net[0].ip\"",
",",
"\... | [
127,
4
] | [
151,
37
] | python | en | ['en', 'en', 'en'] | True |
signal_handler | (sig, frame) |
required for non-tty python runs to interrupt
:param frame:
:param sig:
|
required for non-tty python runs to interrupt
:param frame:
:param sig:
| def signal_handler(sig, frame):
"""
required for non-tty python runs to interrupt
:param frame:
:param sig:
"""
del sig, frame
raise ManualShutdown() | [
"def",
"signal_handler",
"(",
"sig",
",",
"frame",
")",
":",
"del",
"sig",
",",
"frame",
"raise",
"ManualShutdown",
"(",
")"
] | [
654,
0
] | [
661,
26
] | python | en | ['en', 'error', 'th'] | False |
main | () |
This function is used as entrypoint by setuptools
|
This function is used as entrypoint by setuptools
| def main():
"""
This function is used as entrypoint by setuptools
"""
parser = get_option_parser()
parsed_options, parsed_configs = parser.parse_args()
executor = CLI(parsed_options)
try:
code = executor.perform(parsed_configs)
except BaseException as exc_top:
logging.... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"get_option_parser",
"(",
")",
"parsed_options",
",",
"parsed_configs",
"=",
"parser",
".",
"parse_args",
"(",
")",
"executor",
"=",
"CLI",
"(",
"parsed_options",
")",
"try",
":",
"code",
"=",
"executor",
".",
... | [
664,
0
] | [
681,
18
] | python | en | ['en', 'error', 'th'] | False |
CLI.setup_logging | (options) |
Setting up console and file logging, colored if possible
:param options: OptionParser parsed options
|
Setting up console and file logging, colored if possible | def setup_logging(options):
"""
Setting up console and file logging, colored if possible
:param options: OptionParser parsed options
"""
colors = {
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
fmt_file = Forma... | [
"def",
"setup_logging",
"(",
"options",
")",
":",
"colors",
"=",
"{",
"'WARNING'",
":",
"'yellow'",
",",
"'ERROR'",
":",
"'red'",
",",
"'CRITICAL'",
":",
"'bold_red'",
",",
"}",
"fmt_file",
"=",
"Formatter",
"(",
"\"[%(asctime)s %(levelname)s %(name)s] %(message)s... | [
78,
4
] | [
128,
63
] | python | en | ['en', 'error', 'th'] | False |
CLI.close_log | (self) |
Close log handlers
:return:
|
Close log handlers
:return:
| def close_log(self):
"""
Close log handlers
:return:
"""
if self.options.log:
# need to finalize the logger before finishing
for handler in self.log.handlers[:]:
if issubclass(handler.__class__, logging.FileHandler):
sel... | [
"def",
"close_log",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
".",
"log",
":",
"# need to finalize the logger before finishing",
"for",
"handler",
"in",
"self",
".",
"log",
".",
"handlers",
"[",
":",
"]",
":",
"if",
"issubclass",
"(",
"handler",
... | [
130,
4
] | [
141,
53
] | python | en | ['en', 'error', 'th'] | False |
CLI.__move_log_to_artifacts | (self) |
Close log handlers, copy log to artifacts dir, recreate file handlers
:return:
|
Close log handlers, copy log to artifacts dir, recreate file handlers
:return:
| def __move_log_to_artifacts(self):
"""
Close log handlers, copy log to artifacts dir, recreate file handlers
:return:
"""
if self.options.log:
for handler in self.log.handlers[:]:
if issubclass(handler.__class__, logging.FileHandler):
... | [
"def",
"__move_log_to_artifacts",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
".",
"log",
":",
"for",
"handler",
"in",
"self",
".",
"log",
".",
"handlers",
"[",
":",
"]",
":",
"if",
"issubclass",
"(",
"handler",
".",
"__class__",
",",
"logging... | [
143,
4
] | [
164,
75
] | python | en | ['en', 'error', 'th'] | False |
CLI.perform | (self, configs) |
Run the tool
:type configs: list
:return: integer exit code
|
Run the tool | def perform(self, configs):
"""
Run the tool
:type configs: list
:return: integer exit code
"""
url_shorthands = []
jmx_shorthands = []
jtl_shorthands = []
try:
url_shorthands = self.__get_url_shorthands(configs)
configs.ex... | [
"def",
"perform",
"(",
"self",
",",
"configs",
")",
":",
"url_shorthands",
"=",
"[",
"]",
"jmx_shorthands",
"=",
"[",
"]",
"jtl_shorthands",
"=",
"[",
"]",
"try",
":",
"url_shorthands",
"=",
"self",
".",
"__get_url_shorthands",
"(",
"configs",
")",
"config... | [
243,
4
] | [
302,
29
] | python | en | ['en', 'error', 'th'] | False |
CLI.__get_jmx_shorthands | (self, configs) |
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
|
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
| def __get_jmx_shorthands(self, configs):
"""
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
"""
jmxes = []
for filename in configs[:]:
if filename.lower().endswith(".jmx"):
jmxes.appe... | [
"def",
"__get_jmx_shorthands",
"(",
"self",
",",
"configs",
")",
":",
"jmxes",
"=",
"[",
"]",
"for",
"filename",
"in",
"configs",
"[",
":",
"]",
":",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".jmx\"",
")",
":",
"jmxes",
".",
... | [
356,
4
] | [
384,
21
] | python | en | ['en', 'error', 'th'] | False |
CLI.__get_jtl_shorthands | (self, configs) |
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
|
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
| def __get_jtl_shorthands(self, configs):
"""
Generate json file with execution, executor and scenario settings
:type configs: list
:return: list
"""
jtls = []
for filename in configs[:]:
if filename.lower().endswith(".jtl"):
jtls.append... | [
"def",
"__get_jtl_shorthands",
"(",
"self",
",",
"configs",
")",
":",
"jtls",
"=",
"[",
"]",
"for",
"filename",
"in",
"configs",
"[",
":",
"]",
":",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"\".jtl\"",
")",
":",
"jtls",
".",
... | [
386,
4
] | [
414,
21
] | python | en | ['en', 'error', 'th'] | False |
CLI.__get_url_shorthands | (self, configs) |
:type configs: list
:return: list
|
:type configs: list
:return: list
| def __get_url_shorthands(self, configs):
"""
:type configs: list
:return: list
"""
urls = []
for candidate in configs[:]:
if is_url(candidate):
urls.append(candidate)
configs.remove(candidate)
if urls:
self.... | [
"def",
"__get_url_shorthands",
"(",
"self",
",",
"configs",
")",
":",
"urls",
"=",
"[",
"]",
"for",
"candidate",
"in",
"configs",
"[",
":",
"]",
":",
"if",
"is_url",
"(",
"candidate",
")",
":",
"urls",
".",
"append",
"(",
"candidate",
")",
"configs",
... | [
416,
4
] | [
480,
21
] | python | en | ['en', 'error', 'th'] | False |
ConfigOverrider.__init__ | (self, logger) |
:type logger: logging.Logger
|
:type logger: logging.Logger
| def __init__(self, logger):
"""
:type logger: logging.Logger
"""
super(ConfigOverrider, self).__init__()
self.log = logger.getChild(self.__class__.__name__) | [
"def",
"__init__",
"(",
"self",
",",
"logger",
")",
":",
"super",
"(",
"ConfigOverrider",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"log",
"=",
"logger",
".",
"getChild",
"(",
"self",
".",
"__class__",
".",
"__name__",
")"
] | [
484,
4
] | [
489,
59
] | python | en | ['en', 'error', 'th'] | False |
ConfigOverrider.apply_overrides | (self, options, dest) |
Apply overrides
:type options: list[str]
:type dest: Configuration
|
Apply overrides
:type options: list[str]
:type dest: Configuration
| def apply_overrides(self, options, dest):
"""
Apply overrides
:type options: list[str]
:type dest: Configuration
"""
for option in options:
name = option[:option.index('=')]
value = option[option.index('=') + 1:]
try:
se... | [
"def",
"apply_overrides",
"(",
"self",
",",
"options",
",",
"dest",
")",
":",
"for",
"option",
"in",
"options",
":",
"name",
"=",
"option",
"[",
":",
"option",
".",
"index",
"(",
"'='",
")",
"]",
"value",
"=",
"option",
"[",
"option",
".",
"index",
... | [
491,
4
] | [
507,
19
] | 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.