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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
module_dir | (module) |
Find the name of the directory that contains a module, if possible.
Raise ValueError otherwise, e.g. for namespace packages that are split
over several directories.
|
Find the name of the directory that contains a module, if possible. | def module_dir(module):
"""
Find the name of the directory that contains a module, if possible.
Raise ValueError otherwise, e.g. for namespace packages that are split
over several directories.
"""
# Convert to list because _NamespacePath does not support indexing.
paths = list(getattr(modul... | [
"def",
"module_dir",
"(",
"module",
")",
":",
"# Convert to list because _NamespacePath does not support indexing.",
"paths",
"=",
"list",
"(",
"getattr",
"(",
"module",
",",
"'__path__'",
",",
"[",
"]",
")",
")",
"if",
"len",
"(",
"paths",
")",
"==",
"1",
":"... | [
81,
0
] | [
96,
73
] | python | en | ['en', 'error', 'th'] | False |
inject_rename_contenttypes_operations | (plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs) |
Insert a `RenameContentType` operation after every planned `RenameModel`
operation.
|
Insert a `RenameContentType` operation after every planned `RenameModel`
operation.
| def inject_rename_contenttypes_operations(plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs):
"""
Insert a `RenameContentType` operation after every planned `RenameModel`
operation.
"""
if plan is None:
return
# Determine whether or not the ContentType model is available.
... | [
"def",
"inject_rename_contenttypes_operations",
"(",
"plan",
"=",
"None",
",",
"apps",
"=",
"global_apps",
",",
"using",
"=",
"DEFAULT_DB_ALIAS",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"plan",
"is",
"None",
":",
"return",
"# Determine whether or not the ContentT... | [
44,
0
] | [
83,
68
] | python | en | ['en', 'error', 'th'] | False |
create_contenttypes | (app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs) |
Create content types for models in the given app.
|
Create content types for models in the given app.
| def create_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, apps=global_apps, **kwargs):
"""
Create content types for models in the given app.
"""
if not app_config.models_module:
return
app_label = app_config.label
try:
app_config = apps.get_app_c... | [
"def",
"create_contenttypes",
"(",
"app_config",
",",
"verbosity",
"=",
"2",
",",
"interactive",
"=",
"True",
",",
"using",
"=",
"DEFAULT_DB_ALIAS",
",",
"apps",
"=",
"global_apps",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"app_config",
".",
"models... | [
103,
0
] | [
133,
77
] | python | en | ['en', 'error', 'th'] | False |
Field.__init__ | (self, feat, index) |
Initialize on the feature object and the integer index of
the field within the feature.
|
Initialize on the feature object and the integer index of
the field within the feature.
| def __init__(self, feat, index):
"""
Initialize on the feature object and the integer index of
the field within the feature.
"""
# Setting the feature pointer and index.
self._feat = feat
self._index = index
# Getting the pointer for this field.
f... | [
"def",
"__init__",
"(",
"self",
",",
"feat",
",",
"index",
")",
":",
"# Setting the feature pointer and index.",
"self",
".",
"_feat",
"=",
"feat",
"self",
".",
"_index",
"=",
"index",
"# Getting the pointer for this field.",
"fld_ptr",
"=",
"capi",
".",
"get_feat... | [
18,
4
] | [
34,
49
] | python | en | ['en', 'error', 'th'] | False |
Field.__str__ | (self) | Return the string representation of the Field. | Return the string representation of the Field. | def __str__(self):
"Return the string representation of the Field."
return str(self.value).strip() | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"str",
"(",
"self",
".",
"value",
")",
".",
"strip",
"(",
")"
] | [
36,
4
] | [
38,
38
] | python | en | ['en', 'en', 'en'] | True |
Field.as_double | (self) | Retrieve the Field's value as a double (float). | Retrieve the Field's value as a double (float). | def as_double(self):
"Retrieve the Field's value as a double (float)."
return capi.get_field_as_double(self._feat.ptr, self._index) if self.is_set else None | [
"def",
"as_double",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_as_double",
"(",
"self",
".",
"_feat",
".",
"ptr",
",",
"self",
".",
"_index",
")",
"if",
"self",
".",
"is_set",
"else",
"None"
] | [
41,
4
] | [
43,
93
] | python | en | ['en', 'ga', 'en'] | True |
Field.as_int | (self, is_64=False) | Retrieve the Field's value as an integer. | Retrieve the Field's value as an integer. | def as_int(self, is_64=False):
"Retrieve the Field's value as an integer."
if is_64:
return capi.get_field_as_integer64(self._feat.ptr, self._index) if self.is_set else None
else:
return capi.get_field_as_integer(self._feat.ptr, self._index) if self.is_set else None | [
"def",
"as_int",
"(",
"self",
",",
"is_64",
"=",
"False",
")",
":",
"if",
"is_64",
":",
"return",
"capi",
".",
"get_field_as_integer64",
"(",
"self",
".",
"_feat",
".",
"ptr",
",",
"self",
".",
"_index",
")",
"if",
"self",
".",
"is_set",
"else",
"Non... | [
45,
4
] | [
50,
98
] | python | en | ['en', 'ga', 'en'] | True |
Field.as_string | (self) | Retrieve the Field's value as a string. | Retrieve the Field's value as a string. | def as_string(self):
"Retrieve the Field's value as a string."
if not self.is_set:
return None
string = capi.get_field_as_string(self._feat.ptr, self._index)
return force_str(string, encoding=self._feat.encoding, strings_only=True) | [
"def",
"as_string",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_set",
":",
"return",
"None",
"string",
"=",
"capi",
".",
"get_field_as_string",
"(",
"self",
".",
"_feat",
".",
"ptr",
",",
"self",
".",
"_index",
")",
"return",
"force_str",
"(",... | [
52,
4
] | [
57,
81
] | python | en | ['en', 'sk', 'en'] | True |
Field.as_datetime | (self) | Retrieve the Field's value as a tuple of date & time components. | Retrieve the Field's value as a tuple of date & time components. | def as_datetime(self):
"Retrieve the Field's value as a tuple of date & time components."
if not self.is_set:
return None
yy, mm, dd, hh, mn, ss, tz = [c_int() for i in range(7)]
status = capi.get_field_as_datetime(
self._feat.ptr, self._index, byref(yy), byref(mm... | [
"def",
"as_datetime",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_set",
":",
"return",
"None",
"yy",
",",
"mm",
",",
"dd",
",",
"hh",
",",
"mn",
",",
"ss",
",",
"tz",
"=",
"[",
"c_int",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"7",
... | [
59,
4
] | [
70,
93
] | python | en | ['en', 'en', 'en'] | True |
Field.is_set | (self) | Return True if the value of this field isn't null, False otherwise. | Return True if the value of this field isn't null, False otherwise. | def is_set(self):
"Return True if the value of this field isn't null, False otherwise."
return capi.is_field_set(self._feat.ptr, self._index) | [
"def",
"is_set",
"(",
"self",
")",
":",
"return",
"capi",
".",
"is_field_set",
"(",
"self",
".",
"_feat",
".",
"ptr",
",",
"self",
".",
"_index",
")"
] | [
74,
4
] | [
76,
61
] | python | en | ['en', 'en', 'en'] | True |
Field.name | (self) | Return the name of this Field. | Return the name of this Field. | def name(self):
"Return the name of this Field."
name = capi.get_field_name(self.ptr)
return force_str(name, encoding=self._feat.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_field_name",
"(",
"self",
".",
"ptr",
")",
"return",
"force_str",
"(",
"name",
",",
"encoding",
"=",
"self",
".",
"_feat",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
79,
4
] | [
82,
79
] | python | en | ['en', 'en', 'en'] | True |
Field.precision | (self) | Return the precision of this Field. | Return the precision of this Field. | def precision(self):
"Return the precision of this Field."
return capi.get_field_precision(self.ptr) | [
"def",
"precision",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_precision",
"(",
"self",
".",
"ptr",
")"
] | [
85,
4
] | [
87,
49
] | python | en | ['en', 'en', 'en'] | True |
Field.type | (self) | Return the OGR type of this Field. | Return the OGR type of this Field. | def type(self):
"Return the OGR type of this Field."
return capi.get_field_type(self.ptr) | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_type",
"(",
"self",
".",
"ptr",
")"
] | [
90,
4
] | [
92,
44
] | python | en | ['en', 'en', 'en'] | True |
Field.type_name | (self) | Return the OGR field type name for this Field. | Return the OGR field type name for this Field. | def type_name(self):
"Return the OGR field type name for this Field."
return capi.get_field_type_name(self.type) | [
"def",
"type_name",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_type_name",
"(",
"self",
".",
"type",
")"
] | [
95,
4
] | [
97,
50
] | python | en | ['en', 'en', 'en'] | True |
Field.value | (self) | Return the value of this Field. | Return the value of this Field. | def value(self):
"Return the value of this Field."
# Default is to get the field as a string.
return self.as_string() | [
"def",
"value",
"(",
"self",
")",
":",
"# Default is to get the field as a string.",
"return",
"self",
".",
"as_string",
"(",
")"
] | [
100,
4
] | [
103,
31
] | python | en | ['en', 'en', 'en'] | True |
Field.width | (self) | Return the width of this Field. | Return the width of this Field. | def width(self):
"Return the width of this Field."
return capi.get_field_width(self.ptr) | [
"def",
"width",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_width",
"(",
"self",
".",
"ptr",
")"
] | [
106,
4
] | [
108,
45
] | python | en | ['en', 'en', 'en'] | True |
OFTInteger.value | (self) | Return an integer contained in this field. | Return an integer contained in this field. | def value(self):
"Return an integer contained in this field."
return self.as_int(self._bit64) | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"as_int",
"(",
"self",
".",
"_bit64",
")"
] | [
116,
4
] | [
118,
39
] | python | en | ['en', 'en', 'en'] | True |
OFTInteger.type | (self) |
GDAL uses OFTReals to represent OFTIntegers in created
shapefiles -- forcing the type here since the underlying field
type may actually be OFTReal.
|
GDAL uses OFTReals to represent OFTIntegers in created
shapefiles -- forcing the type here since the underlying field
type may actually be OFTReal.
| def type(self):
"""
GDAL uses OFTReals to represent OFTIntegers in created
shapefiles -- forcing the type here since the underlying field
type may actually be OFTReal.
"""
return 0 | [
"def",
"type",
"(",
"self",
")",
":",
"return",
"0"
] | [
121,
4
] | [
127,
16
] | python | en | ['en', 'error', 'th'] | False |
OFTReal.value | (self) | Return a float contained in this field. | Return a float contained in this field. | def value(self):
"Return a float contained in this field."
return self.as_double() | [
"def",
"value",
"(",
"self",
")",
":",
"return",
"self",
".",
"as_double",
"(",
")"
] | [
132,
4
] | [
134,
31
] | python | en | ['en', 'en', 'en'] | True |
OFTDate.value | (self) | Return a Python `date` object for the OFTDate field. | Return a Python `date` object for the OFTDate field. | def value(self):
"Return a Python `date` object for the OFTDate field."
try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return date(yy.value, mm.value, dd.value)
except (TypeError, ValueError, GDALException):
return None | [
"def",
"value",
"(",
"self",
")",
":",
"try",
":",
"yy",
",",
"mm",
",",
"dd",
",",
"hh",
",",
"mn",
",",
"ss",
",",
"tz",
"=",
"self",
".",
"as_datetime",
"(",
")",
"return",
"date",
"(",
"yy",
".",
"value",
",",
"mm",
".",
"value",
",",
"... | [
153,
4
] | [
159,
23
] | python | en | ['en', 'en', 'en'] | True |
OFTDateTime.value | (self) | Return a Python `datetime` object for this OFTDateTime field. | Return a Python `datetime` object for this OFTDateTime field. | def value(self):
"Return a Python `datetime` object for this OFTDateTime field."
# TODO: Adapt timezone information.
# See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html
# The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous),
# 100=GMT, 104... | [
"def",
"value",
"(",
"self",
")",
":",
"# TODO: Adapt timezone information.",
"# See https://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html",
"# The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous),",
"# 100=GMT, 104=GMT+1, 80=GMT-5, etc.",
"try",
":",
"yy",
... | [
164,
4
] | [
174,
23
] | python | en | ['en', 'en', 'en'] | True |
OFTTime.value | (self) | Return a Python `time` object for this OFTTime field. | Return a Python `time` object for this OFTTime field. | def value(self):
"Return a Python `time` object for this OFTTime field."
try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return time(hh.value, mn.value, ss.value)
except (ValueError, GDALException):
return None | [
"def",
"value",
"(",
"self",
")",
":",
"try",
":",
"yy",
",",
"mm",
",",
"dd",
",",
"hh",
",",
"mn",
",",
"ss",
",",
"tz",
"=",
"self",
".",
"as_datetime",
"(",
")",
"return",
"time",
"(",
"hh",
".",
"value",
",",
"mn",
".",
"value",
",",
"... | [
179,
4
] | [
185,
23
] | python | en | ['en', 'en', 'en'] | True |
CarliniWagnerL2.__init__ | (self, model, sess, dtypestr="float32", **kwargs) |
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
|
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
| def __init__(self, model, sess, dtypestr="float32", **kwargs):
"""
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
wrapper_warning_logits()
model = Calla... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"wrapper_warning_logits",
"(",
")",
"model",
"=",
"Calla... | [
38,
4
] | [
62,
9
] | python | en | ['en', 'error', 'th'] | False |
CarliniWagnerL2.generate | (self, x, **kwargs) |
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params`
|
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors. | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert (
... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"(",
"self",
".",
"sess",
"is",
"not",
"None",
")",
",",
"\"Cannot use `generate` when no `sess` was provided\"",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
"... | [
64,
4
] | [
102,
19
] | python | en | ['en', 'error', 'th'] | False |
CarliniWagnerL2.parse_params | (
self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
initial_const=1e-2,
clip_min=0,
clip_max=1,
) |
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
... |
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
... | def parse_params(
self,
y=None,
y_target=None,
batch_size=1,
confidence=0,
learning_rate=5e-3,
binary_search_steps=5,
max_iterations=1000,
abort_early=True,
initial_const=1e-2,
clip_min=0,
clip_max=1,
):
"""
... | [
"def",
"parse_params",
"(",
"self",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"batch_size",
"=",
"1",
",",
"confidence",
"=",
"0",
",",
"learning_rate",
"=",
"5e-3",
",",
"binary_search_steps",
"=",
"5",
",",
"max_iterations",
"=",
"1000"... | [
104,
4
] | [
162,
32
] | python | en | ['en', 'error', 'th'] | False |
CWL2.__init__ | (
self,
sess,
model,
batch_size,
confidence,
targeted,
learning_rate,
binary_search_steps,
max_iterations,
abort_early,
initial_const,
clip_min,
clip_max,
num_labels,
shape,
) |
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param sess: a TF session.
:param model: a cleverhans.model.Model object.
:param batch_size: Number of attacks to run simultaneously.
:pa... |
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors. | def __init__(
self,
sess,
model,
batch_size,
confidence,
targeted,
learning_rate,
binary_search_steps,
max_iterations,
abort_early,
initial_const,
clip_min,
clip_max,
num_labels,
shape,
):
... | [
"def",
"__init__",
"(",
"self",
",",
"sess",
",",
"model",
",",
"batch_size",
",",
"confidence",
",",
"targeted",
",",
"learning_rate",
",",
"binary_search_steps",
",",
"max_iterations",
",",
"abort_early",
",",
"initial_const",
",",
"clip_min",
",",
"clip_max",... | [
170,
4
] | [
305,
76
] | python | en | ['en', 'error', 'th'] | False |
CWL2.attack | (self, imgs, targets) |
Perform the L_2 attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
|
Perform the L_2 attack on the given instance for the given targets. | def attack(self, imgs, targets):
"""
Perform the L_2 attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
r = []
for ... | [
"def",
"attack",
"(",
"self",
",",
"imgs",
",",
"targets",
")",
":",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"imgs",
")",
",",
"self",
".",
"batch_size",
")",
":",
"_logger",
".",
"debug",
"(",
"(",
"\"Running ... | [
307,
4
] | [
323,
26
] | python | en | ['en', 'error', 'th'] | False |
CWL2.attack_batch | (self, imgs, labs) |
Run the attack on a batch of instance and labels.
|
Run the attack on a batch of instance and labels.
| def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
... | [
"def",
"attack_batch",
"(",
"self",
",",
"imgs",
",",
"labs",
")",
":",
"def",
"compare",
"(",
"x",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"int64",
")",
")",
":",
"x",
"=",
"np"... | [
325,
4
] | [
459,
27
] | python | en | ['en', 'error', 'th'] | False |
putchunk | (fp, cid, *data) | Write a PNG chunk (including CRC field) | Write a PNG chunk (including CRC field) | def putchunk(fp, cid, *data):
"""Write a PNG chunk (including CRC field)"""
data = b"".join(data)
fp.write(o32(len(data)) + cid)
fp.write(data)
crc = _crc32(data, _crc32(cid))
fp.write(o32(crc)) | [
"def",
"putchunk",
"(",
"fp",
",",
"cid",
",",
"*",
"data",
")",
":",
"data",
"=",
"b\"\"",
".",
"join",
"(",
"data",
")",
"fp",
".",
"write",
"(",
"o32",
"(",
"len",
"(",
"data",
")",
")",
"+",
"cid",
")",
"fp",
".",
"write",
"(",
"data",
... | [
969,
0
] | [
977,
22
] | python | en | ['en', 'en', 'en'] | True |
getchunks | (im, **params) | Return a list of PNG chunks representing this image. | Return a list of PNG chunks representing this image. | def getchunks(im, **params):
"""Return a list of PNG chunks representing this image."""
class collector:
data = []
def write(self, data):
pass
def append(self, chunk):
self.data.append(chunk)
def append(fp, cid, *data):
data = b"".join(data)
... | [
"def",
"getchunks",
"(",
"im",
",",
"*",
"*",
"params",
")",
":",
"class",
"collector",
":",
"data",
"=",
"[",
"]",
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"pass",
"def",
"append",
"(",
"self",
",",
"chunk",
")",
":",
"self",
".",
"... | [
1295,
0
] | [
1320,
18
] | python | en | ['en', 'en', 'en'] | True |
ChunkStream.read | (self) | Fetch a new chunk. Returns header information. | Fetch a new chunk. Returns header information. | def read(self):
"""Fetch a new chunk. Returns header information."""
cid = None
if self.queue:
cid, pos, length = self.queue.pop()
self.fp.seek(pos)
else:
s = self.fp.read(8)
cid = s[4:]
pos = self.fp.tell()
length ... | [
"def",
"read",
"(",
"self",
")",
":",
"cid",
"=",
"None",
"if",
"self",
".",
"queue",
":",
"cid",
",",
"pos",
",",
"length",
"=",
"self",
".",
"queue",
".",
"pop",
"(",
")",
"self",
".",
"fp",
".",
"seek",
"(",
"pos",
")",
"else",
":",
"s",
... | [
117,
4
] | [
134,
31
] | python | en | ['en', 'en', 'en'] | True |
ChunkStream.call | (self, cid, pos, length) | Call the appropriate chunk handler | Call the appropriate chunk handler | def call(self, cid, pos, length):
"""Call the appropriate chunk handler"""
logger.debug("STREAM %r %s %s", cid, pos, length)
return getattr(self, "chunk_" + cid.decode("ascii"))(pos, length) | [
"def",
"call",
"(",
"self",
",",
"cid",
",",
"pos",
",",
"length",
")",
":",
"logger",
".",
"debug",
"(",
"\"STREAM %r %s %s\"",
",",
"cid",
",",
"pos",
",",
"length",
")",
"return",
"getattr",
"(",
"self",
",",
"\"chunk_\"",
"+",
"cid",
".",
"decode... | [
149,
4
] | [
153,
73
] | python | en | ['en', 'en', 'en'] | True |
ChunkStream.crc | (self, cid, data) | Read and verify checksum | Read and verify checksum | def crc(self, cid, data):
"""Read and verify checksum"""
# Skip CRC checks for ancillary chunks if allowed to load truncated
# images
# 5th byte of first char is 1 [specs, section 5.4]
if ImageFile.LOAD_TRUNCATED_IMAGES and (i8(cid[0]) >> 5 & 1):
self.crc_skip(cid, d... | [
"def",
"crc",
"(",
"self",
",",
"cid",
",",
"data",
")",
":",
"# Skip CRC checks for ancillary chunks if allowed to load truncated",
"# images",
"# 5th byte of first char is 1 [specs, section 5.4]",
"if",
"ImageFile",
".",
"LOAD_TRUNCATED_IMAGES",
"and",
"(",
"i8",
"(",
"ci... | [
155,
4
] | [
173,
20
] | python | en | ['en', 'pt', 'en'] | True |
ChunkStream.crc_skip | (self, cid, data) | Read checksum. Used if the C module is not present | Read checksum. Used if the C module is not present | def crc_skip(self, cid, data):
"""Read checksum. Used if the C module is not present"""
self.fp.read(4) | [
"def",
"crc_skip",
"(",
"self",
",",
"cid",
",",
"data",
")",
":",
"self",
".",
"fp",
".",
"read",
"(",
"4",
")"
] | [
175,
4
] | [
178,
23
] | python | en | ['en', 'en', 'en'] | True |
iTXt.__new__ | (cls, text, lang=None, tkey=None) |
:param cls: the class to use when creating the instance
:param text: value for this key
:param lang: language code
:param tkey: UTF-8 version of the key name
|
:param cls: the class to use when creating the instance
:param text: value for this key
:param lang: language code
:param tkey: UTF-8 version of the key name
| def __new__(cls, text, lang=None, tkey=None):
"""
:param cls: the class to use when creating the instance
:param text: value for this key
:param lang: language code
:param tkey: UTF-8 version of the key name
"""
self = str.__new__(cls, text)
self.lang = l... | [
"def",
"__new__",
"(",
"cls",
",",
"text",
",",
"lang",
"=",
"None",
",",
"tkey",
"=",
"None",
")",
":",
"self",
"=",
"str",
".",
"__new__",
"(",
"cls",
",",
"text",
")",
"self",
".",
"lang",
"=",
"lang",
"self",
".",
"tkey",
"=",
"tkey",
"retu... | [
209,
4
] | [
220,
19
] | python | en | ['en', 'error', 'th'] | False |
PngInfo.add | (self, cid, data) | Appends an arbitrary chunk. Use with caution.
:param cid: a byte string, 4 bytes long.
:param data: a byte string of the encoded data
| Appends an arbitrary chunk. Use with caution. | def add(self, cid, data):
"""Appends an arbitrary chunk. Use with caution.
:param cid: a byte string, 4 bytes long.
:param data: a byte string of the encoded data
"""
self.chunks.append((cid, data)) | [
"def",
"add",
"(",
"self",
",",
"cid",
",",
"data",
")",
":",
"self",
".",
"chunks",
".",
"append",
"(",
"(",
"cid",
",",
"data",
")",
")"
] | [
232,
4
] | [
240,
39
] | python | en | ['en', 'en', 'en'] | True |
PngInfo.add_itxt | (self, key, value, lang="", tkey="", zip=False) | Appends an iTXt chunk.
:param key: latin-1 encodable text key name
:param value: value for this key
:param lang: language code
:param tkey: UTF-8 version of the key name
:param zip: compression flag
| Appends an iTXt chunk. | def add_itxt(self, key, value, lang="", tkey="", zip=False):
"""Appends an iTXt chunk.
:param key: latin-1 encodable text key name
:param value: value for this key
:param lang: language code
:param tkey: UTF-8 version of the key name
:param zip: compression flag
... | [
"def",
"add_itxt",
"(",
"self",
",",
"key",
",",
"value",
",",
"lang",
"=",
"\"\"",
",",
"tkey",
"=",
"\"\"",
",",
"zip",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"bytes",
")",
":",
"key",
"=",
"key",
".",
"encode",
"... | [
242,
4
] | [
268,
84
] | python | en | ['en', 'en', 'en'] | True |
PngInfo.add_text | (self, key, value, zip=False) | Appends a text chunk.
:param key: latin-1 encodable text key name
:param value: value for this key, text or an
:py:class:`PIL.PngImagePlugin.iTXt` instance
:param zip: compression flag
| Appends a text chunk. | def add_text(self, key, value, zip=False):
"""Appends a text chunk.
:param key: latin-1 encodable text key name
:param value: value for this key, text or an
:py:class:`PIL.PngImagePlugin.iTXt` instance
:param zip: compression flag
"""
if isinstance(value, iTX... | [
"def",
"add_text",
"(",
"self",
",",
"key",
",",
"value",
",",
"zip",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"iTXt",
")",
":",
"return",
"self",
".",
"add_itxt",
"(",
"key",
",",
"value",
",",
"value",
".",
"lang",
",",
"v... | [
270,
4
] | [
295,
50
] | python | en | ['en', 'en', 'en'] | True |
PngImageFile.verify | (self) | Verify PNG file | Verify PNG file | def verify(self):
"""Verify PNG file"""
if self.fp is None:
raise RuntimeError("verify must be called directly after open")
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
self.png.verify()
self.png.close()
if self._exclusive... | [
"def",
"verify",
"(",
"self",
")",
":",
"if",
"self",
".",
"fp",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"verify must be called directly after open\"",
")",
"# back up to beginning of IDAT block",
"self",
".",
"fp",
".",
"seek",
"(",
"self",
".",
"til... | [
715,
4
] | [
729,
22
] | python | en | ['en', 'fr', 'en'] | True |
PngImageFile.load_prepare | (self) | internal: prepare to read PNG file | internal: prepare to read PNG file | def load_prepare(self):
"""internal: prepare to read PNG file"""
if self.info.get("interlace"):
self.decoderconfig = self.decoderconfig + (1,)
self.__idat = self.__prepare_idat # used by load_read()
ImageFile.ImageFile.load_prepare(self) | [
"def",
"load_prepare",
"(",
"self",
")",
":",
"if",
"self",
".",
"info",
".",
"get",
"(",
"\"interlace\"",
")",
":",
"self",
".",
"decoderconfig",
"=",
"self",
".",
"decoderconfig",
"+",
"(",
"1",
",",
")",
"self",
".",
"__idat",
"=",
"self",
".",
... | [
822,
4
] | [
829,
46
] | python | en | ['en', 'en', 'en'] | True |
PngImageFile.load_read | (self, read_bytes) | internal: read more image data | internal: read more image data | def load_read(self, read_bytes):
"""internal: read more image data"""
while self.__idat == 0:
# end of chunk, skip forward to next one
self.fp.read(4) # CRC
cid, pos, length = self.png.read()
if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
... | [
"def",
"load_read",
"(",
"self",
",",
"read_bytes",
")",
":",
"while",
"self",
".",
"__idat",
"==",
"0",
":",
"# end of chunk, skip forward to next one",
"self",
".",
"fp",
".",
"read",
"(",
"4",
")",
"# CRC",
"cid",
",",
"pos",
",",
"length",
"=",
"self... | [
831,
4
] | [
862,
39
] | python | en | ['fr', 'en', 'en'] | True |
PngImageFile.load_end | (self) | internal: finished reading image data | internal: finished reading image data | def load_end(self):
"""internal: finished reading image data"""
while True:
self.fp.read(4) # CRC
try:
cid, pos, length = self.png.read()
except (struct.error, SyntaxError):
break
if cid == b"IEND":
break
... | [
"def",
"load_end",
"(",
"self",
")",
":",
"while",
"True",
":",
"self",
".",
"fp",
".",
"read",
"(",
"4",
")",
"# CRC",
"try",
":",
"cid",
",",
"pos",
",",
"length",
"=",
"self",
".",
"png",
".",
"read",
"(",
")",
"except",
"(",
"struct",
".",
... | [
864,
4
] | [
922,
65
] | python | en | ['fr', 'zu', 'en'] | False |
sanitize_replace_with_xxx | (value) |
Sanitize a string value by replacing it with x's.
>>> sanitize_replace_with_xxx('')
''
>>> sanitize_replace_with_xxx(None)
>>> sanitize_replace_with_xxx('Hello')
'xxxxx'
>>> sanitize_replace_with_xxx('Hello Sanitized World!')
'xxxxx xxxxxxxxx xxxxx!'
|
Sanitize a string value by replacing it with x's. | def sanitize_replace_with_xxx(value):
"""
Sanitize a string value by replacing it with x's.
>>> sanitize_replace_with_xxx('')
''
>>> sanitize_replace_with_xxx(None)
>>> sanitize_replace_with_xxx('Hello')
'xxxxx'
>>> sanitize_replace_with_xxx('Hello Sanitized World!')
'xxxxx xxxxx... | [
"def",
"sanitize_replace_with_xxx",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"value",
"return",
"_WORD_CHAR_RX",
".",
"sub",
"(",
"'x'",
",",
"value",
")"
] | [
5,
0
] | [
22,
40
] | python | en | ['en', 'error', 'th'] | False |
carlini_wagner_l2 | (model_fn, x, **kwargs) |
This is the function interface for the Carlini-Wagner-L2 attack.
For more details on the attack and the parameters see the corresponding class.
|
This is the function interface for the Carlini-Wagner-L2 attack.
For more details on the attack and the parameters see the corresponding class.
| def carlini_wagner_l2(model_fn, x, **kwargs):
"""
This is the function interface for the Carlini-Wagner-L2 attack.
For more details on the attack and the parameters see the corresponding class.
"""
return CarliniWagnerL2(model_fn, **kwargs).attack(x) | [
"def",
"carlini_wagner_l2",
"(",
"model_fn",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"CarliniWagnerL2",
"(",
"model_fn",
",",
"*",
"*",
"kwargs",
")",
".",
"attack",
"(",
"x",
")"
] | [
7,
0
] | [
12,
56
] | python | en | ['en', 'error', 'th'] | False |
CarliniWagnerL2.__init__ | (
self,
model_fn,
y=None,
targeted=False,
batch_size=128,
clip_min=0.0,
clip_max=1.0,
binary_search_steps=5,
max_iterations=1_000,
abort_early=True,
confidence=0.0,
initial_const=1e-2,
learning_rate=5e-3,
) |
This attack was originally proposed by Carlini and Wagner. It is an
iterative attack that finds adversarial examples on many defenses that
are robust to other attacks.
Paper link: https://arxiv.org/abs/1608.04644
At a high level, this attack is an iterative attack using Adam and... |
This attack was originally proposed by Carlini and Wagner. It is an
iterative attack that finds adversarial examples on many defenses that
are robust to other attacks.
Paper link: https://arxiv.org/abs/1608.04644
At a high level, this attack is an iterative attack using Adam and... | def __init__(
self,
model_fn,
y=None,
targeted=False,
batch_size=128,
clip_min=0.0,
clip_max=1.0,
binary_search_steps=5,
max_iterations=1_000,
abort_early=True,
confidence=0.0,
initial_const=1e-2,
learning_rate=5e-3,... | [
"def",
"__init__",
"(",
"self",
",",
"model_fn",
",",
"y",
"=",
"None",
",",
"targeted",
"=",
"False",
",",
"batch_size",
"=",
"128",
",",
"clip_min",
"=",
"0.0",
",",
"clip_max",
"=",
"1.0",
",",
"binary_search_steps",
"=",
"5",
",",
"max_iterations",
... | [
20,
4
] | [
97,
47
] | python | en | ['en', 'error', 'th'] | False |
CarliniWagnerL2.attack | (self, x) |
Returns adversarial examples for the tensor.
:param x: input tensor.
:return: a numpy tensor with the adversarial example.
|
Returns adversarial examples for the tensor.
:param x: input tensor.
:return: a numpy tensor with the adversarial example.
| def attack(self, x):
"""
Returns adversarial examples for the tensor.
:param x: input tensor.
:return: a numpy tensor with the adversarial example.
"""
adv_ex = np.zeros_like(x)
for i in range(0, len(x), self.batch_size):
adv_ex[i : i + self.batch_size... | [
"def",
"attack",
"(",
"self",
",",
"x",
")",
":",
"adv_ex",
"=",
"np",
".",
"zeros_like",
"(",
"x",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"x",
")",
",",
"self",
".",
"batch_size",
")",
":",
"adv_ex",
"[",
"i",
":",
"i",
... | [
99,
4
] | [
111,
21
] | python | en | ['en', 'error', 'th'] | False |
sew_messages_and_reactions | (
messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]]
) | Given a iterable of messages and reactions stitch reactions
into messages.
| Given a iterable of messages and reactions stitch reactions
into messages.
| def sew_messages_and_reactions(
messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]]
) -> List[Dict[str, Any]]:
"""Given a iterable of messages and reactions stitch reactions
into messages.
"""
# Add all messages with empty reaction item
for message in messages:
message["react... | [
"def",
"sew_messages_and_reactions",
"(",
"messages",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"reactions",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
... | [
177,
0
] | [
193,
44
] | python | en | ['en', 'en', 'en'] | True |
access_message | (
user_profile: UserProfile, message_id: int
) | You can access a message by ID in our APIs that either:
(1) You received or have previously accessed via starring
(aka have a UserMessage row for).
(2) Was sent to a public stream in your realm.
We produce consistent, boring error messages to avoid leaking any
information from a security perspe... | You can access a message by ID in our APIs that either:
(1) You received or have previously accessed via starring
(aka have a UserMessage row for).
(2) Was sent to a public stream in your realm. | def access_message(
user_profile: UserProfile, message_id: int
) -> Tuple[Message, Optional[UserMessage]]:
"""You can access a message by ID in our APIs that either:
(1) You received or have previously accessed via starring
(aka have a UserMessage row for).
(2) Was sent to a public stream in you... | [
"def",
"access_message",
"(",
"user_profile",
":",
"UserProfile",
",",
"message_id",
":",
"int",
")",
"->",
"Tuple",
"[",
"Message",
",",
"Optional",
"[",
"UserMessage",
"]",
"]",
":",
"try",
":",
"message",
"=",
"Message",
".",
"objects",
".",
"select_rel... | [
655,
0
] | [
675,
48
] | python | en | ['en', 'en', 'en'] | True |
bulk_access_messages_expect_usermessage | (
user_profile_id: int, message_ids: Sequence[int]
) |
Like bulk_access_messages, but faster and potentially stricter.
Returns a subset of `message_ids` containing only messages the
user can access. Makes O(1) database queries.
Use this function only when the user is expected to have a
UserMessage row for every message in `message_ids`. If a
Us... |
Like bulk_access_messages, but faster and potentially stricter. | def bulk_access_messages_expect_usermessage(
user_profile_id: int, message_ids: Sequence[int]
) -> List[int]:
"""
Like bulk_access_messages, but faster and potentially stricter.
Returns a subset of `message_ids` containing only messages the
user can access. Makes O(1) database queries.
Use th... | [
"def",
"bulk_access_messages_expect_usermessage",
"(",
"user_profile_id",
":",
"int",
",",
"message_ids",
":",
"Sequence",
"[",
"int",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"UserMessage",
".",
"objects",
".",
"filter",
"(",
"user_profile_id",
... | [
730,
0
] | [
749,
42
] | python | en | ['en', 'error', 'th'] | False |
render_markdown | (
message: Message,
content: str,
realm: Optional[Realm] = None,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
mention_data: Optional[MentionData] = None,
email_gateway: bool = False,
) |
This is basically just a wrapper for do_render_markdown.
|
This is basically just a wrapper for do_render_markdown.
| def render_markdown(
message: Message,
content: str,
realm: Optional[Realm] = None,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
mention_data: Optional[MentionData] = None,
email_gateway: bool = False,
) -> str:
"""
This is basically just a wrapper for do_render_m... | [
"def",
"render_markdown",
"(",
"message",
":",
"Message",
",",
"content",
":",
"str",
",",
"realm",
":",
"Optional",
"[",
"Realm",
"]",
"=",
"None",
",",
"realm_alert_words_automaton",
":",
"Optional",
"[",
"ahocorasick",
".",
"Automaton",
"]",
"=",
"None",
... | [
752,
0
] | [
782,
27
] | python | en | ['en', 'error', 'th'] | False |
do_render_markdown | (
message: Message,
content: str,
realm: Realm,
sent_by_bot: bool,
translate_emoticons: bool,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
mention_data: Optional[MentionData] = None,
email_gateway: bool = False,
) | Return HTML for given Markdown. Markdown may add properties to the
message object such as `mentions_user_ids`, `mentions_user_group_ids`, and
`mentions_wildcard`. These are only on this Django object and are not
saved in the database.
| Return HTML for given Markdown. Markdown may add properties to the
message object such as `mentions_user_ids`, `mentions_user_group_ids`, and
`mentions_wildcard`. These are only on this Django object and are not
saved in the database.
| def do_render_markdown(
message: Message,
content: str,
realm: Realm,
sent_by_bot: bool,
translate_emoticons: bool,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
mention_data: Optional[MentionData] = None,
email_gateway: bool = False,
) -> str:
"""Return HTML f... | [
"def",
"do_render_markdown",
"(",
"message",
":",
"Message",
",",
"content",
":",
"str",
",",
"realm",
":",
"Realm",
",",
"sent_by_bot",
":",
"bool",
",",
"translate_emoticons",
":",
"bool",
",",
"realm_alert_words_automaton",
":",
"Optional",
"[",
"ahocorasick"... | [
785,
0
] | [
819,
27
] | python | en | ['en', 'en', 'en'] | True |
aggregate_message_dict | (
input_dict: Dict[int, Dict[str, Any]], lookup_fields: List[str], collect_senders: bool
) |
A concrete example might help explain the inputs here:
input_dict = {
1002: dict(stream_id=5, topic='foo', sender_id=40),
1003: dict(stream_id=5, topic='foo', sender_id=41),
1004: dict(stream_id=6, topic='baz', sender_id=99),
}
lookup_fields = ['stream_id', 'topic']
The f... |
A concrete example might help explain the inputs here: | def aggregate_message_dict(
input_dict: Dict[int, Dict[str, Any]], lookup_fields: List[str], collect_senders: bool
) -> List[Dict[str, Any]]:
lookup_dict: Dict[Tuple[Any, ...], Dict[str, Any]] = {}
"""
A concrete example might help explain the inputs here:
input_dict = {
1002: dict(stream_... | [
"def",
"aggregate_message_dict",
"(",
"input_dict",
":",
"Dict",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"lookup_fields",
":",
"List",
"[",
"str",
"]",
",",
"collect_senders",
":",
"bool",
")",
"->",
"List",
"[",
"Dict",
"[",
... | [
837,
0
] | [
897,
48
] | python | en | ['en', 'error', 'th'] | False |
get_recent_conversations_recipient_id | (
user_profile: UserProfile, recipient_id: int, sender_id: int
) | Helper for doing lookups of the recipient_id that
get_recent_private_conversations would have used to record that
message in its data structure.
| Helper for doing lookups of the recipient_id that
get_recent_private_conversations would have used to record that
message in its data structure.
| def get_recent_conversations_recipient_id(
user_profile: UserProfile, recipient_id: int, sender_id: int
) -> int:
"""Helper for doing lookups of the recipient_id that
get_recent_private_conversations would have used to record that
message in its data structure.
"""
my_recipient_id = user_profile... | [
"def",
"get_recent_conversations_recipient_id",
"(",
"user_profile",
":",
"UserProfile",
",",
"recipient_id",
":",
"int",
",",
"sender_id",
":",
"int",
")",
"->",
"int",
":",
"my_recipient_id",
"=",
"user_profile",
".",
"recipient_id",
"if",
"recipient_id",
"==",
... | [
1257,
0
] | [
1267,
23
] | python | en | ['en', 'en', 'en'] | True |
get_recent_private_conversations | (user_profile: UserProfile) | This function uses some carefully optimized SQL queries, designed
to use the UserMessage index on private_messages. It is
significantly complicated by the fact that for 1:1 private
messages, we store the message against a recipient_id of whichever
user was the recipient, and thus for 1:1 private messag... | This function uses some carefully optimized SQL queries, designed
to use the UserMessage index on private_messages. It is
significantly complicated by the fact that for 1:1 private
messages, we store the message against a recipient_id of whichever
user was the recipient, and thus for 1:1 private messag... | def get_recent_private_conversations(user_profile: UserProfile) -> Dict[int, Dict[str, Any]]:
"""This function uses some carefully optimized SQL queries, designed
to use the UserMessage index on private_messages. It is
significantly complicated by the fact that for 1:1 private
messages, we store the me... | [
"def",
"get_recent_private_conversations",
"(",
"user_profile",
":",
"UserProfile",
")",
"->",
"Dict",
"[",
"int",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"RECENT_CONVERSATIONS_LIMIT",
"=",
"1000",
"recipient_map",
"=",
"{",
"}",
"my_recipient_id",
... | [
1270,
0
] | [
1375,
24
] | python | en | ['en', 'en', 'en'] | True |
MessageDict.wide_dict | (message: Message, realm_id: Optional[int] = None) |
The next two lines get the cacheable field related
to our message object, with the side effect of
populating the cache.
|
The next two lines get the cacheable field related
to our message object, with the side effect of
populating the cache.
| def wide_dict(message: Message, realm_id: Optional[int] = None) -> Dict[str, Any]:
"""
The next two lines get the cacheable field related
to our message object, with the side effect of
populating the cache.
"""
json = message_to_dict_json(message, realm_id)
obj = ... | [
"def",
"wide_dict",
"(",
"message",
":",
"Message",
",",
"realm_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"json",
"=",
"message_to_dict_json",
"(",
"message",
",",
"realm_id",
")",
"obj",
... | [
256,
4
] | [
274,
18
] | python | en | ['en', 'error', 'th'] | False |
MessageDict.post_process_dicts | (
objs: List[Dict[str, Any]], apply_markdown: bool, client_gravatar: bool
) |
NOTE: This function mutates the objects in
the `objs` list, rather than making
shallow copies. It might be safer to
make shallow copies here, but performance
is somewhat important here, as we are
often fetching hundreds of messages.
... |
NOTE: This function mutates the objects in
the `objs` list, rather than making
shallow copies. It might be safer to
make shallow copies here, but performance
is somewhat important here, as we are
often fetching hundreds of messages.
... | def post_process_dicts(
objs: List[Dict[str, Any]], apply_markdown: bool, client_gravatar: bool
) -> None:
"""
NOTE: This function mutates the objects in
the `objs` list, rather than making
shallow copies. It might be safer to
make shallow copies he... | [
"def",
"post_process_dicts",
"(",
"objs",
":",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"apply_markdown",
":",
"bool",
",",
"client_gravatar",
":",
"bool",
")",
"->",
"None",
":",
"MessageDict",
".",
"bulk_hydrate_sender_info",
"(",
"obj... | [
277,
4
] | [
292,
94
] | python | en | ['en', 'error', 'th'] | False |
MessageDict.finalize_payload | (
obj: Dict[str, Any],
apply_markdown: bool,
client_gravatar: bool,
keep_rendered_content: bool = False,
skip_copy: bool = False,
) |
By default, we make a shallow copy of the incoming dict to avoid
mutation-related bugs. Code paths that are passing a unique object
can pass skip_copy=True to avoid this extra work.
|
By default, we make a shallow copy of the incoming dict to avoid
mutation-related bugs. Code paths that are passing a unique object
can pass skip_copy=True to avoid this extra work.
| def finalize_payload(
obj: Dict[str, Any],
apply_markdown: bool,
client_gravatar: bool,
keep_rendered_content: bool = False,
skip_copy: bool = False,
) -> Dict[str, Any]:
"""
By default, we make a shallow copy of the incoming dict to avoid
mutation-rel... | [
"def",
"finalize_payload",
"(",
"obj",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"apply_markdown",
":",
"bool",
",",
"client_gravatar",
":",
"bool",
",",
"keep_rendered_content",
":",
"bool",
"=",
"False",
",",
"skip_copy",
":",
"bool",
"=",
"False",
... | [
295,
4
] | [
327,
18
] | python | en | ['en', 'error', 'th'] | False |
MessageDict.build_dict_from_raw_db_row | (row: Dict[str, Any]) |
row is a row from a .values() call, and it needs to have
all the relevant fields populated
|
row is a row from a .values() call, and it needs to have
all the relevant fields populated
| def build_dict_from_raw_db_row(row: Dict[str, Any]) -> Dict[str, Any]:
"""
row is a row from a .values() call, and it needs to have
all the relevant fields populated
"""
return MessageDict.build_message_dict(
message_id=row["id"],
last_edit_time=row["last_... | [
"def",
"build_dict_from_raw_db_row",
"(",
"row",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"MessageDict",
".",
"build_message_dict",
"(",
"message_id",
"=",
"row",
"[",
"\"id\"",
"]",
",",
... | [
413,
4
] | [
436,
9
] | python | en | ['en', 'error', 'th'] | False |
MessageDict.hydrate_recipient_info | (obj: Dict[str, Any], display_recipient: DisplayRecipientT) |
This method hyrdrates recipient info with things
like full names and emails of senders. Eventually
our clients should be able to hyrdrate these fields
themselves with info they already have on users.
|
This method hyrdrates recipient info with things
like full names and emails of senders. Eventually
our clients should be able to hyrdrate these fields
themselves with info they already have on users.
| def hydrate_recipient_info(obj: Dict[str, Any], display_recipient: DisplayRecipientT) -> None:
"""
This method hyrdrates recipient info with things
like full names and emails of senders. Eventually
our clients should be able to hyrdrate these fields
themselves with info they alr... | [
"def",
"hydrate_recipient_info",
"(",
"obj",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"display_recipient",
":",
"DisplayRecipientT",
")",
"->",
"None",
":",
"recipient_type",
"=",
"obj",
"[",
"\"recipient_type\"",
"]",
"recipient_type_id",
"=",
"obj",
"[... | [
557,
4
] | [
596,
48
] | python | en | ['en', 'error', 'th'] | False |
ElasticNetMethod.__init__ | (self, model, sess, dtypestr="float32", **kwargs) |
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
|
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
| def __init__(self, model, sess, dtypestr="float32", **kwargs):
"""
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
wrapper_warning_logits()
model = Calla... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"wrapper_warning_logits",
"(",
")",
"model",
"=",
"Calla... | [
40,
4
] | [
66,
9
] | python | en | ['en', 'error', 'th'] | False |
ElasticNetMethod.generate | (self, x, **kwargs) |
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params`
|
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors. | def generate(self, x, **kwargs):
"""
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param x: (required) A tensor with the inputs.
:param kwargs: See `parse_params`
"""
assert (... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"(",
"self",
".",
"sess",
"is",
"not",
"None",
")",
",",
"\"Cannot use `generate` when no `sess` was provided\"",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
"... | [
68,
4
] | [
108,
19
] | python | en | ['en', 'error', 'th'] | False |
ElasticNetMethod.parse_params | (
self,
y=None,
y_target=None,
beta=1e-2,
decision_rule="EN",
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
max_iterations=1000,
abort_early=False,
initial_const=1e-3,
clip_min=0,
cli... |
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
... |
:param y: (optional) A tensor with the true labels for an untargeted
attack. If None (and y_target is None) then use the
original labels the classifier assigns.
:param y_target: (optional) A tensor with the target labels for a
targeted attack.
... | def parse_params(
self,
y=None,
y_target=None,
beta=1e-2,
decision_rule="EN",
batch_size=1,
confidence=0,
learning_rate=1e-2,
binary_search_steps=9,
max_iterations=1000,
abort_early=False,
initial_const=1e-3,
clip_mi... | [
"def",
"parse_params",
"(",
"self",
",",
"y",
"=",
"None",
",",
"y_target",
"=",
"None",
",",
"beta",
"=",
"1e-2",
",",
"decision_rule",
"=",
"\"EN\"",
",",
"batch_size",
"=",
"1",
",",
"confidence",
"=",
"0",
",",
"learning_rate",
"=",
"1e-2",
",",
... | [
110,
4
] | [
183,
32
] | python | en | ['en', 'error', 'th'] | False |
EAD.__init__ | (
self,
sess,
model,
beta,
decision_rule,
batch_size,
confidence,
targeted,
learning_rate,
binary_search_steps,
max_iterations,
abort_early,
initial_const,
clip_min,
clip_max,
num_labels,
... |
EAD Attack
Return a tensor that constructs adversarial examples for the given
input. Generate uses tf.py_func in order to operate over tensors.
:param sess: a TF session.
:param model: a cleverhans.model.Model object.
:param beta: Trades off L2 distortion with L1 disto... |
EAD Attack | def __init__(
self,
sess,
model,
beta,
decision_rule,
batch_size,
confidence,
targeted,
learning_rate,
binary_search_steps,
max_iterations,
abort_early,
initial_const,
clip_min,
clip_max,
num_... | [
"def",
"__init__",
"(",
"self",
",",
"sess",
",",
"model",
",",
"beta",
",",
"decision_rule",
",",
"batch_size",
",",
"confidence",
",",
"targeted",
",",
"learning_rate",
",",
"binary_search_steps",
",",
"max_iterations",
",",
"abort_early",
",",
"initial_const"... | [
187,
4
] | [
407,
63
] | python | en | ['en', 'error', 'th'] | False |
EAD.attack | (self, imgs, targets) |
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
|
Perform the EAD attack on the given instance for the given targets. | def attack(self, imgs, targets):
"""
Perform the EAD attack on the given instance for the given targets.
If self.targeted is true, then the targets represents the target labels
If self.targeted is false, then targets are the original class labels
"""
batch_size = self.b... | [
"def",
"attack",
"(",
"self",
",",
"imgs",
",",
"targets",
")",
":",
"batch_size",
"=",
"self",
".",
"batch_size",
"r",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"imgs",
")",
"//",
"batch_size",
")",
":",
"_logger",
"."... | [
409,
4
] | [
440,
26
] | python | en | ['en', 'error', 'th'] | False |
EAD.attack_batch | (self, imgs, labs) |
Run the attack on a batch of instance and labels.
|
Run the attack on a batch of instance and labels.
| def attack_batch(self, imgs, labs):
"""
Run the attack on a batch of instance and labels.
"""
def compare(x, y):
if not isinstance(x, (float, int, np.int64)):
x = np.copy(x)
if self.TARGETED:
x[y] -= self.CONFIDENCE
... | [
"def",
"attack_batch",
"(",
"self",
",",
"imgs",
",",
"labs",
")",
":",
"def",
"compare",
"(",
"x",
",",
"y",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"(",
"float",
",",
"int",
",",
"np",
".",
"int64",
")",
")",
":",
"x",
"=",
"np"... | [
442,
4
] | [
580,
27
] | python | en | ['en', 'error', 'th'] | False |
ip_address_validators | (protocol, unpack_ipv4) |
Depending on the given parameters returns the appropriate validators for
the GenericIPAddressField.
This code is here, because it is exactly the same for the model and the form field.
|
Depending on the given parameters returns the appropriate validators for
the GenericIPAddressField. | def ip_address_validators(protocol, unpack_ipv4):
"""
Depending on the given parameters returns the appropriate validators for
the GenericIPAddressField.
This code is here, because it is exactly the same for the model and the form field.
"""
if protocol != 'both' and unpack_ipv4:
raise ... | [
"def",
"ip_address_validators",
"(",
"protocol",
",",
"unpack_ipv4",
")",
":",
"if",
"protocol",
"!=",
"'both'",
"and",
"unpack_ipv4",
":",
"raise",
"ValueError",
"(",
"\"You can only use `unpack_ipv4` if `protocol` is set to 'both'\"",
")",
"try",
":",
"return",
"ip_ad... | [
222,
0
] | [
236,
70
] | python | en | ['en', 'error', 'th'] | False |
mock_inputs | (inputs) |
Decorator to temporarily replace input/getpass to allow interactive
createsuperuser.
|
Decorator to temporarily replace input/getpass to allow interactive
createsuperuser.
| def mock_inputs(inputs):
"""
Decorator to temporarily replace input/getpass to allow interactive
createsuperuser.
"""
def inner(test_func):
def wrapped(*args):
class mock_getpass:
@staticmethod
def getpass(prompt=b'Password: ', stream=None):
... | [
"def",
"mock_inputs",
"(",
"inputs",
")",
":",
"def",
"inner",
"(",
"test_func",
")",
":",
"def",
"wrapped",
"(",
"*",
"args",
")",
":",
"class",
"mock_getpass",
":",
"@",
"staticmethod",
"def",
"getpass",
"(",
"prompt",
"=",
"b'Password: '",
",",
"strea... | [
24,
0
] | [
61,
16
] | python | en | ['en', 'error', 'th'] | False |
CustomUserModelValidationTestCase.test_required_fields_is_list | (self) | REQUIRED_FIELDS should be a list. | REQUIRED_FIELDS should be a list. | def test_required_fields_is_list(self):
"REQUIRED_FIELDS should be a list."
from .custom_user import CustomUserNonListRequiredFields
errors = checks.run_checks()
expected = [
checks.Error(
"'REQUIRED_FIELDS' must be a list or tuple.",
hint=Non... | [
"def",
"test_required_fields_is_list",
"(",
"self",
")",
":",
"from",
".",
"custom_user",
"import",
"CustomUserNonListRequiredFields",
"errors",
"=",
"checks",
".",
"run_checks",
"(",
")",
"expected",
"=",
"[",
"checks",
".",
"Error",
"(",
"\"'REQUIRED_FIELDS' must ... | [
419,
4
] | [
432,
42
] | python | en | ['en', 'en', 'en'] | True |
CustomUserModelValidationTestCase.test_username_not_in_required_fields | (self) | USERNAME_FIELD should not appear in REQUIRED_FIELDS. | USERNAME_FIELD should not appear in REQUIRED_FIELDS. | def test_username_not_in_required_fields(self):
"USERNAME_FIELD should not appear in REQUIRED_FIELDS."
from .custom_user import CustomUserBadRequiredFields
errors = checks.run_checks()
expected = [
checks.Error(
("The field named as the 'USERNAME_FIELD' for a... | [
"def",
"test_username_not_in_required_fields",
"(",
"self",
")",
":",
"from",
".",
"custom_user",
"import",
"CustomUserBadRequiredFields",
"errors",
"=",
"checks",
".",
"run_checks",
"(",
")",
"expected",
"=",
"[",
"checks",
".",
"Error",
"(",
"(",
"\"The field na... | [
436,
4
] | [
450,
42
] | python | en | ['en', 'en', 'en'] | True |
CustomUserModelValidationTestCase.test_username_non_unique | (self) | A non-unique USERNAME_FIELD should raise a model validation error. | A non-unique USERNAME_FIELD should raise a model validation error. | def test_username_non_unique(self):
"A non-unique USERNAME_FIELD should raise a model validation error."
from .custom_user import CustomUserNonUniqueUsername
errors = checks.run_checks()
expected = [
checks.Error(
("'CustomUserNonUniqueUsername.username' must... | [
"def",
"test_username_non_unique",
"(",
"self",
")",
":",
"from",
".",
"custom_user",
"import",
"CustomUserNonUniqueUsername",
"errors",
"=",
"checks",
".",
"run_checks",
"(",
")",
"expected",
"=",
"[",
"checks",
".",
"Error",
"(",
"(",
"\"'CustomUserNonUniqueUser... | [
454,
4
] | [
468,
42
] | python | en | ['en', 'it', 'en'] | True |
CustomUserModelValidationTestCase.test_username_non_unique_with_custom_backend | (self) | A non-unique USERNAME_FIELD should raise an error only if we use the
default authentication backend. Otherwise, an warning should be raised.
| A non-unique USERNAME_FIELD should raise an error only if we use the
default authentication backend. Otherwise, an warning should be raised.
| def test_username_non_unique_with_custom_backend(self):
""" A non-unique USERNAME_FIELD should raise an error only if we use the
default authentication backend. Otherwise, an warning should be raised.
"""
from .custom_user import CustomUserNonUniqueUsername
errors = checks.run_c... | [
"def",
"test_username_non_unique_with_custom_backend",
"(",
"self",
")",
":",
"from",
".",
"custom_user",
"import",
"CustomUserNonUniqueUsername",
"errors",
"=",
"checks",
".",
"run_checks",
"(",
")",
"expected",
"=",
"[",
"checks",
".",
"Warning",
"(",
"(",
"\"'C... | [
475,
4
] | [
492,
42
] | python | en | ['en', 'en', 'en'] | True |
PermissionTestCase.test_duplicated_permissions | (self) |
Test that we show proper error message if we are trying to create
duplicate permissions.
|
Test that we show proper error message if we are trying to create
duplicate permissions.
| def test_duplicated_permissions(self):
"""
Test that we show proper error message if we are trying to create
duplicate permissions.
"""
auth_app_config = apps.get_app_config('auth')
# check duplicated default permission
models.Permission._meta.permissions = [
... | [
"def",
"test_duplicated_permissions",
"(",
"self",
")",
":",
"auth_app_config",
"=",
"apps",
".",
"get_app_config",
"(",
"'auth'",
")",
"# check duplicated default permission",
"models",
".",
"Permission",
".",
"_meta",
".",
"permissions",
"=",
"[",
"(",
"'change_pe... | [
508,
4
] | [
539,
56
] | python | en | ['en', 'error', 'th'] | False |
_add_doc | (func, doc) | Add documentation to a function. | Add documentation to a function. | def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc | [
"def",
"_add_doc",
"(",
"func",
",",
"doc",
")",
":",
"func",
".",
"__doc__",
"=",
"doc"
] | [
68,
0
] | [
70,
22
] | python | en | ['en', 'en', 'en'] | True |
_import_module | (name) | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | [
73,
0
] | [
76,
28
] | python | en | ['en', 'en', 'en'] | True |
add_move | (move) | Add an item to six.moves. | Add an item to six.moves. | def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move) | [
"def",
"add_move",
"(",
"move",
")",
":",
"setattr",
"(",
"_MovedItems",
",",
"move",
".",
"name",
",",
"move",
")"
] | [
396,
0
] | [
398,
41
] | python | en | ['en', 'en', 'en'] | True |
remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | [
401,
0
] | [
409,
62
] | python | en | ['en', 'en', 'en'] | True |
iterkeys | (d, **kw) | Return an iterator over the keys of a dictionary. | Return an iterator over the keys of a dictionary. | def iterkeys(d, **kw):
"""Return an iterator over the keys of a dictionary."""
return iter(getattr(d, _iterkeys)(**kw)) | [
"def",
"iterkeys",
"(",
"d",
",",
"*",
"*",
"kw",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_iterkeys",
")",
"(",
"*",
"*",
"kw",
")",
")"
] | [
487,
0
] | [
489,
44
] | python | en | ['en', 'en', 'en'] | True |
itervalues | (d, **kw) | Return an iterator over the values of a dictionary. | Return an iterator over the values of a dictionary. | def itervalues(d, **kw):
"""Return an iterator over the values of a dictionary."""
return iter(getattr(d, _itervalues)(**kw)) | [
"def",
"itervalues",
"(",
"d",
",",
"*",
"*",
"kw",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_itervalues",
")",
"(",
"*",
"*",
"kw",
")",
")"
] | [
491,
0
] | [
493,
46
] | python | en | ['en', 'en', 'en'] | True |
iteritems | (d, **kw) | Return an iterator over the (key, value) pairs of a dictionary. | Return an iterator over the (key, value) pairs of a dictionary. | def iteritems(d, **kw):
"""Return an iterator over the (key, value) pairs of a dictionary."""
return iter(getattr(d, _iteritems)(**kw)) | [
"def",
"iteritems",
"(",
"d",
",",
"*",
"*",
"kw",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_iteritems",
")",
"(",
"*",
"*",
"kw",
")",
")"
] | [
495,
0
] | [
497,
45
] | python | en | ['en', 'en', 'en'] | True |
iterlists | (d, **kw) | Return an iterator over the (key, [values]) pairs of a dictionary. | Return an iterator over the (key, [values]) pairs of a dictionary. | def iterlists(d, **kw):
"""Return an iterator over the (key, [values]) pairs of a dictionary."""
return iter(getattr(d, _iterlists)(**kw)) | [
"def",
"iterlists",
"(",
"d",
",",
"*",
"*",
"kw",
")",
":",
"return",
"iter",
"(",
"getattr",
"(",
"d",
",",
"_iterlists",
")",
"(",
"*",
"*",
"kw",
")",
")"
] | [
499,
0
] | [
501,
45
] | python | en | ['en', 'en', 'en'] | True |
with_metaclass | (meta, *bases) | Create a base class with a metaclass. | Create a base class with a metaclass. | def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass. Because of internal type checks
# we also need to ... | [
"def",
"with_metaclass",
"(",
"meta",
",",
"*",
"bases",
")",
":",
"# This requires a bit of explanation: the basic idea is to make a",
"# dummy metaclass for one level of class instantiation that replaces",
"# itself with the actual metaclass. Because of internal type checks",
"# we also n... | [
628,
0
] | [
643,
49
] | python | en | ['en', 'en', 'en'] | True |
add_metaclass | (metaclass) | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
slots = orig_vars.get('__slots__')
if slots is not None:
... | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"orig_vars",
".",
"pop",
"(",
"'__dict__'",
",",
"None",
")",
"orig_vars",
".",
"pop",
"(",
"... | [
646,
0
] | [
659,
18
] | python | en | ['en', 'en', 'en'] | True |
fix_messages | (apps: StateApps, schema_editor: DatabaseSchemaEditor) | Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT
UserProfile objects (their implementations were removed long ago).
We do this by:
* Changing their sent messages to have been sent by NOTIFICATION_BOT.
* Changing their 1:1 PMs to be PMs with NOTIFICATION_BOT and deleting thei... | Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT
UserProfile objects (their implementations were removed long ago). | def fix_messages(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT
UserProfile objects (their implementations were removed long ago).
We do this by:
* Changing their sent messages to have been sent by NOTIFICAT... | [
"def",
"fix_messages",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"UserProfile",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"UserProfile\"",
")",
"Huddle",
"=",
"apps",
".",
"get_mode... | [
8,
0
] | [
77,
12
] | python | en | ['en', 'en', 'en'] | True |
Git.get_current_branch | (cls, location) |
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
|
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
| def get_current_branch(cls, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
... | [
"def",
"get_current_branch",
"(",
"cls",
",",
"location",
")",
":",
"# git-symbolic-ref exits with empty stdout if \"HEAD\" is a detached",
"# HEAD rather than a symbolic ref. In addition, the -q causes the",
"# command to exit with status code 1 instead of 128 in this case",
"# and to suppre... | [
92,
4
] | [
110,
19
] | python | en | ['en', 'error', 'th'] | False |
Git.export | (self, location, url) | Export the Git repository at the url to the destination location | Export the Git repository at the url to the destination location | def export(self, location, url):
# type: (str, HiddenText) -> None
"""Export the Git repository at the url to the destination location"""
if not location.endswith('/'):
location = location + '/'
with TempDirectory(kind="export") as temp_dir:
self.unpack(temp_dir.... | [
"def",
"export",
"(",
"self",
",",
"location",
",",
"url",
")",
":",
"# type: (str, HiddenText) -> None",
"if",
"not",
"location",
".",
"endswith",
"(",
"'/'",
")",
":",
"location",
"=",
"location",
"+",
"'/'",
"with",
"TempDirectory",
"(",
"kind",
"=",
"\... | [
112,
4
] | [
123,
13
] | python | en | ['en', 'en', 'en'] | True |
Git.get_revision_sha | (cls, dest, rev) |
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
|
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None. | def get_revision_sha(cls, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev to... | [
"def",
"get_revision_sha",
"(",
"cls",
",",
"dest",
",",
"rev",
")",
":",
"# Pass rev to pre-filter the list.",
"output",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'show-ref'",
",",
"rev",
"]",
",",
"cwd",
"=",
"dest",
",",
"show_stdout",
"=",
"False",
",... | [
126,
4
] | [
158,
27
] | python | en | ['en', 'error', 'th'] | False |
Git.resolve_revision | (cls, dest, url, rev_options) |
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
|
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found. | def resolve_revision(cls, dest, url, rev_options):
# type: (str, HiddenText, RevOptions) -> RevOptions
"""
Resolve a revision to a new RevOptions object with the SHA1 of the
branch, tag, or ref if found.
Args:
rev_options: a RevOptions object.
"""
rev =... | [
"def",
"resolve_revision",
"(",
"cls",
",",
"dest",
",",
"url",
",",
"rev_options",
")",
":",
"# type: (str, HiddenText, RevOptions) -> RevOptions",
"rev",
"=",
"rev_options",
".",
"arg_rev",
"# The arg_rev property's implementation for Git ensures that the",
"# rev return valu... | [
161,
4
] | [
203,
26
] | python | en | ['en', 'error', 'th'] | False |
Git.is_commit_id_equal | (cls, dest, name) |
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
|
Return whether the current commit hash equals the given name. | def is_commit_id_equal(cls, dest, name):
"""
Return whether the current commit hash equals the given name.
Args:
dest: the repository directory.
name: a string name.
"""
if not name:
# Then avoid an unnecessary subprocess call.
return ... | [
"def",
"is_commit_id_equal",
"(",
"cls",
",",
"dest",
",",
"name",
")",
":",
"if",
"not",
"name",
":",
"# Then avoid an unnecessary subprocess call.",
"return",
"False",
"return",
"cls",
".",
"get_revision",
"(",
"dest",
")",
"==",
"name"
] | [
206,
4
] | [
218,
45
] | python | en | ['en', 'error', 'th'] | False |
Git.get_remote_url | (cls, location) |
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
|
Return URL of the first remote encountered. | def get_remote_url(cls, location):
"""
Return URL of the first remote encountered.
Raises RemoteNotFoundError if the repository does not have a remote
url configured.
"""
# We need to pass 1 for extra_ok_returncodes since the command
# exits with return code 1 if... | [
"def",
"get_remote_url",
"(",
"cls",
",",
"location",
")",
":",
"# We need to pass 1 for extra_ok_returncodes since the command",
"# exits with return code 1 if there are no matching lines.",
"stdout",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'config'",
",",
"'--get-regexp'",... | [
277,
4
] | [
301,
26
] | python | en | ['en', 'error', 'th'] | False |
Git.get_subdirectory | (cls, location) |
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
|
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
| def get_subdirectory(cls, location):
"""
Return the path to setup.py, relative to the repo root.
Return None if setup.py is in the repo root.
"""
# find the repo root
git_dir = cls.run_command(
['rev-parse', '--git-dir'],
show_stdout=False, cwd=loc... | [
"def",
"get_subdirectory",
"(",
"cls",
",",
"location",
")",
":",
"# find the repo root",
"git_dir",
"=",
"cls",
".",
"run_command",
"(",
"[",
"'rev-parse'",
",",
"'--git-dir'",
"]",
",",
"show_stdout",
"=",
"False",
",",
"cwd",
"=",
"location",
")",
".",
... | [
313,
4
] | [
325,
69
] | python | en | ['en', 'error', 'th'] | False |
Git.get_url_rev_and_auth | (cls, url) |
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we need a scheme for
parsing. Hence we remove it again afterwards and return it as a stub.
|
Prefixes stub URLs like 'user | def get_url_rev_and_auth(cls, url):
# type: (str) -> Tuple[str, Optional[str], AuthInfo]
"""
Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.
That's required because although they use SSH they sometimes don't
work with a ssh:// scheme (e.g. GitHub). But we nee... | [
"def",
"get_url_rev_and_auth",
"(",
"cls",
",",
"url",
")",
":",
"# type: (str) -> Tuple[str, Optional[str], AuthInfo]",
"# Works around an apparent Git bug",
"# (see https://article.gmane.org/gmane.comp.version-control.git/146500)",
"scheme",
",",
"netloc",
",",
"path",
",",
"quer... | [
328,
4
] | [
360,
34
] | python | en | ['en', 'error', 'th'] | False |
vatm | (
model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None,
) |
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized logits
:param x: the input placeholder
:param logits: the model's unnormalized output tensor (the input to
... |
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized logits
:param x: the input placeholder
:param logits: the model's unnormalized output tensor (the input to
... | def vatm(
model,
x,
logits,
eps,
num_iterations=1,
xi=1e-6,
clip_min=None,
clip_max=None,
scope=None,
):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which retu... | [
"def",
"vatm",
"(",
"model",
",",
"x",
",",
"logits",
",",
"eps",
",",
"num_iterations",
"=",
"1",
",",
"xi",
"=",
"1e-6",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"scope",
"=",
"None",
",",
")",
":",
"with",
"tf",
".",
... | [
112,
0
] | [
152,
20
] | python | en | ['en', 'error', 'th'] | False |
VirtualAdversarialMethod.__init__ | (self, model, sess=None, dtypestr="float32", **kwargs) |
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
|
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
| def __init__(self, model, sess=None, dtypestr="float32", **kwargs):
"""
Note: the model parameter should be an instance of the
cleverhans.model.Model abstraction provided by CleverHans.
"""
if not isinstance(model, Model):
wrapper_warning_logits()
model = ... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
"=",
"None",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"model",
",",
"Model",
")",
":",
"wrapper_warning_logits",
"(",
")",
"model"... | [
28,
4
] | [
40,
51
] | python | en | ['en', 'error', 'th'] | False |
VirtualAdversarialMethod.generate | (self, x, **kwargs) |
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
|
Generate symbolic graph for adversarial examples and return. | def generate(self, x, **kwargs):
"""
Generate symbolic graph for adversarial examples and return.
:param x: The model's symbolic inputs.
:param kwargs: See `parse_params`
"""
# Parse and save attack-specific parameters
assert self.parse_params(**kwargs)
... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# Parse and save attack-specific parameters",
"assert",
"self",
".",
"parse_params",
"(",
"*",
"*",
"kwargs",
")",
"return",
"vatm",
"(",
"self",
".",
"model",
",",
"x",
",",
"... | [
42,
4
] | [
61,
9
] | python | en | ['en', 'error', 'th'] | False |
VirtualAdversarialMethod.parse_params | (
self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs
) |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
Attack-specific parameters:
:param eps: (optional float )the epsilon (input variation parameter)
:param nb_iter: (optional) the number of iterations
Defaults to 1 ... |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes. | def parse_params(
self,
eps=2.0,
nb_iter=None,
xi=1e-6,
clip_min=None,
clip_max=None,
num_iterations=None,
**kwargs
):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
... | [
"def",
"parse_params",
"(",
"self",
",",
"eps",
"=",
"2.0",
",",
"nb_iter",
"=",
"None",
",",
"xi",
"=",
"1e-6",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
",",
"num_iterations",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# S... | [
63,
4
] | [
109,
19
] | python | en | ['en', 'error', 'th'] | False |
scantree | (root) |
Recurse the given directory yielding (pathname, os.stat(pathname)) pairs
|
Recurse the given directory yielding (pathname, os.stat(pathname)) pairs
| def scantree(root):
"""
Recurse the given directory yielding (pathname, os.stat(pathname)) pairs
"""
for entry in os.scandir(root):
if entry.is_dir():
yield from scantree(entry.path)
else:
yield entry.path, entry.stat() | [
"def",
"scantree",
"(",
"root",
")",
":",
"for",
"entry",
"in",
"os",
".",
"scandir",
"(",
"root",
")",
":",
"if",
"entry",
".",
"is_dir",
"(",
")",
":",
"yield",
"from",
"scantree",
"(",
"entry",
".",
"path",
")",
"else",
":",
"yield",
"entry",
... | [
264,
0
] | [
272,
42
] | python | en | ['en', 'error', 'th'] | False |
WhiteNoise.url_is_canonical | (url) |
Check that the URL path is in canonical format i.e. has normalised
slashes and no path traversal elements
|
Check that the URL path is in canonical format i.e. has normalised
slashes and no path traversal elements
| def url_is_canonical(url):
"""
Check that the URL path is in canonical format i.e. has normalised
slashes and no path traversal elements
"""
if "\\" in url:
return False
normalised = normpath(url)
if url.endswith("/") and url != "/":
normal... | [
"def",
"url_is_canonical",
"(",
"url",
")",
":",
"if",
"\"\\\\\"",
"in",
"url",
":",
"return",
"False",
"normalised",
"=",
"normpath",
"(",
"url",
")",
"if",
"url",
".",
"endswith",
"(",
"\"/\"",
")",
"and",
"url",
"!=",
"\"/\"",
":",
"normalised",
"+=... | [
181,
4
] | [
191,
32
] | python | en | ['en', 'error', 'th'] | False |
WhiteNoise.immutable_file_test | (self, path, url) |
This should be implemented by sub-classes (see e.g. WhiteNoiseMiddleware)
or by setting the `immutable_file_test` config option
|
This should be implemented by sub-classes (see e.g. WhiteNoiseMiddleware)
or by setting the `immutable_file_test` config option
| def immutable_file_test(self, path, url):
"""
This should be implemented by sub-classes (see e.g. WhiteNoiseMiddleware)
or by setting the `immutable_file_test` config option
"""
return False | [
"def",
"immutable_file_test",
"(",
"self",
",",
"path",
",",
"url",
")",
":",
"return",
"False"
] | [
237,
4
] | [
242,
20
] | python | en | ['en', 'error', 'th'] | False |
WhiteNoise.redirect | (self, from_url, to_url) |
Return a relative 302 redirect
We use relative redirects as we don't know the absolute URL the app is
being hosted under
|
Return a relative 302 redirect | def redirect(self, from_url, to_url):
"""
Return a relative 302 redirect
We use relative redirects as we don't know the absolute URL the app is
being hosted under
"""
if to_url == from_url + "/":
relative_url = from_url.split("/")[-1] + "/"
elif from_... | [
"def",
"redirect",
"(",
"self",
",",
"from_url",
",",
"to_url",
")",
":",
"if",
"to_url",
"==",
"from_url",
"+",
"\"/\"",
":",
"relative_url",
"=",
"from_url",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"+",
"\"/\"",
"elif",
"from_url",
"==... | [
244,
4
] | [
261,
54
] | python | en | ['en', 'error', 'th'] | False |
lookup | (tag) |
:param tag: Integer tag number
:returns: Taginfo namedtuple, From the TAGS_V2 info if possible,
otherwise just populating the value and name from TAGS.
If the tag is not recognized, "unknown" is returned for the name
|
:param tag: Integer tag number
:returns: Taginfo namedtuple, From the TAGS_V2 info if possible,
otherwise just populating the value and name from TAGS.
If the tag is not recognized, "unknown" is returned for the name | def lookup(tag):
"""
:param tag: Integer tag number
:returns: Taginfo namedtuple, From the TAGS_V2 info if possible,
otherwise just populating the value and name from TAGS.
If the tag is not recognized, "unknown" is returned for the name
"""
return TAGS_V2.get(tag, TagInfo(tag, TAG... | [
"def",
"lookup",
"(",
"tag",
")",
":",
"return",
"TAGS_V2",
".",
"get",
"(",
"tag",
",",
"TagInfo",
"(",
"tag",
",",
"TAGS",
".",
"get",
"(",
"tag",
",",
"\"unknown\"",
")",
")",
")"
] | [
35,
0
] | [
44,
67
] | 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.