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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Layer._make_feature | (self, feat_id) |
Helper routine for __getitem__ that constructs a Feature from the given
Feature ID. If the OGR Layer does not support random-access reading,
then each feature of the layer will be incremented through until the
a Feature is found matching the given feature ID.
|
Helper routine for __getitem__ that constructs a Feature from the given
Feature ID. If the OGR Layer does not support random-access reading,
then each feature of the layer will be incremented through until the
a Feature is found matching the given feature ID.
| def _make_feature(self, feat_id):
"""
Helper routine for __getitem__ that constructs a Feature from the given
Feature ID. If the OGR Layer does not support random-access reading,
then each feature of the layer will be incremented through until the
a Feature is found matching the... | [
"def",
"_make_feature",
"(",
"self",
",",
"feat_id",
")",
":",
"if",
"self",
".",
"_random_read",
":",
"# If the Layer supports random reading, return.",
"try",
":",
"return",
"Feature",
"(",
"capi",
".",
"get_feature",
"(",
"self",
".",
"ptr",
",",
"feat_id",
... | [
69,
4
] | [
89,
61
] | python | en | ['en', 'error', 'th'] | False |
Layer.extent | (self) | Return the extent (an Envelope) of this layer. | Return the extent (an Envelope) of this layer. | def extent(self):
"Return the extent (an Envelope) of this layer."
env = OGREnvelope()
capi.get_extent(self.ptr, byref(env), 1)
return Envelope(env) | [
"def",
"extent",
"(",
"self",
")",
":",
"env",
"=",
"OGREnvelope",
"(",
")",
"capi",
".",
"get_extent",
"(",
"self",
".",
"ptr",
",",
"byref",
"(",
"env",
")",
",",
"1",
")",
"return",
"Envelope",
"(",
"env",
")"
] | [
93,
4
] | [
97,
28
] | python | en | ['en', 'en', 'en'] | True |
Layer.name | (self) | Return the name of this layer in the Data Source. | Return the name of this layer in the Data Source. | def name(self):
"Return the name of this layer in the Data Source."
name = capi.get_fd_name(self._ldefn)
return force_str(name, self._ds.encoding, strings_only=True) | [
"def",
"name",
"(",
"self",
")",
":",
"name",
"=",
"capi",
".",
"get_fd_name",
"(",
"self",
".",
"_ldefn",
")",
"return",
"force_str",
"(",
"name",
",",
"self",
".",
"_ds",
".",
"encoding",
",",
"strings_only",
"=",
"True",
")"
] | [
100,
4
] | [
103,
68
] | python | en | ['en', 'en', 'en'] | True |
Layer.num_feat | (self, force=1) | Return the number of features in the Layer. | Return the number of features in the Layer. | def num_feat(self, force=1):
"Return the number of features in the Layer."
return capi.get_feature_count(self.ptr, force) | [
"def",
"num_feat",
"(",
"self",
",",
"force",
"=",
"1",
")",
":",
"return",
"capi",
".",
"get_feature_count",
"(",
"self",
".",
"ptr",
",",
"force",
")"
] | [
106,
4
] | [
108,
54
] | python | en | ['en', 'en', 'en'] | True |
Layer.num_fields | (self) | Return the number of fields in the Layer. | Return the number of fields in the Layer. | def num_fields(self):
"Return the number of fields in the Layer."
return capi.get_field_count(self._ldefn) | [
"def",
"num_fields",
"(",
"self",
")",
":",
"return",
"capi",
".",
"get_field_count",
"(",
"self",
".",
"_ldefn",
")"
] | [
111,
4
] | [
113,
48
] | python | en | ['en', 'en', 'en'] | True |
Layer.geom_type | (self) | Return the geometry type (OGRGeomType) of the Layer. | Return the geometry type (OGRGeomType) of the Layer. | def geom_type(self):
"Return the geometry type (OGRGeomType) of the Layer."
return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) | [
"def",
"geom_type",
"(",
"self",
")",
":",
"return",
"OGRGeomType",
"(",
"capi",
".",
"get_fd_geom_type",
"(",
"self",
".",
"_ldefn",
")",
")"
] | [
116,
4
] | [
118,
62
] | python | en | ['en', 'en', 'en'] | True |
Layer.srs | (self) | Return the Spatial Reference used in this Layer. | Return the Spatial Reference used in this Layer. | def srs(self):
"Return the Spatial Reference used in this Layer."
try:
ptr = capi.get_layer_srs(self.ptr)
return SpatialReference(srs_api.clone_srs(ptr))
except SRSException:
return None | [
"def",
"srs",
"(",
"self",
")",
":",
"try",
":",
"ptr",
"=",
"capi",
".",
"get_layer_srs",
"(",
"self",
".",
"ptr",
")",
"return",
"SpatialReference",
"(",
"srs_api",
".",
"clone_srs",
"(",
"ptr",
")",
")",
"except",
"SRSException",
":",
"return",
"Non... | [
121,
4
] | [
127,
23
] | python | en | ['en', 'en', 'en'] | True |
Layer.fields | (self) |
Return a list of string names corresponding to each of the Fields
available in this Layer.
|
Return a list of string names corresponding to each of the Fields
available in this Layer.
| def fields(self):
"""
Return a list of string names corresponding to each of the Fields
available in this Layer.
"""
return [force_str(
capi.get_field_name(capi.get_field_defn(self._ldefn, i)),
self._ds.encoding, strings_only=True,
) for i in range... | [
"def",
"fields",
"(",
"self",
")",
":",
"return",
"[",
"force_str",
"(",
"capi",
".",
"get_field_name",
"(",
"capi",
".",
"get_field_defn",
"(",
"self",
".",
"_ldefn",
",",
"i",
")",
")",
",",
"self",
".",
"_ds",
".",
"encoding",
",",
"strings_only",
... | [
130,
4
] | [
138,
42
] | python | en | ['en', 'error', 'th'] | False |
Layer.field_types | (self) |
Return a list of the types of fields in this Layer. For example,
return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that
has an integer, a floating-point, and string fields.
|
Return a list of the types of fields in this Layer. For example,
return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that
has an integer, a floating-point, and string fields.
| def field_types(self):
"""
Return a list of the types of fields in this Layer. For example,
return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that
has an integer, a floating-point, and string fields.
"""
return [OGRFieldTypes[capi.get_field_type(capi.get_... | [
"def",
"field_types",
"(",
"self",
")",
":",
"return",
"[",
"OGRFieldTypes",
"[",
"capi",
".",
"get_field_type",
"(",
"capi",
".",
"get_field_defn",
"(",
"self",
".",
"_ldefn",
",",
"i",
")",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"nu... | [
141,
4
] | [
148,
48
] | python | en | ['en', 'error', 'th'] | False |
Layer.field_widths | (self) | Return a list of the maximum field widths for the features. | Return a list of the maximum field widths for the features. | def field_widths(self):
"Return a list of the maximum field widths for the features."
return [capi.get_field_width(capi.get_field_defn(self._ldefn, i))
for i in range(self.num_fields)] | [
"def",
"field_widths",
"(",
"self",
")",
":",
"return",
"[",
"capi",
".",
"get_field_width",
"(",
"capi",
".",
"get_field_defn",
"(",
"self",
".",
"_ldefn",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_fields",
")",
"]"
] | [
151,
4
] | [
154,
48
] | python | en | ['en', 'en', 'en'] | True |
Layer.field_precisions | (self) | Return the field precisions for the features. | Return the field precisions for the features. | def field_precisions(self):
"Return the field precisions for the features."
return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i))
for i in range(self.num_fields)] | [
"def",
"field_precisions",
"(",
"self",
")",
":",
"return",
"[",
"capi",
".",
"get_field_precision",
"(",
"capi",
".",
"get_field_defn",
"(",
"self",
".",
"_ldefn",
",",
"i",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_fields",
")",
"]"... | [
157,
4
] | [
160,
48
] | python | en | ['en', 'en', 'en'] | True |
Layer.get_fields | (self, field_name) |
Return a list containing the given field name for every Feature
in the Layer.
|
Return a list containing the given field name for every Feature
in the Layer.
| def get_fields(self, field_name):
"""
Return a list containing the given field name for every Feature
in the Layer.
"""
if field_name not in self.fields:
raise GDALException('invalid field name: %s' % field_name)
return [feat.get(field_name) for feat in self] | [
"def",
"get_fields",
"(",
"self",
",",
"field_name",
")",
":",
"if",
"field_name",
"not",
"in",
"self",
".",
"fields",
":",
"raise",
"GDALException",
"(",
"'invalid field name: %s'",
"%",
"field_name",
")",
"return",
"[",
"feat",
".",
"get",
"(",
"field_name... | [
186,
4
] | [
193,
54
] | python | en | ['en', 'error', 'th'] | False |
Layer.get_geoms | (self, geos=False) |
Return a list containing the OGRGeometry for every Feature in
the Layer.
|
Return a list containing the OGRGeometry for every Feature in
the Layer.
| def get_geoms(self, geos=False):
"""
Return a list containing the OGRGeometry for every Feature in
the Layer.
"""
if geos:
from django.contrib.gis.geos import GEOSGeometry
return [GEOSGeometry(feat.geom.wkb) for feat in self]
else:
retu... | [
"def",
"get_geoms",
"(",
"self",
",",
"geos",
"=",
"False",
")",
":",
"if",
"geos",
":",
"from",
"django",
".",
"contrib",
".",
"gis",
".",
"geos",
"import",
"GEOSGeometry",
"return",
"[",
"GEOSGeometry",
"(",
"feat",
".",
"geom",
".",
"wkb",
")",
"f... | [
195,
4
] | [
204,
47
] | python | en | ['en', 'error', 'th'] | False |
Layer.test_capability | (self, capability) |
Return a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
'DeleteFeat... |
Return a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
'DeleteFeat... | def test_capability(self, capability):
"""
Return a bool indicating whether the this Layer supports the given
capability (a string). Valid capability strings include:
'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
'FastFeatureCount', 'FastGetExtent', 'C... | [
"def",
"test_capability",
"(",
"self",
",",
"capability",
")",
":",
"return",
"bool",
"(",
"capi",
".",
"test_capability",
"(",
"self",
".",
"ptr",
",",
"force_bytes",
"(",
"capability",
")",
")",
")"
] | [
206,
4
] | [
214,
76
] | python | en | ['en', 'error', 'th'] | False |
update_record_count | (count_a, count_b) | Updates the running number of records processed.
Given previous running total and current batch size, return new running total.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
count_b: tf.int64 scalar tensor of current batch size.
Returns:
A tf.int64 scalar tensor of new... | Updates the running number of records processed. | def update_record_count(count_a, count_b):
"""Updates the running number of records processed.
Given previous running total and current batch size, return new running total.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
count_b: tf.int64 scalar tensor of current batch size.... | [
"def",
"update_record_count",
"(",
"count_a",
",",
"count_b",
")",
":",
"return",
"count_a",
"+",
"count_b"
] | [
4,
0
] | [
16,
26
] | python | en | ['en', 'en', 'en'] | True |
update_mean_incremental | (count_a, mean_a, value_b) | Updates the running mean vector incrementally.
Given previous running total, running column means, and single example's
column values, return new running column means.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
mean_a: tf.float64 vector tensor of previous running column ... | Updates the running mean vector incrementally. | def update_mean_incremental(count_a, mean_a, value_b):
"""Updates the running mean vector incrementally.
Given previous running total, running column means, and single example's
column values, return new running column means.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
... | [
"def",
"update_mean_incremental",
"(",
"count_a",
",",
"mean_a",
",",
"value_b",
")",
":",
"umean_a",
"=",
"mean_a",
"*",
"tf",
".",
"cast",
"(",
"x",
"=",
"count_a",
",",
"dtype",
"=",
"tf",
".",
"float64",
")",
"mean_ab_num",
"=",
"umean_a",
"+",
"tf... | [
22,
0
] | [
40,
16
] | python | en | ['en', 'en', 'en'] | True |
update_cov_incremental | (
count_a, mean_a, cov_a, value_b, mean_ab, sample_cov) | Updates the running covariance matrix incrementally.
Given previous running total, running column means, running covariance matrix,
single example's column values, new running column means, and whether to use
sample covariance or not, return new running covariance matrix.
Args:
count_a: tf.int64 scalar te... | Updates the running covariance matrix incrementally. | def update_cov_incremental(
count_a, mean_a, cov_a, value_b, mean_ab, sample_cov):
"""Updates the running covariance matrix incrementally.
Given previous running total, running column means, running covariance matrix,
single example's column values, new running column means, and whether to use
sample covar... | [
"def",
"update_cov_incremental",
"(",
"count_a",
",",
"mean_a",
",",
"cov_a",
",",
"value_b",
",",
"mean_ab",
",",
"sample_cov",
")",
":",
"mean_diff",
"=",
"tf",
".",
"matmul",
"(",
"a",
"=",
"value_b",
"-",
"mean_a",
",",
"b",
"=",
"value_b",
"-",
"m... | [
44,
0
] | [
73,
15
] | python | en | ['en', 'de', 'en'] | True |
singleton_batch_cov_variable_updating | (
inner_size, X, count_variable, mean_variable, cov_variable) | Updates mahalanobis variables incrementally when number_of_rows equals 1.
Given the inner size of the matrix, the data vector X, the variable tracking
running record counts, the variable tracking running column means, and the
variable tracking running covariance matrix, returns updated running
covariance matri... | Updates mahalanobis variables incrementally when number_of_rows equals 1. | def singleton_batch_cov_variable_updating(
inner_size, X, count_variable, mean_variable, cov_variable):
"""Updates mahalanobis variables incrementally when number_of_rows equals 1.
Given the inner size of the matrix, the data vector X, the variable tracking
running record counts, the variable tracking runnin... | [
"def",
"singleton_batch_cov_variable_updating",
"(",
"inner_size",
",",
"X",
",",
"count_variable",
",",
"mean_variable",
",",
"cov_variable",
")",
":",
"# Calculate new combined mean for incremental covariance matrix calculation",
"# time_shape = (num_feat,), features_shape = (seq_len... | [
76,
0
] | [
134,
50
] | python | en | ['en', 'en', 'en'] | True |
singleton_batch_var_variable_updating | (
inner_size, x, count_variable, mean_variable, var_variable) | Updates mahalanobis thresh vars incrementally when number_of_rows equals 1.
Given the inner size of the matrix, the data scalar x, the variable tracking
running record counts, the variable tracking the running mean, and the
variable tracking the running variance, returns updated running variance,
running mean,... | Updates mahalanobis thresh vars incrementally when number_of_rows equals 1. | def singleton_batch_var_variable_updating(
inner_size, x, count_variable, mean_variable, var_variable):
"""Updates mahalanobis thresh vars incrementally when number_of_rows equals 1.
Given the inner size of the matrix, the data scalar x, the variable tracking
running record counts, the variable tracking the ... | [
"def",
"singleton_batch_var_variable_updating",
"(",
"inner_size",
",",
"x",
",",
"count_variable",
",",
"mean_variable",
",",
"var_variable",
")",
":",
"# Calculate new combined mean for incremental covariance matrix calculation",
"# time_shape = (), features_shape = ()",
"mean_ab",... | [
137,
0
] | [
195,
50
] | python | en | ['en', 'en', 'en'] | True |
update_mean_batch | (count_a, mean_a, count_b, mean_b) | Updates the running mean vector with a batch of data.
Given previous running total, running column means, current batch size, and
batch's column means, return new running column means.
Args:
count_a: tf.int64 scalar tensor of previous running total of records.
mean_a: tf.float64 vector tensor of previou... | Updates the running mean vector with a batch of data. | def update_mean_batch(count_a, mean_a, count_b, mean_b):
"""Updates the running mean vector with a batch of data.
Given previous running total, running column means, current batch size, and
batch's column means, return new running column means.
Args:
count_a: tf.int64 scalar tensor of previous running tot... | [
"def",
"update_mean_batch",
"(",
"count_a",
",",
"mean_a",
",",
"count_b",
",",
"mean_b",
")",
":",
"sum_a",
"=",
"mean_a",
"*",
"tf",
".",
"cast",
"(",
"x",
"=",
"count_a",
",",
"dtype",
"=",
"tf",
".",
"float64",
")",
"sum_b",
"=",
"mean_b",
"*",
... | [
201,
0
] | [
220,
16
] | python | en | ['en', 'en', 'en'] | True |
update_cov_batch | (
count_a, mean_a, cov_a, count_b, mean_b, cov_b, sample_cov) | Updates the running covariance matrix with batch of data.
Given previous running total, running column means, running covariance matrix,
current batch size, batch's column means, batch's covariance matrix, and
whether to use sample covariance or not, return new running covariance matrix.
Args:
count_a: tf... | Updates the running covariance matrix with batch of data. | def update_cov_batch(
count_a, mean_a, cov_a, count_b, mean_b, cov_b, sample_cov):
"""Updates the running covariance matrix with batch of data.
Given previous running total, running column means, running covariance matrix,
current batch size, batch's column means, batch's covariance matrix, and
whether to ... | [
"def",
"update_cov_batch",
"(",
"count_a",
",",
"mean_a",
",",
"cov_a",
",",
"count_b",
",",
"mean_b",
",",
"cov_b",
",",
"sample_cov",
")",
":",
"mean_diff",
"=",
"tf",
".",
"expand_dims",
"(",
"input",
"=",
"mean_a",
"-",
"mean_b",
",",
"axis",
"=",
... | [
223,
0
] | [
260,
15
] | python | en | ['en', 'en', 'en'] | True |
non_singleton_batch_cov_variable_updating | (
cur_batch_size, inner_size, X, count_variable, mean_variable, cov_variable) | Updates mahalanobis variables when number_of_rows does NOT equal 1.
Given the current batch size, inner size of the matrix, the data matrix X,
the variable tracking running record counts, the variable tracking running
column means, and the variable tracking running covariance matrix, returns
updated running co... | Updates mahalanobis variables when number_of_rows does NOT equal 1. | def non_singleton_batch_cov_variable_updating(
cur_batch_size, inner_size, X, count_variable, mean_variable, cov_variable):
"""Updates mahalanobis variables when number_of_rows does NOT equal 1.
Given the current batch size, inner size of the matrix, the data matrix X,
the variable tracking running record co... | [
"def",
"non_singleton_batch_cov_variable_updating",
"(",
"cur_batch_size",
",",
"inner_size",
",",
"X",
",",
"count_variable",
",",
"mean_variable",
",",
"cov_variable",
")",
":",
"# Find statistics of batch",
"number_of_rows",
"=",
"cur_batch_size",
"*",
"inner_size",
"#... | [
263,
0
] | [
342,
50
] | python | en | ['en', 'en', 'en'] | True |
non_singleton_batch_var_variable_updating | (
cur_batch_size, inner_size, x, count_variable, mean_variable, var_variable) | Updates mahalanobis thresh variables when number_of_rows does NOT equal 1.
Given the current batch size, inner size of the matrix, the data vector x,
the variable tracking the running record count, the variable tracking the
running mean, and the variable tracking the running variance, returns
updated running v... | Updates mahalanobis thresh variables when number_of_rows does NOT equal 1. | def non_singleton_batch_var_variable_updating(
cur_batch_size, inner_size, x, count_variable, mean_variable, var_variable):
"""Updates mahalanobis thresh variables when number_of_rows does NOT equal 1.
Given the current batch size, inner size of the matrix, the data vector x,
the variable tracking the runnin... | [
"def",
"non_singleton_batch_var_variable_updating",
"(",
"cur_batch_size",
",",
"inner_size",
",",
"x",
",",
"count_variable",
",",
"mean_variable",
",",
"var_variable",
")",
":",
"# Find statistics of batch",
"number_of_rows",
"=",
"cur_batch_size",
"*",
"inner_size",
"#... | [
345,
0
] | [
421,
50
] | python | en | ['en', 'en', 'en'] | True |
mahalanobis_dist | (err_vec, mean_vec, inv_cov, final_shape) | Calculates mahalanobis distance from MLE.
Given reconstruction error vector, mean reconstruction error vector, inverse
covariance of reconstruction error, and mahalanobis distance tensor's final
shape, return mahalanobis distance.
Args:
err_vec: tf.float64 matrix tensor of reconstruction errors.
mean_... | Calculates mahalanobis distance from MLE. | def mahalanobis_dist(err_vec, mean_vec, inv_cov, final_shape):
"""Calculates mahalanobis distance from MLE.
Given reconstruction error vector, mean reconstruction error vector, inverse
covariance of reconstruction error, and mahalanobis distance tensor's final
shape, return mahalanobis distance.
Args:
e... | [
"def",
"mahalanobis_dist",
"(",
"err_vec",
",",
"mean_vec",
",",
"inv_cov",
",",
"final_shape",
")",
":",
"# time_shape = (cur_batch_size * seq_len, num_feat)",
"# features_shape = (cur_batch_size * num_feat, seq_len)",
"err_vec_cen",
"=",
"err_vec",
"-",
"mean_vec",
"# time_sh... | [
424,
0
] | [
469,
43
] | python | en | ['en', 'su', 'en'] | True |
calculate_error_distribution_statistics_training | (
cur_batch_size,
X_time_abs_recon_err,
abs_err_count_time_var,
abs_err_mean_time_var,
abs_err_cov_time_var,
abs_err_inv_cov_time_var,
X_feat_abs_recon_err,
abs_err_count_feat_var,
abs_err_mean_feat_var,
abs_err_cov_feat_var,
abs_err_inv_cov_feat_var,
params,
dummy_va... | Calculates error distribution statistics during training mode.
Given dimensions of inputs, reconstructed inputs' absolute errors, and
variables tracking counts, means, and covariances of error distribution,
returns loss and train_op.
Args:
cur_batch_size: Current batch size, could be partially filled.
... | Calculates error distribution statistics during training mode. | def calculate_error_distribution_statistics_training(
cur_batch_size,
X_time_abs_recon_err,
abs_err_count_time_var,
abs_err_mean_time_var,
abs_err_cov_time_var,
abs_err_inv_cov_time_var,
X_feat_abs_recon_err,
abs_err_count_feat_var,
abs_err_mean_feat_var,
abs_err_cov_feat_var,
... | [
"def",
"calculate_error_distribution_statistics_training",
"(",
"cur_batch_size",
",",
"X_time_abs_recon_err",
",",
"abs_err_count_time_var",
",",
"abs_err_mean_time_var",
",",
"abs_err_cov_time_var",
",",
"abs_err_inv_cov_time_var",
",",
"X_feat_abs_recon_err",
",",
"abs_err_count... | [
472,
0
] | [
596,
23
] | python | da | ['da', 'la', 'en'] | False |
XFrameOptionsMiddleware.get_xframe_options_value | (self, request, response) |
Get the value to set for the X_FRAME_OPTIONS header. Use the value from
the X_FRAME_OPTIONS setting, or 'DENY' if not set.
This method can be overridden if needed, allowing it to vary based on
the request or response.
|
Get the value to set for the X_FRAME_OPTIONS header. Use the value from
the X_FRAME_OPTIONS setting, or 'DENY' if not set. | def get_xframe_options_value(self, request, response):
"""
Get the value to set for the X_FRAME_OPTIONS header. Use the value from
the X_FRAME_OPTIONS setting, or 'DENY' if not set.
This method can be overridden if needed, allowing it to vary based on
the request or response.
... | [
"def",
"get_xframe_options_value",
"(",
"self",
",",
"request",
",",
"response",
")",
":",
"return",
"getattr",
"(",
"settings",
",",
"'X_FRAME_OPTIONS'",
",",
"'DENY'",
")",
".",
"upper",
"(",
")"
] | [
38,
4
] | [
46,
67
] | python | en | ['en', 'error', 'th'] | False |
_parse_arguments | (argv) | Parses command-line arguments. | Parses command-line arguments. | def _parse_arguments(argv):
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
'--game',
help='Which open ai gym game to play',
type=str,
default='CartPole-v0')
parser.add_argument(
'--episodes',
help='The number o... | [
"def",
"_parse_arguments",
"(",
"argv",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--game'",
",",
"help",
"=",
"'Which open ai gym game to play'",
",",
"type",
"=",
"str",
",",
"default",
"=",
... | [
33,
0
] | [
94,
40
] | python | en | ['en', 'fr', 'en'] | True |
_run | (game, network_params, memory_params, explore_decay, ops) | Sets up and runs the gaming simulation.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
args: The arguments from the command line parsed by_parse_arguments.
| Sets up and runs the gaming simulation. | def _run(game, network_params, memory_params, explore_decay, ops):
"""Sets up and runs the gaming simulation.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
args: The argum... | [
"def",
"_run",
"(",
"game",
",",
"network_params",
",",
"memory_params",
",",
"explore_decay",
",",
"ops",
")",
":",
"# Setup TensorBoard Writer.",
"trial_id",
"=",
"json",
".",
"loads",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'TF_CONFIG'",
",",
"'{}'",... | [
97,
0
] | [
162,
57
] | python | en | ['en', 'fil', 'en'] | True |
_play | (agent, env, training, recorder=None) | Plays through one episode of the game.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
agent: The actor learning to play in the given environment.
env: The environment for... | Plays through one episode of the game. | def _play(agent, env, training, recorder=None):
"""Plays through one episode of the game.
Initializes TensorFlow, the training agent, and the game environment.
The agent plays the game from the starting state for a number of
episodes set by the user.
Args:
agent: The actor learning to play i... | [
"def",
"_play",
"(",
"agent",
",",
"env",
",",
"training",
",",
"recorder",
"=",
"None",
")",
":",
"episode_reward",
"=",
"0",
"# The total reward for an episode.",
"state",
"=",
"env",
".",
"reset",
"(",
")",
"# Set up Environment and get start state.",
"done",
... | [
165,
0
] | [
197,
25
] | python | en | ['en', 'en', 'en'] | True |
_create_agent | (env, network_params, memory_params, explore_decay) | Creates a Reinforcement Learning agent.
Args:
env: The environment for the agent to act in.
args: The arguments from the command line parsed by_parse_arguments.
Returns:
An RL agent.
| Creates a Reinforcement Learning agent. | def _create_agent(env, network_params, memory_params, explore_decay):
"""Creates a Reinforcement Learning agent.
Args:
env: The environment for the agent to act in.
args: The arguments from the command line parsed by_parse_arguments.
Returns:
An RL agent.
"""
space_shape = env.ob... | [
"def",
"_create_agent",
"(",
"env",
",",
"network_params",
",",
"memory_params",
",",
"explore_decay",
")",
":",
"space_shape",
"=",
"env",
".",
"observation_space",
".",
"shape",
"action_size",
"=",
"env",
".",
"action_space",
".",
"n",
"network",
"=",
"model... | [
200,
0
] | [
215,
67
] | python | en | ['en', 'en', 'en'] | True |
_record_video | (env, agent, output_path) | Records a video of an agent playing a gaming simulation.
Args:
env: The environment for the agent to act in.
agent: An RL agent created by _create_agent.
output_path (str): The directory path of where to save the recording.
| Records a video of an agent playing a gaming simulation. | def _record_video(env, agent, output_path):
"""Records a video of an agent playing a gaming simulation.
Args:
env: The environment for the agent to act in.
agent: An RL agent created by _create_agent.
output_path (str): The directory path of where to save the recording.
"""
video_reco... | [
"def",
"_record_video",
"(",
"env",
",",
"agent",
",",
"output_path",
")",
":",
"video_recorder",
"=",
"VideoRecorder",
"(",
"env",
",",
"RECORDING_NAME",
")",
"_play",
"(",
"agent",
",",
"env",
",",
"False",
",",
"recorder",
"=",
"video_recorder",
")",
"v... | [
218,
0
] | [
237,
49
] | python | en | ['en', 'en', 'en'] | True |
main | () | Parses command line arguments and kicks off the gaming simulation. | Parses command line arguments and kicks off the gaming simulation. | def main():
"""Parses command line arguments and kicks off the gaming simulation."""
args = _parse_arguments(sys.argv[1:])[0]
network_params = (args.learning_rate, args.hidden_neurons)
memory_params = (args.memory_size, args.memory_batch_size, args.gamma)
ops = argparse.Namespace(**{
'job_di... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"_parse_arguments",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"[",
"0",
"]",
"network_params",
"=",
"(",
"args",
".",
"learning_rate",
",",
"args",
".",
"hidden_neurons",
")",
"memory_params",
"=",
"... | [
240,
0
] | [
251,
75
] | python | en | ['en', 'en', 'en'] | True |
parse_requirements | (
filename: str,
session: PipSession,
finder: Optional["PackageFinder"] = None,
options: Optional[optparse.Values] = None,
constraint: bool = False,
) | Parse a requirements file and yield ParsedRequirement instances.
:param filename: Path or url of requirements file.
:param session: PipSession instance.
:param finder: Instance of pip.index.PackageFinder.
:param options: cli options.
:param constraint: If true, parsing a constraint... | Parse a requirements file and yield ParsedRequirement instances. | def parse_requirements(
filename: str,
session: PipSession,
finder: Optional["PackageFinder"] = None,
options: Optional[optparse.Values] = None,
constraint: bool = False,
) -> Iterator[ParsedRequirement]:
"""Parse a requirements file and yield ParsedRequirement instances.
:param filename: ... | [
"def",
"parse_requirements",
"(",
"filename",
":",
"str",
",",
"session",
":",
"PipSession",
",",
"finder",
":",
"Optional",
"[",
"\"PackageFinder\"",
"]",
"=",
"None",
",",
"options",
":",
"Optional",
"[",
"optparse",
".",
"Values",
"]",
"=",
"None",
",",... | [
115,
0
] | [
142,
28
] | python | en | ['en', 'en', 'en'] | True |
preprocess | (content: str) | Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
| Split, filter, and join lines, and return a line iterator | def preprocess(content: str) -> ReqFileLines:
"""Split, filter, and join lines, and return a line iterator
:param content: the content of the requirements file
"""
lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)
lines_enum = join_lines(lines_enum)
lines_enum = ignore_comment... | [
"def",
"preprocess",
"(",
"content",
":",
"str",
")",
"->",
"ReqFileLines",
":",
"lines_enum",
":",
"ReqFileLines",
"=",
"enumerate",
"(",
"content",
".",
"splitlines",
"(",
")",
",",
"start",
"=",
"1",
")",
"lines_enum",
"=",
"join_lines",
"(",
"lines_enu... | [
145,
0
] | [
154,
21
] | python | en | ['en', 'en', 'en'] | True |
handle_line | (
line: ParsedLine,
options: Optional[optparse.Values] = None,
finder: Optional["PackageFinder"] = None,
session: Optional[PipSession] = None,
) | Handle a single parsed requirements line; This can result in
creating/yielding requirements, or updating the finder.
:param line: The parsed line to be processed.
:param options: CLI options.
:param finder: The finder - updated by non-requirement lines.
:param session: The sessi... | Handle a single parsed requirements line; This can result in
creating/yielding requirements, or updating the finder. | def handle_line(
line: ParsedLine,
options: Optional[optparse.Values] = None,
finder: Optional["PackageFinder"] = None,
session: Optional[PipSession] = None,
) -> Optional[ParsedRequirement]:
"""Handle a single parsed requirements line; This can result in
creating/yielding requirements, or updat... | [
"def",
"handle_line",
"(",
"line",
":",
"ParsedLine",
",",
"options",
":",
"Optional",
"[",
"optparse",
".",
"Values",
"]",
"=",
"None",
",",
"finder",
":",
"Optional",
"[",
"\"PackageFinder\"",
"]",
"=",
"None",
",",
"session",
":",
"Optional",
"[",
"Pi... | [
262,
0
] | [
303,
19
] | python | en | ['en', 'en', 'en'] | True |
break_args_options | (line: str) | Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
| Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
| def break_args_options(line: str) -> Tuple[str, str]:
"""Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
"""
tokens = line.split(' ')
args = []
options = tokens[:]... | [
"def",
"break_args_options",
"(",
"line",
":",
"str",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"tokens",
"=",
"line",
".",
"split",
"(",
"' '",
")",
"args",
"=",
"[",
"]",
"options",
"=",
"tokens",
"[",
":",
"]",
"for",
"token",
"in"... | [
392,
0
] | [
406,
44
] | python | en | ['en', 'en', 'en'] | True |
build_parser | () |
Return a parser for parsing requirement lines
|
Return a parser for parsing requirement lines
| def build_parser() -> optparse.OptionParser:
"""
Return a parser for parsing requirement lines
"""
parser = optparse.OptionParser(add_help_option=False)
option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ
for option_factory in option_factories:
option = option_factory()
... | [
"def",
"build_parser",
"(",
")",
"->",
"optparse",
".",
"OptionParser",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"add_help_option",
"=",
"False",
")",
"option_factories",
"=",
"SUPPORTED_OPTIONS",
"+",
"SUPPORTED_OPTIONS_REQ",
"for",
"option_factory... | [
414,
0
] | [
433,
17
] | python | en | ['en', 'error', 'th'] | False |
join_lines | (lines_enum: ReqFileLines) | Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
| Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
| def join_lines(lines_enum: ReqFileLines) -> ReqFileLines:
"""Joins a line ending in '\' with the previous line (except when following
comments). The joined line takes on the index of the first line.
"""
primary_line_number = None
new_line: List[str] = []
for line_number, line in lines_enum:
... | [
"def",
"join_lines",
"(",
"lines_enum",
":",
"ReqFileLines",
")",
"->",
"ReqFileLines",
":",
"primary_line_number",
"=",
"None",
"new_line",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"if",
"not... | [
436,
0
] | [
462,
52
] | python | en | ['en', 'en', 'en'] | True |
ignore_comments | (lines_enum: ReqFileLines) |
Strips comments and filter empty lines.
|
Strips comments and filter empty lines.
| def ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:
"""
Strips comments and filter empty lines.
"""
for line_number, line in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
yield line_number, line | [
"def",
"ignore_comments",
"(",
"lines_enum",
":",
"ReqFileLines",
")",
"->",
"ReqFileLines",
":",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"line",
"=",
"COMMENT_RE",
".",
"sub",
"(",
"''",
",",
"line",
")",
"line",
"=",
"line",
".",
"s... | [
467,
0
] | [
475,
35
] | python | en | ['en', 'error', 'th'] | False |
expand_env_variables | (lines_enum: ReqFileLines) | Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across pl... | Replace all environment variables that can be retrieved via `os.getenv`. | def expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` ar... | [
"def",
"expand_env_variables",
"(",
"lines_enum",
":",
"ReqFileLines",
")",
"->",
"ReqFileLines",
":",
"for",
"line_number",
",",
"line",
"in",
"lines_enum",
":",
"for",
"env_var",
",",
"var_name",
"in",
"ENV_VAR_RE",
".",
"findall",
"(",
"line",
")",
":",
"... | [
478,
0
] | [
502,
31
] | python | en | ['en', 'en', 'en'] | True |
get_file_content | (url: str, session: PipSession) | Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
Respects # -*- coding: declarations on the retrieved files.
:param url: File path or url.
:param session: PipSession instance.
| Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
Respects # -*- coding: declarations on the retrieved files. | def get_file_content(url: str, session: PipSession) -> Tuple[str, str]:
"""Gets the content of a file; it may be a filename, file: URL, or
http: URL. Returns (location, content). Content is unicode.
Respects # -*- coding: declarations on the retrieved files.
:param url: File path or url.
... | [
"def",
"get_file_content",
"(",
"url",
":",
"str",
",",
"session",
":",
"PipSession",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"scheme",
"=",
"get_url_scheme",
"(",
"url",
")",
"# Pip has special support for file:// URLs (LocalFSAdapter).",
"if",
"s... | [
505,
0
] | [
527,
23
] | python | en | ['en', 'en', 'en'] | True |
RequirementsFileParser.parse | (self, filename: str, constraint: bool) | Parse a given file, yielding parsed lines.
| Parse a given file, yielding parsed lines.
| def parse(self, filename: str, constraint: bool) -> Iterator[ParsedLine]:
"""Parse a given file, yielding parsed lines.
"""
yield from self._parse_and_recurse(filename, constraint) | [
"def",
"parse",
"(",
"self",
",",
"filename",
":",
"str",
",",
"constraint",
":",
"bool",
")",
"->",
"Iterator",
"[",
"ParsedLine",
"]",
":",
"yield",
"from",
"self",
".",
"_parse_and_recurse",
"(",
"filename",
",",
"constraint",
")"
] | [
315,
4
] | [
318,
64
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceAsyncClient.__init__ | (
self,
*,
credentials: credentials.Credentials = None,
transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
) | Instantiate the dashboards service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the cl... | Instantiate the dashboards service client. | def __init__(
self,
*,
credentials: credentials.Credentials = None,
transport: Union[str, DashboardsServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
) -> None:
"""Instantiate the dashboards service client.
Args:
credential... | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"credentials",
":",
"credentials",
".",
"Credentials",
"=",
"None",
",",
"transport",
":",
"Union",
"[",
"str",
",",
"DashboardsServiceTransport",
"]",
"=",
"\"grpc_asyncio\"",
",",
"client_options",
":",
"ClientO... | [
59,
4
] | [
98,
9
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceAsyncClient.create_dashboard | (
self,
request: dashboards_service.CreateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Creates a new custom dashboard.
This method requires the ``monitoring.dashboards.create``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.CreateDashboardReque... | r"""Creates a new custom dashboard. | async def create_dashboard(
self,
request: dashboards_service.CreateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Creates a new custom ... | [
"async",
"def",
"create_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"CreateDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",... | [
100,
4
] | [
154,
23
] | python | cy | ['pt', 'cy', 'en'] | False |
DashboardsServiceAsyncClient.list_dashboards | (
self,
request: dashboards_service.ListDashboardsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Lists the existing dashboards.
This method requires the ``monitoring.dashboards.list``
permission on the specified project. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.ListDashboardsRequest`)... | r"""Lists the existing dashboards. | async def list_dashboards(
self,
request: dashboards_service.ListDashboardsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListDashboardsAsyncPager:
r"""Lists the e... | [
"async",
"def",
"list_dashboards",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"ListDashboardsRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
... | [
156,
4
] | [
216,
23
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceAsyncClient.get_dashboard | (
self,
request: dashboards_service.GetDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Fetches a specific dashboard.
This method requires the ``monitoring.dashboards.get``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.GetDashboardRequest`):
... | r"""Fetches a specific dashboard. | async def get_dashboard(
self,
request: dashboards_service.GetDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Fetches a specific dashboar... | [
"async",
"def",
"get_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"GetDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",
"fl... | [
218,
4
] | [
272,
23
] | python | en | ['en', 'en', 'en'] | True |
DashboardsServiceAsyncClient.delete_dashboard | (
self,
request: dashboards_service.DeleteDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Deletes an existing custom dashboard.
This method requires the ``monitoring.dashboards.delete``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboards_service.DeleteDashbo... | r"""Deletes an existing custom dashboard. | async def delete_dashboard(
self,
request: dashboards_service.DeleteDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Deletes an existing custom dashboard... | [
"async",
"def",
"delete_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"DeleteDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",... | [
274,
4
] | [
319,
9
] | python | en | ['en', 'cy', 'en'] | True |
DashboardsServiceAsyncClient.update_dashboard | (
self,
request: dashboards_service.UpdateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) | r"""Replaces an existing custom dashboard with a new definition.
This method requires the ``monitoring.dashboards.update``
permission on the specified dashboard. For more information, see
`Google Cloud IAM <https://cloud.google.com/iam>`__.
Args:
request (:class:`~.dashboar... | r"""Replaces an existing custom dashboard with a new definition. | async def update_dashboard(
self,
request: dashboards_service.UpdateDashboardRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> dashboard.Dashboard:
r"""Replaces an existing ... | [
"async",
"def",
"update_dashboard",
"(",
"self",
",",
"request",
":",
"dashboards_service",
".",
"UpdateDashboardRequest",
"=",
"None",
",",
"*",
",",
"retry",
":",
"retries",
".",
"Retry",
"=",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
":",... | [
321,
4
] | [
377,
23
] | python | en | ['en', 'en', 'en'] | True |
ContactList.search | (self, name) | Return all contacts that contain the search value in their name | Return all contacts that contain the search value in their name | def search(self, name):
"Return all contacts that contain the search value in their name"
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts | [
"def",
"search",
"(",
"self",
",",
"name",
")",
":",
"matching_contacts",
"=",
"[",
"]",
"for",
"contact",
"in",
"self",
":",
"if",
"name",
"in",
"contact",
".",
"name",
":",
"matching_contacts",
".",
"append",
"(",
"contact",
")",
"return",
"matching_co... | [
13,
4
] | [
19,
32
] | python | en | ['en', 'en', 'en'] | True |
Field.clean | (self, value) |
Validate the given value and return its "cleaned" value as an
appropriate Python object. Raise ValidationError for any errors.
|
Validate the given value and return its "cleaned" value as an
appropriate Python object. Raise ValidationError for any errors.
| def clean(self, value):
"""
Validate the given value and return its "cleaned" value as an
appropriate Python object. Raise ValidationError for any errors.
"""
value = self.to_python(value)
self.validate(value)
self.run_validators(value)
return value | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"to_python",
"(",
"value",
")",
"self",
".",
"validate",
"(",
"value",
")",
"self",
".",
"run_validators",
"(",
"value",
")",
"return",
"value"
] | [
143,
4
] | [
151,
20
] | python | en | ['en', 'error', 'th'] | False |
Field.bound_data | (self, data, initial) |
Return the value that should be shown for this field on render of a
bound form, given the submitted POST data for the field and the initial
data, if any.
For most fields, this will simply be data; FileFields need to handle it
a bit differently.
|
Return the value that should be shown for this field on render of a
bound form, given the submitted POST data for the field and the initial
data, if any. | def bound_data(self, data, initial):
"""
Return the value that should be shown for this field on render of a
bound form, given the submitted POST data for the field and the initial
data, if any.
For most fields, this will simply be data; FileFields need to handle it
a bi... | [
"def",
"bound_data",
"(",
"self",
",",
"data",
",",
"initial",
")",
":",
"if",
"self",
".",
"disabled",
":",
"return",
"initial",
"return",
"data"
] | [
153,
4
] | [
164,
19
] | python | en | ['en', 'error', 'th'] | False |
Field.widget_attrs | (self, widget) |
Given a Widget instance (*not* a Widget class), return a dictionary of
any HTML attributes that should be added to the Widget, based on this
Field.
|
Given a Widget instance (*not* a Widget class), return a dictionary of
any HTML attributes that should be added to the Widget, based on this
Field.
| def widget_attrs(self, widget):
"""
Given a Widget instance (*not* a Widget class), return a dictionary of
any HTML attributes that should be added to the Widget, based on this
Field.
"""
return {} | [
"def",
"widget_attrs",
"(",
"self",
",",
"widget",
")",
":",
"return",
"{",
"}"
] | [
166,
4
] | [
172,
17
] | python | en | ['en', 'error', 'th'] | False |
Field.has_changed | (self, initial, data) | Return True if data differs from initial. | Return True if data differs from initial. | def has_changed(self, initial, data):
"""Return True if data differs from initial."""
# Always return False if the field is disabled since self.bound_data
# always uses the initial value in this case.
if self.disabled:
return False
try:
data = self.to_pyth... | [
"def",
"has_changed",
"(",
"self",
",",
"initial",
",",
"data",
")",
":",
"# Always return False if the field is disabled since self.bound_data",
"# always uses the initial value in this case.",
"if",
"self",
".",
"disabled",
":",
"return",
"False",
"try",
":",
"data",
"=... | [
174,
4
] | [
191,
42
] | python | en | ['en', 'en', 'en'] | True |
Field.get_bound_field | (self, form, field_name) |
Return a BoundField instance that will be used when accessing the form
field in a template.
|
Return a BoundField instance that will be used when accessing the form
field in a template.
| def get_bound_field(self, form, field_name):
"""
Return a BoundField instance that will be used when accessing the form
field in a template.
"""
return BoundField(form, self, field_name) | [
"def",
"get_bound_field",
"(",
"self",
",",
"form",
",",
"field_name",
")",
":",
"return",
"BoundField",
"(",
"form",
",",
"self",
",",
"field_name",
")"
] | [
193,
4
] | [
198,
49
] | python | en | ['en', 'error', 'th'] | False |
CharField.to_python | (self, value) | Return a string. | Return a string. | def to_python(self, value):
"""Return a string."""
if value not in self.empty_values:
value = str(value)
if self.strip:
value = value.strip()
if value in self.empty_values:
return self.empty_value
return value | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"not",
"in",
"self",
".",
"empty_values",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"self",
".",
"strip",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"... | [
222,
4
] | [
230,
20
] | python | en | ['en', 'cy', 'en'] | True |
IntegerField.to_python | (self, value) |
Validate that int() can be called on the input. Return the result
of int() or None for empty values.
|
Validate that int() can be called on the input. Return the result
of int() or None for empty values.
| def to_python(self, value):
"""
Validate that int() can be called on the input. Return the result
of int() or None for empty values.
"""
value = super().to_python(value)
if value in self.empty_values:
return None
if self.localize:
value = f... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
")",
".",
"to_python",
"(",
"value",
")",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"self",
".",
"localize",
":",
"value",
"=",
... | [
262,
4
] | [
277,
20
] | python | en | ['en', 'error', 'th'] | False |
FloatField.to_python | (self, value) |
Validate that float() can be called on the input. Return the result
of float() or None for empty values.
|
Validate that float() can be called on the input. Return the result
of float() or None for empty values.
| def to_python(self, value):
"""
Validate that float() can be called on the input. Return the result
of float() or None for empty values.
"""
value = super(IntegerField, self).to_python(value)
if value in self.empty_values:
return None
if self.localize:... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"IntegerField",
",",
"self",
")",
".",
"to_python",
"(",
"value",
")",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"self",
".",
"l... | [
294,
4
] | [
308,
20
] | python | en | ['en', 'error', 'th'] | False |
DecimalField.to_python | (self, value) |
Validate that the input is a decimal number. Return a Decimal
instance or None for empty values. Ensure that there are no more
than max_digits in the number and no more than decimal_places digits
after the decimal point.
|
Validate that the input is a decimal number. Return a Decimal
instance or None for empty values. Ensure that there are no more
than max_digits in the number and no more than decimal_places digits
after the decimal point.
| def to_python(self, value):
"""
Validate that the input is a decimal number. Return a Decimal
instance or None for empty values. Ensure that there are no more
than max_digits in the number and no more than decimal_places digits
after the decimal point.
"""
if valu... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"self",
".",
"localize",
":",
"value",
"=",
"formats",
".",
"sanitize_separators",
"(",
"value",
")",
"value",
"=",
... | [
334,
4
] | [
350,
20
] | python | en | ['en', 'error', 'th'] | False |
DateField.to_python | (self, value) |
Validate that the input can be converted to a date. Return a Python
datetime.date object.
|
Validate that the input can be converted to a date. Return a Python
datetime.date object.
| def to_python(self, value):
"""
Validate that the input can be converted to a date. Return a Python
datetime.date object.
"""
if value in self.empty_values:
return None
if isinstance(value, datetime.datetime):
return value.date()
if isinsta... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"value",
".",
"date",
"(",
")",
... | [
404,
4
] | [
415,
39
] | python | en | ['en', 'error', 'th'] | False |
TimeField.to_python | (self, value) |
Validate that the input can be converted to a time. Return a Python
datetime.time object.
|
Validate that the input can be converted to a time. Return a Python
datetime.time object.
| def to_python(self, value):
"""
Validate that the input can be converted to a time. Return a Python
datetime.time object.
"""
if value in self.empty_values:
return None
if isinstance(value, datetime.time):
return value
return super().to_pyt... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"time",
")",
":",
"return",
"value",
"return",
"super",
"(",
")",
... | [
428,
4
] | [
437,
39
] | python | en | ['en', 'error', 'th'] | False |
DateTimeField.to_python | (self, value) |
Validate that the input can be converted to a datetime. Return a
Python datetime.datetime object.
|
Validate that the input can be converted to a datetime. Return a
Python datetime.datetime object.
| def to_python(self, value):
"""
Validate that the input can be converted to a datetime. Return a
Python datetime.datetime object.
"""
if value in self.empty_values:
return None
if isinstance(value, datetime.datetime):
return from_current_timezone(v... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"datetime",
".",
"datetime",
")",
":",
"return",
"from_current_timezone",
"(",
"value",... | [
461,
4
] | [
479,
44
] | python | en | ['en', 'error', 'th'] | False |
RegexField.__init__ | (self, regex, **kwargs) |
regex can be either a string or a compiled regular expression object.
|
regex can be either a string or a compiled regular expression object.
| def __init__(self, regex, **kwargs):
"""
regex can be either a string or a compiled regular expression object.
"""
kwargs.setdefault('strip', False)
super().__init__(**kwargs)
self._set_regex(regex) | [
"def",
"__init__",
"(",
"self",
",",
"regex",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'strip'",
",",
"False",
")",
"super",
"(",
")",
".",
"__init__",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_set_regex",
"(",
"rege... | [
514,
4
] | [
520,
30
] | python | en | ['en', 'error', 'th'] | False |
ImageField.to_python | (self, data) |
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Pillow supports).
|
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Pillow supports).
| def to_python(self, data):
"""
Check that the file-upload field data contains a valid image (GIF, JPG,
PNG, etc. -- whatever Pillow supports).
"""
f = super().to_python(data)
if f is None:
return None
from PIL import Image
# We need to get a ... | [
"def",
"to_python",
"(",
"self",
",",
"data",
")",
":",
"f",
"=",
"super",
"(",
")",
".",
"to_python",
"(",
"data",
")",
"if",
"f",
"is",
"None",
":",
"return",
"None",
"from",
"PIL",
"import",
"Image",
"# We need to get a file object for Pillow. We might ha... | [
621,
4
] | [
662,
16
] | python | en | ['en', 'error', 'th'] | False |
BooleanField.to_python | (self, value) | Return a Python boolean object. | Return a Python boolean object. | def to_python(self, value):
"""Return a Python boolean object."""
# Explicitly check for the string 'False', which is what a hidden field
# will submit for False. Also check for '0', since this is what
# RadioSelect will provide. Because bool("True") == bool('1') == True,
# we do... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"# Explicitly check for the string 'False', which is what a hidden field",
"# will submit for False. Also check for '0', since this is what",
"# RadioSelect will provide. Because bool(\"True\") == bool('1') == True,",
"# we don't need to... | [
716,
4
] | [
726,
39
] | python | en | ['en', 'cy', 'en'] | True |
NullBooleanField.to_python | (self, value) |
Explicitly check for the string 'True' and 'False', which is what a
hidden field will submit for True and False, for 'true' and 'false',
which are likely to be returned by JavaScript serializations of forms,
and for '1' and '0', which is what a RadioField will submit. Unlike
the... |
Explicitly check for the string 'True' and 'False', which is what a
hidden field will submit for True and False, for 'true' and 'false',
which are likely to be returned by JavaScript serializations of forms,
and for '1' and '0', which is what a RadioField will submit. Unlike
the... | def to_python(self, value):
"""
Explicitly check for the string 'True' and 'False', which is what a
hidden field will submit for True and False, for 'true' and 'false',
which are likely to be returned by JavaScript serializations of forms,
and for '1' and '0', which is what a Rad... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"(",
"True",
",",
"'True'",
",",
"'true'",
",",
"'1'",
")",
":",
"return",
"True",
"elif",
"value",
"in",
"(",
"False",
",",
"'False'",
",",
"'false'",
",",
"'0'",
")",
... | [
747,
4
] | [
761,
23
] | python | en | ['en', 'error', 'th'] | False |
ChoiceField.to_python | (self, value) | Return a string. | Return a string. | def to_python(self, value):
"""Return a string."""
if value in self.empty_values:
return ''
return str(value) | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"''",
"return",
"str",
"(",
"value",
")"
] | [
806,
4
] | [
810,
25
] | python | en | ['en', 'cy', 'en'] | True |
ChoiceField.validate | (self, value) | Validate that the input is in self.choices. | Validate that the input is in self.choices. | def validate(self, value):
"""Validate that the input is in self.choices."""
super().validate(value)
if value and not self.valid_value(value):
raise ValidationError(
self.error_messages['invalid_choice'],
code='invalid_choice',
params={... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
")",
".",
"validate",
"(",
"value",
")",
"if",
"value",
"and",
"not",
"self",
".",
"valid_value",
"(",
"value",
")",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"error_message... | [
812,
4
] | [
820,
13
] | python | en | ['en', 'en', 'en'] | True |
ChoiceField.valid_value | (self, value) | Check to see if the provided value is a valid choice. | Check to see if the provided value is a valid choice. | def valid_value(self, value):
"""Check to see if the provided value is a valid choice."""
text_value = str(value)
for k, v in self.choices:
if isinstance(v, (list, tuple)):
# This is an optgroup, so look inside the group for options
for k2, v2 in v:
... | [
"def",
"valid_value",
"(",
"self",
",",
"value",
")",
":",
"text_value",
"=",
"str",
"(",
"value",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"choices",
":",
"if",
"isinstance",
"(",
"v",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"# This ... | [
822,
4
] | [
834,
20
] | python | en | ['en', 'en', 'en'] | True |
TypedChoiceField._coerce | (self, value) |
Validate that the value can be coerced to the right type (if not empty).
|
Validate that the value can be coerced to the right type (if not empty).
| def _coerce(self, value):
"""
Validate that the value can be coerced to the right type (if not empty).
"""
if value == self.empty_value or value in self.empty_values:
return self.empty_value
try:
value = self.coerce(value)
except (ValueError, TypeE... | [
"def",
"_coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"empty_value",
"or",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"self",
".",
"empty_value",
"try",
":",
"value",
"=",
"self",
".",
"coerce",
"(",
... | [
843,
4
] | [
857,
20
] | python | en | ['en', 'error', 'th'] | False |
MultipleChoiceField.validate | (self, value) | Validate that the input is a list or tuple. | Validate that the input is a list or tuple. | def validate(self, value):
"""Validate that the input is a list or tuple."""
if self.required and not value:
raise ValidationError(self.error_messages['required'], code='required')
# Validate that each value in the value list is in self.choices.
for val in value:
... | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"required",
"and",
"not",
"value",
":",
"raise",
"ValidationError",
"(",
"self",
".",
"error_messages",
"[",
"'required'",
"]",
",",
"code",
"=",
"'required'",
")",
"# Validate that... | [
879,
4
] | [
890,
17
] | python | en | ['en', 'en', 'en'] | True |
TypedMultipleChoiceField._coerce | (self, value) |
Validate that the values are in self.choices and can be coerced to the
right type.
|
Validate that the values are in self.choices and can be coerced to the
right type.
| def _coerce(self, value):
"""
Validate that the values are in self.choices and can be coerced to the
right type.
"""
if value == self.empty_value or value in self.empty_values:
return self.empty_value
new_value = []
for choice in value:
try... | [
"def",
"_coerce",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"empty_value",
"or",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"self",
".",
"empty_value",
"new_value",
"=",
"[",
"]",
"for",
"choice",
"in",
"val... | [
912,
4
] | [
929,
24
] | python | en | ['en', 'error', 'th'] | False |
ComboField.clean | (self, value) |
Validate the given value against all of self.fields, which is a
list of Field instances.
|
Validate the given value against all of self.fields, which is a
list of Field instances.
| def clean(self, value):
"""
Validate the given value against all of self.fields, which is a
list of Field instances.
"""
super().clean(value)
for field in self.fields:
value = field.clean(value)
return value | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"super",
"(",
")",
".",
"clean",
"(",
"value",
")",
"for",
"field",
"in",
"self",
".",
"fields",
":",
"value",
"=",
"field",
".",
"clean",
"(",
"value",
")",
"return",
"value"
] | [
955,
4
] | [
963,
20
] | python | en | ['en', 'error', 'th'] | False |
MultiValueField.clean | (self, value) |
Validate every value in the given list. A value is validated against
the corresponding Field in self.fields.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), clean() would call
DateField.clean(value[0]) and TimeField.clean(value[1]).... |
Validate every value in the given list. A value is validated against
the corresponding Field in self.fields. | def clean(self, value):
"""
Validate every value in the given list. A value is validated against
the corresponding Field in self.fields.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), clean() would call
DateField.clean(value... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"clean_data",
"=",
"[",
"]",
"errors",
"=",
"[",
"]",
"if",
"self",
".",
"disabled",
"and",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"self",
".",
"widget",
".",
"... | [
1011,
4
] | [
1063,
18
] | python | en | ['en', 'error', 'th'] | False |
MultiValueField.compress | (self, data_list) |
Return a single value for the given list of values. The values can be
assumed to be valid.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), this might return a datetime
object created by combining the date and time in data_list.
... |
Return a single value for the given list of values. The values can be
assumed to be valid. | def compress(self, data_list):
"""
Return a single value for the given list of values. The values can be
assumed to be valid.
For example, if this MultiValueField was instantiated with
fields=(DateField(), TimeField()), this might return a datetime
object created by comb... | [
"def",
"compress",
"(",
"self",
",",
"data_list",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Subclasses must implement this method.'",
")"
] | [
1065,
4
] | [
1074,
75
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus.__init__ | (self, train_file=None, test_file=None, output_file=None, factors=10, learn_rate=0.01, epochs=10,
delta=0.015, init_mean=0.1, init_stdev=0.1, bias_learn_rate=0.005, delta_bias=0.002,
stop_criteria=0.009, sep='\t', output_sep='\t', random_seed=None, update_delta=False) |
SVD++ for rating prediction
The SVD++ algorithm, an extension of SVD taking into account implicit ratings. Just as for SVD, the parameters
are learned using a SGD on the regularized squared error objective.
Usage::
>> SVDPlusPlus(train, test).compute()
:param tra... |
SVD++ for rating prediction | def __init__(self, train_file=None, test_file=None, output_file=None, factors=10, learn_rate=0.01, epochs=10,
delta=0.015, init_mean=0.1, init_stdev=0.1, bias_learn_rate=0.005, delta_bias=0.002,
stop_criteria=0.009, sep='\t', output_sep='\t', random_seed=None, update_delta=False):
... | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
"=",
"None",
",",
"test_file",
"=",
"None",
",",
"output_file",
"=",
"None",
",",
"factors",
"=",
"10",
",",
"learn_rate",
"=",
"0.01",
",",
"epochs",
"=",
"10",
",",
"delta",
"=",
"0.015",
",",
"ini... | [
23,
4
] | [
97,
41
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus.init_model | (self) |
Method to treat and initialize the model. . Extends init_model from MatrixFactorization
|
Method to treat and initialize the model. . Extends init_model from MatrixFactorization | def init_model(self):
"""
Method to treat and initialize the model. . Extends init_model from MatrixFactorization
"""
super(SVDPlusPlus, self).init_model()
self.n_u = {}
self.items_id_seen_by_user = {}
for user in self.train_set['users']:
for item ... | [
"def",
"init_model",
"(",
"self",
")",
":",
"super",
"(",
"SVDPlusPlus",
",",
"self",
")",
".",
"init_model",
"(",
")",
"self",
".",
"n_u",
"=",
"{",
"}",
"self",
".",
"items_id_seen_by_user",
"=",
"{",
"}",
"for",
"user",
"in",
"self",
".",
"train_s... | [
99,
4
] | [
114,
107
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus.fit | (self) |
This method performs iterations of stochastic gradient ascent over the training data.
|
This method performs iterations of stochastic gradient ascent over the training data. | def fit(self):
"""
This method performs iterations of stochastic gradient ascent over the training data.
"""
rmse_old = .0
for epoch in range(self.epochs):
error_final = .0
for user, item, feedback in self.feedback_triples:
pu = self.p[u... | [
"def",
"fit",
"(",
"self",
")",
":",
"rmse_old",
"=",
".0",
"for",
"epoch",
"in",
"range",
"(",
"self",
".",
"epochs",
")",
":",
"error_final",
"=",
".0",
"for",
"user",
",",
"item",
",",
"feedback",
"in",
"self",
".",
"feedback_triples",
":",
"pu",
... | [
116,
4
] | [
161,
35
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus.create_factors | (self) |
This method extends create_factors from Matrix Factorization, adding y factors
|
This method extends create_factors from Matrix Factorization, adding y factors | def create_factors(self):
"""
This method extends create_factors from Matrix Factorization, adding y factors
"""
super(SVDPlusPlus, self).create_factors()
self.y = np.random.normal(self.init_mean, self.init_stdev, (len(self.items), self.factors)) | [
"def",
"create_factors",
"(",
"self",
")",
":",
"super",
"(",
"SVDPlusPlus",
",",
"self",
")",
".",
"create_factors",
"(",
")",
"self",
".",
"y",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"self",
".",
"init_mean",
",",
"self",
".",
"init_stdev",
... | [
163,
4
] | [
170,
99
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus._predict_svd_plus_plus_score | (self, u, i, pu, cond=True) |
:param u: User ID (from self.items)
:type u: int
:param i: Item ID (from self.items)
:type i: int
:param pu: User updated vector (pu * y)
:type pu: list or np.array
:param cond: Use max and min values of train set to limit score
:type cond: bool, defa... | def _predict_svd_plus_plus_score(self, u, i, pu, cond=True):
"""
:param u: User ID (from self.items)
:type u: int
:param i: Item ID (from self.items)
:type i: int
:param pu: User updated vector (pu * y)
:type pu: list or np.array
:param cond: Use max a... | [
"def",
"_predict_svd_plus_plus_score",
"(",
"self",
",",
"u",
",",
"i",
",",
"pu",
",",
"cond",
"=",
"True",
")",
":",
"rui",
"=",
"self",
".",
"train_set",
"[",
"\"mean_value\"",
"]",
"+",
"self",
".",
"bu",
"[",
"u",
"]",
"+",
"self",
".",
"bi",
... | [
172,
4
] | [
198,
18
] | python | en | ['en', 'error', 'th'] | False | |
SVDPlusPlus.y_sum_rows | (self, user) |
Incorporating implicit feedback in the SVD: Sum (j E N(u)) Yj
:param user: User ID
:type user: int
:return: Sum of y vectors for seen items of user
|
Incorporating implicit feedback in the SVD: Sum (j E N(u)) Yj | def y_sum_rows(self, user):
"""
Incorporating implicit feedback in the SVD: Sum (j E N(u)) Yj
:param user: User ID
:type user: int
:return: Sum of y vectors for seen items of user
"""
sum_imp = np.zeros(self.factors)
for ui in self.items_id_seen_by_use... | [
"def",
"y_sum_rows",
"(",
"self",
",",
"user",
")",
":",
"sum_imp",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"factors",
")",
"for",
"ui",
"in",
"self",
".",
"items_id_seen_by_user",
"[",
"user",
"]",
":",
"sum_imp",
"+=",
"self",
".",
"y",
"[",
"... | [
200,
4
] | [
214,
39
] | python | en | ['en', 'error', 'th'] | False |
SVDPlusPlus.predict | (self) |
This method computes a final rating for unknown pairs (user, item)
|
This method computes a final rating for unknown pairs (user, item) | def predict(self):
"""
This method computes a final rating for unknown pairs (user, item)
"""
if self.test_file is not None:
for user in self.test_set['users']:
pu = self.p[self.user_to_user_id[user]] + self.y_sum_rows(self.user_to_user_id[user])
... | [
"def",
"predict",
"(",
"self",
")",
":",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"for",
"user",
"in",
"self",
".",
"test_set",
"[",
"'users'",
"]",
":",
"pu",
"=",
"self",
".",
"p",
"[",
"self",
".",
"user_to_user_id",
"[",
"user"... | [
216,
4
] | [
231,
32
] | python | en | ['en', 'error', 'th'] | False |
reset_format_cache | () | Clear any cached formats.
This method is provided primarily for testing purposes,
so that the effects of cached formats can be removed.
| Clear any cached formats. | def reset_format_cache():
"""Clear any cached formats.
This method is provided primarily for testing purposes,
so that the effects of cached formats can be removed.
"""
global _format_cache, _format_modules_cache
_format_cache = {}
_format_modules_cache = {} | [
"def",
"reset_format_cache",
"(",
")",
":",
"global",
"_format_cache",
",",
"_format_modules_cache",
"_format_cache",
"=",
"{",
"}",
"_format_modules_cache",
"=",
"{",
"}"
] | [
48,
0
] | [
56,
30
] | python | en | ['en', 'en', 'en'] | True |
iter_format_modules | (lang, format_module_path=None) | Find format modules. | Find format modules. | def iter_format_modules(lang, format_module_path=None):
"""Find format modules."""
if not check_for_language(lang):
return
if format_module_path is None:
format_module_path = settings.FORMAT_MODULE_PATH
format_locations = []
if format_module_path:
if isinstance(format_modul... | [
"def",
"iter_format_modules",
"(",
"lang",
",",
"format_module_path",
"=",
"None",
")",
":",
"if",
"not",
"check_for_language",
"(",
"lang",
")",
":",
"return",
"if",
"format_module_path",
"is",
"None",
":",
"format_module_path",
"=",
"settings",
".",
"FORMAT_MO... | [
59,
0
] | [
83,
20
] | python | en | ['en', 'co', 'en'] | True |
get_format_modules | (lang=None, reverse=False) | Return a list of the format modules found. | Return a list of the format modules found. | def get_format_modules(lang=None, reverse=False):
"""Return a list of the format modules found."""
if lang is None:
lang = get_language()
if lang not in _format_modules_cache:
_format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH))
modules = _format_mod... | [
"def",
"get_format_modules",
"(",
"lang",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"lang",
"is",
"None",
":",
"lang",
"=",
"get_language",
"(",
")",
"if",
"lang",
"not",
"in",
"_format_modules_cache",
":",
"_format_modules_cache",
"[",
"l... | [
86,
0
] | [
95,
18
] | python | en | ['en', 'en', 'en'] | True |
get_format | (format_type, lang=None, use_l10n=None) |
For a specific format type, return the format for the current
language (locale). Default to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings... |
For a specific format type, return the format for the current
language (locale). Default to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'. | def get_format(format_type, lang=None, use_l10n=None):
"""
For a specific format type, return the format for the current
language (locale). Default to the format in the settings.
format_type is the name of the format, e.g. 'DATE_FORMAT'.
If use_l10n is provided and is not None, it forces the value ... | [
"def",
"get_format",
"(",
"format_type",
",",
"lang",
"=",
"None",
",",
"use_l10n",
"=",
"None",
")",
":",
"use_l10n",
"=",
"use_l10n",
"or",
"(",
"use_l10n",
"is",
"None",
"and",
"settings",
".",
"USE_L10N",
")",
"if",
"use_l10n",
"and",
"lang",
"is",
... | [
98,
0
] | [
137,
14
] | python | en | ['en', 'error', 'th'] | False |
date_format | (value, format=None, use_l10n=None) |
Format a datetime.date or datetime.datetime object using a
localizable format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Format a datetime.date or datetime.datetime object using a
localizable format. | def date_format(value, format=None, use_l10n=None):
"""
Format a datetime.date or datetime.datetime object using a
localizable format.
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateforma... | [
"def",
"date_format",
"(",
"value",
",",
"format",
"=",
"None",
",",
"use_l10n",
"=",
"None",
")",
":",
"return",
"dateformat",
".",
"format",
"(",
"value",
",",
"get_format",
"(",
"format",
"or",
"'DATE_FORMAT'",
",",
"use_l10n",
"=",
"use_l10n",
")",
"... | [
143,
0
] | [
151,
91
] | python | en | ['en', 'error', 'th'] | False |
time_format | (value, format=None, use_l10n=None) |
Format a datetime.time object using a localizable format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Format a datetime.time object using a localizable format. | def time_format(value, format=None, use_l10n=None):
"""
Format a datetime.time object using a localizable format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
return dateformat.time_format(value, get_format... | [
"def",
"time_format",
"(",
"value",
",",
"format",
"=",
"None",
",",
"use_l10n",
"=",
"None",
")",
":",
"return",
"dateformat",
".",
"time_format",
"(",
"value",
",",
"get_format",
"(",
"format",
"or",
"'TIME_FORMAT'",
",",
"use_l10n",
"=",
"use_l10n",
")"... | [
154,
0
] | [
161,
96
] | python | en | ['en', 'error', 'th'] | False |
number_format | (value, decimal_pos=None, use_l10n=None, force_grouping=False) |
Format a numeric value using localization settings.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Format a numeric value using localization settings. | def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False):
"""
Format a numeric value using localization settings.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
if use_l10n or (use_l10n... | [
"def",
"number_format",
"(",
"value",
",",
"decimal_pos",
"=",
"None",
",",
"use_l10n",
"=",
"None",
",",
"force_grouping",
"=",
"False",
")",
":",
"if",
"use_l10n",
"or",
"(",
"use_l10n",
"is",
"None",
"and",
"settings",
".",
"USE_L10N",
")",
":",
"lang... | [
164,
0
] | [
183,
5
] | python | en | ['en', 'error', 'th'] | False |
localize | (value, use_l10n=None) |
Check if value is a localizable type (date, number...) and return it
formatted as a string using current locale format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
|
Check if value is a localizable type (date, number...) and return it
formatted as a string using current locale format. | def localize(value, use_l10n=None):
"""
Check if value is a localizable type (date, number...) and return it
formatted as a string using current locale format.
If use_l10n is provided and is not None, it forces the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
... | [
"def",
"localize",
"(",
"value",
",",
"use_l10n",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# Handle strings first for performance reasons.",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
... | [
186,
0
] | [
208,
16
] | python | en | ['en', 'error', 'th'] | False |
localize_input | (value, default=None) |
Check if an input value is a localizable type and return it
formatted with the appropriate formatting string of the current locale.
|
Check if an input value is a localizable type and return it
formatted with the appropriate formatting string of the current locale.
| def localize_input(value, default=None):
"""
Check if an input value is a localizable type and return it
formatted with the appropriate formatting string of the current locale.
"""
if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(va... | [
"def",
"localize_input",
"(",
"value",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# Handle strings first for performance reasons.",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"bool",
")",
":... | [
211,
0
] | [
233,
16
] | python | en | ['en', 'error', 'th'] | False |
sanitize_separators | (value) |
Sanitize a value according to the current decimal and
thousand separator setting. Used with form field input.
|
Sanitize a value according to the current decimal and
thousand separator setting. Used with form field input.
| def sanitize_separators(value):
"""
Sanitize a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
if isinstance(value, str):
parts = []
decimal_separator = get_format('DECIMAL_SEPARATOR')
if decimal_separator in value:
... | [
"def",
"sanitize_separators",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"parts",
"=",
"[",
"]",
"decimal_separator",
"=",
"get_format",
"(",
"'DECIMAL_SEPARATOR'",
")",
"if",
"decimal_separator",
"in",
"value",
":",
"val... | [
236,
0
] | [
258,
16
] | python | en | ['en', 'error', 'th'] | False |
jsonp_loader | (url, prefix_regex=r'^(.*\()', suffix_regex=r'(\);)$', sub_d=None, sub_by='') | jsonp_loader is to request (JSON) data from a server in a different domain (JSONP)
and covert to python readable data.
1. url is the url (https) where data is located
2. "prefix_regex" and "suffix_regex" are regex patterns used to
remove JSONP specific prefix and suffix, such as callback header: ... | jsonp_loader is to request (JSON) data from a server in a different domain (JSONP)
and covert to python readable data.
1. url is the url (https) where data is located
2. "prefix_regex" and "suffix_regex" are regex patterns used to
remove JSONP specific prefix and suffix, such as callback header: ... | def jsonp_loader(url, prefix_regex=r'^(.*\()', suffix_regex=r'(\);)$', sub_d=None, sub_by=''):
"""jsonp_loader is to request (JSON) data from a server in a different domain (JSONP)
and covert to python readable data.
1. url is the url (https) where data is located
2. "prefix_regex" and "suffix_regex" ... | [
"def",
"jsonp_loader",
"(",
"url",
",",
"prefix_regex",
"=",
"r'^(.*\\()'",
",",
"suffix_regex",
"=",
"r'(\\);)$'",
",",
"sub_d",
"=",
"None",
",",
"sub_by",
"=",
"''",
")",
":",
"hdr",
"=",
"{",
"'User-Agent'",
":",
"'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/53... | [
13,
0
] | [
36,
64
] | python | en | ['en', 'en', 'en'] | True |
JSONPDecoder.decode | (self, json_string) |
json_string is basicly string that you give to json.loads method
|
json_string is basicly string that you give to json.loads method
| def decode(self, json_string):
"""
json_string is basicly string that you give to json.loads method
"""
default_obj = super(JSONPDecoder, self).decode(json_string)
return list(self._iterdecode(default_obj))[0] | [
"def",
"decode",
"(",
"self",
",",
"json_string",
")",
":",
"default_obj",
"=",
"super",
"(",
"JSONPDecoder",
",",
"self",
")",
".",
"decode",
"(",
"json_string",
")",
"return",
"list",
"(",
"self",
".",
"_iterdecode",
"(",
"default_obj",
")",
")",
"[",
... | [
58,
4
] | [
65,
53
] | python | en | ['en', 'error', 'th'] | False |
JSONPDecoder.is_js_date_utc | (json) | Check if the string contains Date.UTC function
and return match group(s) if there is
| Check if the string contains Date.UTC function
and return match group(s) if there is
| def is_js_date_utc(json):
"""Check if the string contains Date.UTC function
and return match group(s) if there is
"""
JS_date_utc_pattern = r'Date\.UTC\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\)'
re_date = re.compile(JS_date_utc_pattern, re.M)
... | [
"def",
"is_js_date_utc",
"(",
"json",
")",
":",
"JS_date_utc_pattern",
"=",
"r'Date\\.UTC\\(([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?\\)'",
"re_date",
"=",
"re",
".",
"compile",
"(",
"JS_date_utc_pattern",
",",
"re",
".",
"M",
")",
"if",
"re_date",
".",
... | [
98,
4
] | [
109,
24
] | python | en | ['en', 'en', 'en'] | True |
JSONPDecoder.json2datetime | (json) | Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed.
| Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed.
| def json2datetime(json):
"""Convert JSON representation to date or datetime object depending on
the argument count. Requires UTC datetime representation.
Raises ValueError if the string cannot be parsed.
"""
json_m = re.search(r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9... | [
"def",
"json2datetime",
"(",
"json",
")",
":",
"json_m",
"=",
"re",
".",
"search",
"(",
"r'([0-9]+,[0-9]+,[0-9]+)(,[0-9]+,[0-9]+,[0-9]+)?(,[0-9]+)?'",
",",
"json",
")",
"args",
"=",
"json_m",
".",
"group",
"(",
"0",
")",
".",
"split",
"(",
"','",
")",
"try",... | [
112,
4
] | [
135,
64
] | python | en | ['en', 'en', 'en'] | True |
__deepcopy__ | (self, memo) | Don't populate the QuerySet's cache. | Don't populate the QuerySet's cache. | def __deepcopy__(self, memo):
"""Don't populate the QuerySet's cache."""
obj = self.__class__()
for k, v in self.__dict__.items():
if k == '_result_cache':
obj.__dict__[k] = None
else:
obj.__dict__[k] = copy.deepcopy(v, memo)
return... | [
"def",
"__deepcopy__",
"(",
"self",
",",
"memo",
")",
":",
"obj",
"=",
"self",
".",
"__class__",
"(",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'_result_cache'",
":",
"obj",
".",
"__d... | [
220,
4
] | [
228,
18
] | python | en | ['en', 'en', 'en'] | True |
__iter__ | (self) |
The queryset iterator protocol uses three nested iterators in the
default case:
1. sql.compiler.execute_sql()
- Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)
using cursor.fetchmany(). This part is responsible for
doing some col... |
The queryset iterator protocol uses three nested iterators in the
default case:
1. sql.compiler.execute_sql()
- Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)
using cursor.fetchmany(). This part is responsible for
doing some col... | def __iter__(self):
"""
The queryset iterator protocol uses three nested iterators in the
default case:
1. sql.compiler.execute_sql()
- Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)
using cursor.fetchmany(). This part is responsible for
... | [
"def",
"__iter__",
"(",
"self",
")",
":",
"self",
".",
"_fetch_all",
"(",
")",
"return",
"iter",
"(",
"self",
".",
"_result_cache",
")"
] | [
264,
4
] | [
280,
39
] | python | en | ['en', 'error', 'th'] | False |
__getitem__ | (self, k) | Retrieve an item or slice from the set of results. | Retrieve an item or slice from the set of results. | def __getitem__(self, k):
"""Retrieve an item or slice from the set of results."""
if not isinstance(k, (int, slice)):
raise TypeError(
'QuerySet indices must be integers or slices, not %s.'
% type(k).__name__
)
assert ((not isinstance(k, s... | [
"def",
"__getitem__",
"(",
"self",
",",
"k",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"(",
"int",
",",
"slice",
")",
")",
":",
"raise",
"TypeError",
"(",
"'QuerySet indices must be integers or slices, not %s.'",
"%",
"type",
"(",
"k",
")",
".",
... | [
286,
4
] | [
317,
34
] | python | en | ['en', 'en', 'en'] | True |
iterator | (self, chunk_size=2000) |
An iterator over the results from applying this QuerySet to the
database.
|
An iterator over the results from applying this QuerySet to the
database.
| def iterator(self, chunk_size=2000):
"""
An iterator over the results from applying this QuerySet to the
database.
"""
if chunk_size <= 0:
raise ValueError('Chunk size must be strictly positive.')
use_chunked_fetch = not connections[self.db].settings_dict.get(... | [
"def",
"iterator",
"(",
"self",
",",
"chunk_size",
"=",
"2000",
")",
":",
"if",
"chunk_size",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"'Chunk size must be strictly positive.'",
")",
"use_chunked_fetch",
"=",
"not",
"connections",
"[",
"self",
".",
"db",
"]... | [
354,
4
] | [
362,
60
] | python | en | ['en', 'error', 'th'] | False |
decide_user_install | (
use_user_site: Optional[bool],
prefix_path: Optional[str] = None,
target_dir: Optional[str] = None,
root_path: Optional[str] = None,
isolated_mode: bool = False,
) | Determine whether to do a user install based on the input options.
If use_user_site is False, no additional checks are done.
If use_user_site is True, it is checked for compatibility with other
options.
If use_user_site is None, the default behaviour depends on the environment,
which is provided by... | Determine whether to do a user install based on the input options. | def decide_user_install(
use_user_site: Optional[bool],
prefix_path: Optional[str] = None,
target_dir: Optional[str] = None,
root_path: Optional[str] = None,
isolated_mode: bool = False,
) -> bool:
"""Determine whether to do a user install based on the input options.
If use_user_site is Fal... | [
"def",
"decide_user_install",
"(",
"use_user_site",
":",
"Optional",
"[",
"bool",
"]",
",",
"prefix_path",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"target_dir",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"root_path",
":",
"Optional",
... | [
601,
0
] | [
657,
15
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.