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
set_urlconf
(urlconf_name)
Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default.
Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default.
def set_urlconf(urlconf_name): """ Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default. """ if urlconf_name: _urlconfs.value = urlconf_name else: if hasattr(_urlconfs, "value"): del _urlconfs.valu...
[ "def", "set_urlconf", "(", "urlconf_name", ")", ":", "if", "urlconf_name", ":", "_urlconfs", ".", "value", "=", "urlconf_name", "else", ":", "if", "hasattr", "(", "_urlconfs", ",", "\"value\"", ")", ":", "del", "_urlconfs", ".", "value" ]
[ 618, 0 ]
[ 627, 31 ]
python
en
['en', 'error', 'th']
False
get_urlconf
(default=None)
Returns the root URLconf to use for the current thread if it has been changed from the default one.
Returns the root URLconf to use for the current thread if it has been changed from the default one.
def get_urlconf(default=None): """ Returns the root URLconf to use for the current thread if it has been changed from the default one. """ return getattr(_urlconfs, "value", default)
[ "def", "get_urlconf", "(", "default", "=", "None", ")", ":", "return", "getattr", "(", "_urlconfs", ",", "\"value\"", ",", "default", ")" ]
[ 630, 0 ]
[ 635, 47 ]
python
en
['en', 'error', 'th']
False
is_valid_path
(path, urlconf=None)
Returns True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks.
Returns True if the given path resolves against the default URL resolver, False otherwise.
def is_valid_path(path, urlconf=None): """ Returns True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: reso...
[ "def", "is_valid_path", "(", "path", ",", "urlconf", "=", "None", ")", ":", "try", ":", "resolve", "(", "path", ",", "urlconf", ")", "return", "True", "except", "Resolver404", ":", "return", "False" ]
[ 638, 0 ]
[ 650, 20 ]
python
en
['en', 'error', 'th']
False
LocaleRegexProvider.regex
(self)
Returns a compiled regular expression, depending upon the activated language-code.
Returns a compiled regular expression, depending upon the activated language-code.
def regex(self): """ Returns a compiled regular expression, depending upon the activated language-code. """ language_code = get_language() if language_code not in self._regex_dict: if isinstance(self._regex, six.string_types): regex = self._reg...
[ "def", "regex", "(", "self", ")", ":", "language_code", "=", "get_language", "(", ")", "if", "language_code", "not", "in", "self", ".", "_regex_dict", ":", "if", "isinstance", "(", "self", ".", "_regex", ",", "six", ".", "string_types", ")", ":", "regex"...
[ 179, 4 ]
[ 198, 46 ]
python
en
['en', 'error', 'th']
False
RegexURLPattern.add_prefix
(self, prefix)
Adds the prefix string to a string-based callback.
Adds the prefix string to a string-based callback.
def add_prefix(self, prefix): """ Adds the prefix string to a string-based callback. """ if not prefix or not hasattr(self, '_callback_str'): return self._callback_str = prefix + '.' + self._callback_str
[ "def", "add_prefix", "(", "self", ",", "prefix", ")", ":", "if", "not", "prefix", "or", "not", "hasattr", "(", "self", ",", "'_callback_str'", ")", ":", "return", "self", ".", "_callback_str", "=", "prefix", "+", "'.'", "+", "self", ".", "_callback_str" ...
[ 218, 4 ]
[ 224, 62 ]
python
en
['en', 'error', 'th']
False
LineString.__init__
(self, *args, **kwargs)
Initialize on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object. Examples: ls = LineString((1, 1), (2, 2)) ls = LineString([(1, 1), (2, 2)]) ...
Initialize on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object.
def __init__(self, *args, **kwargs): """ Initialize on the given sequence -- may take lists, tuples, NumPy arrays of X,Y pairs, or Point objects. If Point objects are used, ownership is _not_ transferred to the LineString object. Examples: ls = LineString((1, 1), (2, 2...
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# If only one argument provided, set the coords array appropriately", "if", "len", "(", "args", ")", "==", "1", ":", "coords", "=", "args", "[", "0", "]", "else", ":", "c...
[ 13, 4 ]
[ 89, 60 ]
python
en
['en', 'error', 'th']
False
LineString.__iter__
(self)
Allow iteration over this LineString.
Allow iteration over this LineString.
def __iter__(self): "Allow iteration over this LineString." return iter(self._cs)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iter", "(", "self", ".", "_cs", ")" ]
[ 91, 4 ]
[ 93, 29 ]
python
en
['en', 'en', 'en']
True
LineString.__len__
(self)
Return the number of points in this LineString.
Return the number of points in this LineString.
def __len__(self): "Return the number of points in this LineString." return len(self._cs)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_cs", ")" ]
[ 95, 4 ]
[ 97, 28 ]
python
en
['en', 'en', 'en']
True
LineString.tuple
(self)
Return a tuple version of the geometry from the coordinate sequence.
Return a tuple version of the geometry from the coordinate sequence.
def tuple(self): "Return a tuple version of the geometry from the coordinate sequence." return self._cs.tuple
[ "def", "tuple", "(", "self", ")", ":", "return", "self", ".", "_cs", ".", "tuple" ]
[ 134, 4 ]
[ 136, 29 ]
python
en
['en', 'en', 'en']
True
LineString._listarr
(self, func)
Return a sequence (list) corresponding with the given function. Return a numpy array if possible.
Return a sequence (list) corresponding with the given function. Return a numpy array if possible.
def _listarr(self, func): """ Return a sequence (list) corresponding with the given function. Return a numpy array if possible. """ lst = [func(i) for i in range(len(self))] if numpy: return numpy.array(lst) # ARRRR! else: return lst
[ "def", "_listarr", "(", "self", ",", "func", ")", ":", "lst", "=", "[", "func", "(", "i", ")", "for", "i", "in", "range", "(", "len", "(", "self", ")", ")", "]", "if", "numpy", ":", "return", "numpy", ".", "array", "(", "lst", ")", "# ARRRR!", ...
[ 139, 4 ]
[ 148, 22 ]
python
en
['en', 'error', 'th']
False
LineString.array
(self)
Return a numpy array for the LineString.
Return a numpy array for the LineString.
def array(self): "Return a numpy array for the LineString." return self._listarr(self._cs.__getitem__)
[ "def", "array", "(", "self", ")", ":", "return", "self", ".", "_listarr", "(", "self", ".", "_cs", ".", "__getitem__", ")" ]
[ 151, 4 ]
[ 153, 50 ]
python
en
['en', 'en', 'en']
True
LineString.x
(self)
Return a list or numpy array of the X variable.
Return a list or numpy array of the X variable.
def x(self): "Return a list or numpy array of the X variable." return self._listarr(self._cs.getX)
[ "def", "x", "(", "self", ")", ":", "return", "self", ".", "_listarr", "(", "self", ".", "_cs", ".", "getX", ")" ]
[ 156, 4 ]
[ 158, 43 ]
python
en
['en', 'ga', 'en']
True
LineString.y
(self)
Return a list or numpy array of the Y variable.
Return a list or numpy array of the Y variable.
def y(self): "Return a list or numpy array of the Y variable." return self._listarr(self._cs.getY)
[ "def", "y", "(", "self", ")", ":", "return", "self", ".", "_listarr", "(", "self", ".", "_cs", ".", "getY", ")" ]
[ 161, 4 ]
[ 163, 43 ]
python
en
['en', 'en', 'en']
True
LineString.z
(self)
Return a list or numpy array of the Z variable.
Return a list or numpy array of the Z variable.
def z(self): "Return a list or numpy array of the Z variable." if not self.hasz: return None else: return self._listarr(self._cs.getZ)
[ "def", "z", "(", "self", ")", ":", "if", "not", "self", ".", "hasz", ":", "return", "None", "else", ":", "return", "self", ".", "_listarr", "(", "self", ".", "_cs", ".", "getZ", ")" ]
[ 166, 4 ]
[ 171, 47 ]
python
en
['en', 'ga', 'en']
True
PostGISIntrospection.get_postgis_types
(self)
Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported).
Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported).
def get_postgis_types(self): """ Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported). """ field_types = [ ('geometry', 'GeometryField'), # The value fo...
[ "def", "get_postgis_types", "(", "self", ")", ":", "field_types", "=", "[", "(", "'geometry'", ",", "'GeometryField'", ")", ",", "# The value for the geography type is actually a tuple", "# to pass in the `geography=True` keyword to the field", "# definition.", "(", "'geography...
[ 21, 4 ]
[ 50, 28 ]
python
en
['en', 'error', 'th']
False
PostGISIntrospection.get_geometry_type
(self, table_name, geo_col)
The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type,
The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type,
def get_geometry_type(self, table_name, geo_col): """ The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to det...
[ "def", "get_geometry_type", "(", "self", ",", "table_name", ",", "geo_col", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "try", ":", "# First seeing if this geometry column is in the `geometry_columns`", "cursor", ".", "...
[ 63, 4 ]
[ 107, 39 ]
python
en
['en', 'error', 'th']
False
compile_keys
()
Build a dictionary to quickly lookup keys. Note: This function searches 'override:{key}' before '{key}' names.
Build a dictionary to quickly lookup keys.
def compile_keys(): """ Build a dictionary to quickly lookup keys. Note: This function searches 'override:{key}' before '{key}' names. """ active_parameter_set = _init["active_parameter_set"] builtin_layer = _init["all_configs"][0]["config"] _init["compiled_keys"] = {} for key ...
[ "def", "compile_keys", "(", ")", ":", "active_parameter_set", "=", "_init", "[", "\"active_parameter_set\"", "]", "builtin_layer", "=", "_init", "[", "\"all_configs\"", "]", "[", "0", "]", "[", "\"config\"", "]", "_init", "[", "\"compiled_keys\"", "]", "=", "{...
[ 276, 0 ]
[ 337, 39 ]
python
en
['en', 'en', 'en']
True
subclass_exception
(name, bases, module, attached_to)
Create exception subclass. Used by ModelBase below. The exception is created in a way that allows it to be pickled, assuming that the returned exception class will be added as an attribute to the 'attached_to' class.
Create exception subclass. Used by ModelBase below.
def subclass_exception(name, bases, module, attached_to): """ Create exception subclass. Used by ModelBase below. The exception is created in a way that allows it to be pickled, assuming that the returned exception class will be added as an attribute to the 'attached_to' class. """ return t...
[ "def", "subclass_exception", "(", "name", ",", "bases", ",", "module", ",", "attached_to", ")", ":", "return", "type", "(", "name", ",", "bases", ",", "{", "'__module__'", ":", "module", ",", "'__qualname__'", ":", "'%s.%s'", "%", "(", "attached_to", ".", ...
[ 51, 0 ]
[ 62, 6 ]
python
en
['en', 'error', 'th']
False
model_unpickle
(model_id)
Used to unpickle Model subclasses with deferred fields.
Used to unpickle Model subclasses with deferred fields.
def model_unpickle(model_id): """Used to unpickle Model subclasses with deferred fields.""" if isinstance(model_id, tuple): model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id return model.__new__(model)
[ "def", "model_unpickle", "(", "model_id", ")", ":", "if", "isinstance", "(", "model_id", ",", "tuple", ")", ":", "model", "=", "apps", ".", "get_model", "(", "*", "model_id", ")", "else", ":", "# Backwards compat - the model was cached directly in earlier versions."...
[ 1901, 0 ]
[ 1908, 31 ]
python
en
['en', 'en', 'en']
True
ModelBase._prepare
(cls)
Create some methods once self._meta has been populated.
Create some methods once self._meta has been populated.
def _prepare(cls): """Create some methods once self._meta has been populated.""" opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = partialmethod(cls._get_next_or_previous_in_order, is_next=True) cls.get_previous_in_order =...
[ "def", "_prepare", "(", "cls", ")", ":", "opts", "=", "cls", ".", "_meta", "opts", ".", "_prepare", "(", "cls", ")", "if", "opts", ".", "order_with_respect_to", ":", "cls", ".", "get_next_in_order", "=", "partialmethod", "(", "cls", ".", "_get_next_or_prev...
[ 328, 4 ]
[ 372, 39 ]
python
en
['en', 'en', 'en']
True
Model.__getstate__
(self)
Hook to allow choosing the attributes to pickle.
Hook to allow choosing the attributes to pickle.
def __getstate__(self): """Hook to allow choosing the attributes to pickle.""" return self.__dict__
[ "def", "__getstate__", "(", "self", ")", ":", "return", "self", ".", "__dict__" ]
[ 543, 4 ]
[ 545, 28 ]
python
en
['en', 'en', 'en']
True
Model.get_deferred_fields
(self)
Return a set containing names of deferred fields for this instance.
Return a set containing names of deferred fields for this instance.
def get_deferred_fields(self): """ Return a set containing names of deferred fields for this instance. """ return { f.attname for f in self._meta.concrete_fields if f.attname not in self.__dict__ }
[ "def", "get_deferred_fields", "(", "self", ")", ":", "return", "{", "f", ".", "attname", "for", "f", "in", "self", ".", "_meta", ".", "concrete_fields", "if", "f", ".", "attname", "not", "in", "self", ".", "__dict__", "}" ]
[ 574, 4 ]
[ 581, 9 ]
python
en
['en', 'error', 'th']
False
Model.refresh_from_db
(self, using=None, fields=None)
Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default. Fields can be used to specify which ...
Reload field values from the database.
def refresh_from_db(self, using=None, fields=None): """ Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will over...
[ "def", "refresh_from_db", "(", "self", ",", "using", "=", "None", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "self", ".", "_prefetched_objects_cache", "=", "{", "}", "else", ":", "prefetched_objects_cache", "=", "getattr", "("...
[ 583, 4 ]
[ 642, 46 ]
python
en
['en', 'error', 'th']
False
Model.serializable_value
(self, field_name)
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value. Used to serialize a field's value (in the serializer, or f...
Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value.
def serializable_value(self, field_name): """ Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value. Used ...
[ "def", "serializable_value", "(", "self", ",", "field_name", ")", ":", "try", ":", "field", "=", "self", ".", "_meta", ".", "get_field", "(", "field_name", ")", "except", "FieldDoesNotExist", ":", "return", "getattr", "(", "self", ",", "field_name", ")", "...
[ 644, 4 ]
[ 659, 43 ]
python
en
['en', 'error', 'th']
False
Model.save
(self, force_insert=False, force_update=False, using=None, update_fields=None)
Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally,...
Save the current instance. Override this in a subclass if you want to control the saving process.
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that ...
[ "def", "save", "(", "self", ",", "force_insert", "=", "False", ",", "force_update", "=", "False", ",", "using", "=", "None", ",", "update_fields", "=", "None", ")", ":", "# Ensure that a model instance without a PK hasn't been assigned to", "# a ForeignKey or OneToOneFi...
[ 661, 4 ]
[ 745, 78 ]
python
en
['en', 'error', 'th']
False
Model.save_base
(self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None)
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before s...
Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending.
def save_base(self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None): """ Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. ...
[ "def", "save_base", "(", "self", ",", "raw", "=", "False", ",", "force_insert", "=", "False", ",", "force_update", "=", "False", ",", "using", "=", "None", ",", "update_fields", "=", "None", ")", ":", "using", "=", "using", "or", "router", ".", "db_for...
[ 748, 4 ]
[ 795, 13 ]
python
en
['en', 'error', 'th']
False
Model._save_parents
(self, cls, using, update_fields)
Save all the parents of cls using values from self.
Save all the parents of cls using values from self.
def _save_parents(self, cls, using, update_fields): """Save all the parents of cls using values from self.""" meta = cls._meta inserted = False for parent, field in meta.parents.items(): # Make sure the link fields are synced between parent and self. if (field and...
[ "def", "_save_parents", "(", "self", ",", "cls", ",", "using", ",", "update_fields", ")", ":", "meta", "=", "cls", ".", "_meta", "inserted", "=", "False", "for", "parent", ",", "field", "in", "meta", ".", "parents", ".", "items", "(", ")", ":", "# Ma...
[ 799, 4 ]
[ 825, 23 ]
python
en
['en', 'en', 'en']
True
Model._save_table
(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None)
Do the heavy-lifting involved in saving. Update or insert the data for a single table.
Do the heavy-lifting involved in saving. Update or insert the data for a single table.
def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for f in me...
[ "def", "_save_table", "(", "self", ",", "raw", "=", "False", ",", "cls", "=", "None", ",", "force_insert", "=", "False", ",", "force_update", "=", "False", ",", "using", "=", "None", ",", "update_fields", "=", "None", ")", ":", "meta", "=", "cls", "....
[ 827, 4 ]
[ 889, 22 ]
python
en
['en', 'error', 'th']
False
Model._do_update
(self, base_qs, using, pk_val, values, update_fields, forced_update)
Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB).
Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB).
def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update): """ Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB). """ filtered = base_qs.filter(pk=pk_val) if not valu...
[ "def", "_do_update", "(", "self", ",", "base_qs", ",", "using", ",", "pk_val", ",", "values", ",", "update_fields", ",", "forced_update", ")", ":", "filtered", "=", "base_qs", ".", "filter", "(", "pk", "=", "pk_val", ")", "if", "not", "values", ":", "#...
[ 891, 4 ]
[ 916, 43 ]
python
en
['en', 'error', 'th']
False
Model._do_insert
(self, manager, using, fields, returning_fields, raw)
Do an INSERT. If returning_fields is defined then this method should return the newly created data for the model.
Do an INSERT. If returning_fields is defined then this method should return the newly created data for the model.
def _do_insert(self, manager, using, fields, returning_fields, raw): """ Do an INSERT. If returning_fields is defined then this method should return the newly created data for the model. """ return manager._insert( [self], fields=fields, returning_fields=returning_fie...
[ "def", "_do_insert", "(", "self", ",", "manager", ",", "using", ",", "fields", ",", "returning_fields", ",", "raw", ")", ":", "return", "manager", ".", "_insert", "(", "[", "self", "]", ",", "fields", "=", "fields", ",", "returning_fields", "=", "returni...
[ 918, 4 ]
[ 926, 9 ]
python
en
['en', 'error', 'th']
False
Model.clean
(self)
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS....
Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS....
def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field ...
[ "def", "clean", "(", "self", ")", ":", "pass" ]
[ 982, 4 ]
[ 989, 12 ]
python
en
['en', 'error', 'th']
False
Model.validate_unique
(self, exclude=None)
Check unique constraints on the model and raise ValidationError if any failed.
Check unique constraints on the model and raise ValidationError if any failed.
def validate_unique(self, exclude=None): """ Check unique constraints on the model and raise ValidationError if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors =...
[ "def", "validate_unique", "(", "self", ",", "exclude", "=", "None", ")", ":", "unique_checks", ",", "date_checks", "=", "self", ".", "_get_unique_checks", "(", "exclude", "=", "exclude", ")", "errors", "=", "self", ".", "_perform_unique_checks", "(", "unique_c...
[ 991, 4 ]
[ 1005, 41 ]
python
en
['en', 'error', 'th']
False
Model._get_unique_checks
(self, exclude=None)
Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but t...
Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but t...
def _get_unique_checks(self, exclude=None): """ Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that ...
[ "def", "_get_unique_checks", "(", "self", ",", "exclude", "=", "None", ")", ":", "if", "exclude", "is", "None", ":", "exclude", "=", "[", "]", "unique_checks", "=", "[", "]", "unique_togethers", "=", "[", "(", "self", ".", "__class__", ",", "self", "."...
[ 1007, 4 ]
[ 1064, 41 ]
python
en
['en', 'error', 'th']
False
Model.full_clean
(self, exclude=None, validate_unique=True)
Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur.
Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur.
def full_clean(self, exclude=None, validate_unique=True): """ Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = [] else: exclud...
[ "def", "full_clean", "(", "self", ",", "exclude", "=", "None", ",", "validate_unique", "=", "True", ")", ":", "errors", "=", "{", "}", "if", "exclude", "is", "None", ":", "exclude", "=", "[", "]", "else", ":", "exclude", "=", "list", "(", "exclude", ...
[ 1187, 4 ]
[ 1221, 41 ]
python
en
['en', 'error', 'th']
False
Model.clean_fields
(self, exclude=None)
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur.
def clean_fields(self, exclude=None): """ Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur. """ if exclude is None: exclude = [] errors = {} for f in self._meta.fields: if f.name in exclu...
[ "def", "clean_fields", "(", "self", ",", "exclude", "=", "None", ")", ":", "if", "exclude", "is", "None", ":", "exclude", "=", "[", "]", "errors", "=", "{", "}", "for", "f", "in", "self", ".", "_meta", ".", "fields", ":", "if", "f", ".", "name", ...
[ 1223, 4 ]
[ 1246, 41 ]
python
en
['en', 'error', 'th']
False
Model._check_swappable
(cls)
Check if the swapped model exists.
Check if the swapped model exists.
def _check_swappable(cls): """Check if the swapped model exists.""" errors = [] if cls._meta.swapped: try: apps.get_model(cls._meta.swapped) except ValueError: errors.append( checks.Error( "'%s' i...
[ "def", "_check_swappable", "(", "cls", ")", ":", "errors", "=", "[", "]", "if", "cls", ".", "_meta", ".", "swapped", ":", "try", ":", "apps", ".", "get_model", "(", "cls", ".", "_meta", ".", "swapped", ")", "except", "ValueError", ":", "errors", ".",...
[ 1280, 4 ]
[ 1304, 21 ]
python
en
['en', 'en', 'en']
True
Model._check_managers
(cls, **kwargs)
Perform all manager checks.
Perform all manager checks.
def _check_managers(cls, **kwargs): """Perform all manager checks.""" errors = [] for manager in cls._meta.managers: errors.extend(manager.check(**kwargs)) return errors
[ "def", "_check_managers", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "for", "manager", "in", "cls", ".", "_meta", ".", "managers", ":", "errors", ".", "extend", "(", "manager", ".", "check", "(", "*", "*", "kwargs", ")"...
[ 1320, 4 ]
[ 1325, 21 ]
python
en
['en', 'en', 'en']
True
Model._check_fields
(cls, **kwargs)
Perform all field checks.
Perform all field checks.
def _check_fields(cls, **kwargs): """Perform all field checks.""" errors = [] for field in cls._meta.local_fields: errors.extend(field.check(**kwargs)) for field in cls._meta.local_many_to_many: errors.extend(field.check(from_model=cls, **kwargs)) return e...
[ "def", "_check_fields", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "errors", "=", "[", "]", "for", "field", "in", "cls", ".", "_meta", ".", "local_fields", ":", "errors", ".", "extend", "(", "field", ".", "check", "(", "*", "*", "kwargs", ")", ...
[ 1328, 4 ]
[ 1335, 21 ]
python
en
['en', 'sk', 'en']
True
Model._check_m2m_through_same_relationship
(cls)
Check if no relationship model is used by more than one m2m field.
Check if no relationship model is used by more than one m2m field.
def _check_m2m_through_same_relationship(cls): """ Check if no relationship model is used by more than one m2m field. """ errors = [] seen_intermediary_signatures = [] fields = cls._meta.local_many_to_many # Skip when the target model wasn't found. fields = (f ...
[ "def", "_check_m2m_through_same_relationship", "(", "cls", ")", ":", "errors", "=", "[", "]", "seen_intermediary_signatures", "=", "[", "]", "fields", "=", "cls", ".", "_meta", ".", "local_many_to_many", "# Skip when the target model wasn't found.", "fields", "=", "("...
[ 1338, 4 ]
[ 1367, 21 ]
python
en
['en', 'en', 'en']
True
Model._check_id_field
(cls)
Check if `id` field is a primary key.
Check if `id` field is a primary key.
def _check_id_field(cls): """Check if `id` field is a primary key.""" fields = [f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk] # fields is empty or consists of the invalid "id" field if fields and not fields[0].primary_key and cls._meta.pk.name == 'id': ...
[ "def", "_check_id_field", "(", "cls", ")", ":", "fields", "=", "[", "f", "for", "f", "in", "cls", ".", "_meta", ".", "local_fields", "if", "f", ".", "name", "==", "'id'", "and", "f", "!=", "cls", ".", "_meta", ".", "pk", "]", "# fields is empty or co...
[ 1370, 4 ]
[ 1384, 21 ]
python
en
['en', 'en', 'en']
True
Model._check_field_name_clashes
(cls)
Forbid field shadowing in multi-table inheritance.
Forbid field shadowing in multi-table inheritance.
def _check_field_name_clashes(cls): """Forbid field shadowing in multi-table inheritance.""" errors = [] used_fields = {} # name or attname -> field # Check that multi-inheritance doesn't cause field name shadowing. for parent in cls._meta.get_parent_list(): for f i...
[ "def", "_check_field_name_clashes", "(", "cls", ")", ":", "errors", "=", "[", "]", "used_fields", "=", "{", "}", "# name or attname -> field", "# Check that multi-inheritance doesn't cause field name shadowing.", "for", "parent", "in", "cls", ".", "_meta", ".", "get_par...
[ 1387, 4 ]
[ 1441, 21 ]
python
en
['en', 'fy', 'en']
True
Model._check_index_together
(cls)
Check the value of "index_together" option.
Check the value of "index_together" option.
def _check_index_together(cls): """Check the value of "index_together" option.""" if not isinstance(cls._meta.index_together, (tuple, list)): return [ checks.Error( "'index_together' must be a list or tuple.", obj=cls, ...
[ "def", "_check_index_together", "(", "cls", ")", ":", "if", "not", "isinstance", "(", "cls", ".", "_meta", ".", "index_together", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "[", "checks", ".", "Error", "(", "\"'index_together' must be a list or...
[ 1527, 4 ]
[ 1551, 25 ]
python
en
['en', 'en', 'en']
True
Model._check_unique_together
(cls)
Check the value of "unique_together" option.
Check the value of "unique_together" option.
def _check_unique_together(cls): """Check the value of "unique_together" option.""" if not isinstance(cls._meta.unique_together, (tuple, list)): return [ checks.Error( "'unique_together' must be a list or tuple.", obj=cls, ...
[ "def", "_check_unique_together", "(", "cls", ")", ":", "if", "not", "isinstance", "(", "cls", ".", "_meta", ".", "unique_together", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "[", "checks", ".", "Error", "(", "\"'unique_together' must be a list...
[ 1554, 4 ]
[ 1578, 25 ]
python
en
['en', 'en', 'en']
True
Model._check_indexes
(cls)
Check the fields and names of indexes.
Check the fields and names of indexes.
def _check_indexes(cls): """Check the fields and names of indexes.""" errors = [] for index in cls._meta.indexes: # Index name can't start with an underscore or a number, restricted # for cross-database compatibility with Oracle. if index.name[0] == '_' or ind...
[ "def", "_check_indexes", "(", "cls", ")", ":", "errors", "=", "[", "]", "for", "index", "in", "cls", ".", "_meta", ".", "indexes", ":", "# Index name can't start with an underscore or a number, restricted", "# for cross-database compatibility with Oracle.", "if", "index",...
[ 1581, 4 ]
[ 1607, 21 ]
python
en
['en', 'en', 'en']
True
Model._check_ordering
(cls)
Check "ordering" option -- is it a list of strings and do all fields exist?
Check "ordering" option -- is it a list of strings and do all fields exist?
def _check_ordering(cls): """ Check "ordering" option -- is it a list of strings and do all fields exist? """ if cls._meta._ordering_clash: return [ checks.Error( "'ordering' and 'order_with_respect_to' cannot be used together.", ...
[ "def", "_check_ordering", "(", "cls", ")", ":", "if", "cls", ".", "_meta", ".", "_ordering_clash", ":", "return", "[", "checks", ".", "Error", "(", "\"'ordering' and 'order_with_respect_to' cannot be used together.\"", ",", "obj", "=", "cls", ",", "id", "=", "'m...
[ 1660, 4 ]
[ 1759, 21 ]
python
en
['en', 'error', 'th']
False
Model._check_long_column_names
(cls)
Check that any auto-generated column names are shorter than the limits for each database in which the model will be created.
Check that any auto-generated column names are shorter than the limits for each database in which the model will be created.
def _check_long_column_names(cls): """ Check that any auto-generated column names are shorter than the limits for each database in which the model will be created. """ errors = [] allowed_len = None db_alias = None # Find the minimum max allowed length am...
[ "def", "_check_long_column_names", "(", "cls", ")", ":", "errors", "=", "[", "]", "allowed_len", "=", "None", "db_alias", "=", "None", "# Find the minimum max allowed length among all specified db_aliases.", "for", "db", "in", "settings", ".", "DATABASES", ":", "# ski...
[ 1762, 4 ]
[ 1832, 21 ]
python
en
['en', 'error', 'th']
False
get_cache
(backend, **kwargs)
Function to create a cache backend dynamically. This is flexible by design to allow different use cases: To load a backend that is pre-defined in the settings:: cache = get_cache('default') To create a backend with its dotted import path, including arbitrary options:: cache = ge...
Function to create a cache backend dynamically. This is flexible by design to allow different use cases:
def get_cache(backend, **kwargs): """ Function to create a cache backend dynamically. This is flexible by design to allow different use cases: To load a backend that is pre-defined in the settings:: cache = get_cache('default') To create a backend with its dotted import path, includin...
[ "def", "get_cache", "(", "backend", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "\"'get_cache' is deprecated in favor of 'caches'.\"", ",", "RemovedInDjango19Warning", ",", "stacklevel", "=", "2", ")", "cache", "=", "_create_cache", "(", "back...
[ 37, 0 ]
[ 61, 16 ]
python
en
['en', 'error', 'th']
False
parse_requirements
( filename, # type: str session, # type: PipSession finder=None, # type: Optional[PackageFinder] comes_from=None, # type: Optional[str] options=None, # type: Optional[optparse.Values] constraint=False, # type: bool )
Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param session: PipSession instance. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: cli o...
Parse a requirements file and yield InstallRequirement instances.
def parse_requirements( filename, # type: str session, # type: PipSession finder=None, # type: Optional[PackageFinder] comes_from=None, # type: Optional[str] options=None, # type: Optional[optparse.Values] constraint=False, # type: bool ): # type: (...) -> Iterator[ParsedRequirement] ...
[ "def", "parse_requirements", "(", "filename", ",", "# type: str", "session", ",", "# type: PipSession", "finder", "=", "None", ",", "# type: Optional[PackageFinder]", "comes_from", "=", "None", ",", "# type: Optional[str]", "options", "=", "None", ",", "# type: Optional...
[ 128, 0 ]
[ 158, 28 ]
python
en
['en', 'en', 'en']
True
preprocess
(content)
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): # type: (Text) -> ReqFileLines """Split, filter, and join lines, and return a line iterator :param content: the content of the requirements file """ lines_enum = enumerate(content.splitlines(), start=1) # type: ReqFileLines lines_enum = join_lines(lines_enum) lines...
[ "def", "preprocess", "(", "content", ")", ":", "# type: (Text) -> ReqFileLines", "lines_enum", "=", "enumerate", "(", "content", ".", "splitlines", "(", ")", ",", "start", "=", "1", ")", "# type: ReqFileLines", "lines_enum", "=", "join_lines", "(", "lines_enum", ...
[ 161, 0 ]
[ 171, 21 ]
python
en
['en', 'en', 'en']
True
handle_line
( line, # type: ParsedLine options=None, # type: Optional[optparse.Values] finder=None, # type: Optional[PackageFinder] session=None, # type: Optional[PipSession] )
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, # type: ParsedLine options=None, # type: Optional[optparse.Values] finder=None, # type: Optional[PackageFinder] session=None, # type: Optional[PipSession] ): # type: (...) -> Optional[ParsedRequirement] """Handle a single parsed requirements line; This can result in ...
[ "def", "handle_line", "(", "line", ",", "# type: ParsedLine", "options", "=", "None", ",", "# type: Optional[optparse.Values]", "finder", "=", "None", ",", "# type: Optional[PackageFinder]", "session", "=", "None", ",", "# type: Optional[PipSession]", ")", ":", "# type:...
[ 268, 0 ]
[ 310, 19 ]
python
en
['en', 'en', 'en']
True
break_args_options
(line)
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): # type: (Text) -> Tuple[str, Text] """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 = [] opti...
[ "def", "break_args_options", "(", "line", ")", ":", "# type: (Text) -> Tuple[str, Text]", "tokens", "=", "line", ".", "split", "(", "' '", ")", "args", "=", "[", "]", "options", "=", "tokens", "[", ":", "]", "for", "token", "in", "tokens", ":", "if", "to...
[ 418, 0 ]
[ 433, 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(): # type: () -> 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_fa...
[ "def", "build_parser", "(", ")", ":", "# type: () -> optparse.OptionParser", "parser", "=", "optparse", ".", "OptionParser", "(", "add_help_option", "=", "False", ")", "option_factories", "=", "SUPPORTED_OPTIONS", "+", "SUPPORTED_OPTIONS_REQ", "for", "option_factory", "...
[ 442, 0 ]
[ 463, 17 ]
python
en
['en', 'error', 'th']
False
join_lines
(lines_enum)
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): # type: (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 = [] # type: List[Text] for line_number, l...
[ "def", "join_lines", "(", "lines_enum", ")", ":", "# type: (ReqFileLines) -> ReqFileLines", "primary_line_number", "=", "None", "new_line", "=", "[", "]", "# type: List[Text]", "for", "line_number", ",", "line", "in", "lines_enum", ":", "if", "not", "line", ".", "...
[ 466, 0 ]
[ 491, 52 ]
python
en
['en', 'en', 'en']
True
ignore_comments
(lines_enum)
Strips comments and filter empty lines.
Strips comments and filter empty lines.
def ignore_comments(lines_enum): # type: (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", ")", ":", "# type: (ReqFileLines) -> ReqFileLines", "for", "line_number", ",", "line", "in", "lines_enum", ":", "line", "=", "COMMENT_RE", ".", "sub", "(", "''", ",", "line", ")", "line", "=", "line", ".", "strip", ...
[ 496, 0 ]
[ 505, 35 ]
python
en
['en', 'error', 'th']
False
expand_env_variables
(lines_enum)
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): # type: (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 con...
[ "def", "expand_env_variables", "(", "lines_enum", ")", ":", "# type: (ReqFileLines) -> ReqFileLines", "for", "line_number", ",", "line", "in", "lines_enum", ":", "for", "env_var", ",", "var_name", "in", "ENV_VAR_RE", ".", "findall", "(", "line", ")", ":", "value",...
[ 508, 0 ]
[ 533, 31 ]
python
en
['en', 'en', 'en']
True
get_file_content
(url, session, comes_from=None)
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. :param comes_from: Origin descrip...
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, session, comes_from=None): # type: (str, PipSession, Optional[str]) -> Tuple[str, Text] """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", ",", "session", ",", "comes_from", "=", "None", ")", ":", "# type: (str, PipSession, Optional[str]) -> Tuple[str, Text]", "scheme", "=", "get_url_scheme", "(", "url", ")", "if", "scheme", "in", "[", "'http'", ",", "'https'", ...
[ 536, 0 ]
[ 578, 23 ]
python
en
['en', 'en', 'en']
True
RequirementsFileParser.parse
(self, filename, constraint)
Parse a given file, yielding parsed lines.
Parse a given file, yielding parsed lines.
def parse(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] """Parse a given file, yielding parsed lines. """ for line in self._parse_and_recurse(filename, constraint): yield line
[ "def", "parse", "(", "self", ",", "filename", ",", "constraint", ")", ":", "# type: (str, bool) -> Iterator[ParsedLine]", "for", "line", "in", "self", ".", "_parse_and_recurse", "(", "filename", ",", "constraint", ")", ":", "yield", "line" ]
[ 325, 4 ]
[ 330, 22 ]
python
en
['en', 'en', 'en']
True
Field.clean
(self, value)
Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors.
Validates the given value and returns its "cleaned" value as an appropriate Python object.
def clean(self, value): """ Validates the given value and returns its "cleaned" value as an appropriate Python object. Raises ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return ...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "to_python", "(", "value", ")", "self", ".", "validate", "(", "value", ")", "self", ".", "run_validators", "(", "value", ")", "return", "value" ]
[ 152, 4 ]
[ 162, 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", ")", ":", "return", "data" ]
[ 164, 4 ]
[ 173, 19 ]
python
en
['en', 'error', 'th']
False
Field.widget_attrs
(self, widget)
Given a Widget instance (*not* a Widget class), returns 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), returns 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), returns a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {}
[ "def", "widget_attrs", "(", "self", ",", "widget", ")", ":", "return", "{", "}" ]
[ 175, 4 ]
[ 181, 17 ]
python
en
['en', 'error', 'th']
False
Field.get_limit_choices_to
(self)
Returns ``limit_choices_to`` for this form field. If it is a callable, it will be invoked and the result will be returned.
Returns ``limit_choices_to`` for this form field.
def get_limit_choices_to(self): """ Returns ``limit_choices_to`` for this form field. If it is a callable, it will be invoked and the result will be returned. """ if callable(self.limit_choices_to): return self.limit_choices_to() return self.limit_cho...
[ "def", "get_limit_choices_to", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "limit_choices_to", ")", ":", "return", "self", ".", "limit_choices_to", "(", ")", "return", "self", ".", "limit_choices_to" ]
[ 183, 4 ]
[ 192, 36 ]
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. """ # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or initial value we get # is None, replace it w/ ''. initial_value = ...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "# For purposes of seeing whether something has changed, None is", "# the same as an empty string, if the data or initial value we get", "# is None, replace it w/ ''.", "initial_value", "=", "initial", "if", ...
[ 194, 4 ]
[ 209, 42 ]
python
en
['en', 'error', 'th']
False
CharField.to_python
(self, value)
Returns a Unicode object.
Returns a Unicode object.
def to_python(self, value): "Returns a Unicode object." if value in self.empty_values: return '' return smart_text(value)
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "''", "return", "smart_text", "(", "value", ")" ]
[ 228, 4 ]
[ 232, 32 ]
python
en
['en', 'bg', 'en']
True
IntegerField.to_python
(self, value)
Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values.
Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values.
def to_python(self, value): """ Validates that int() can be called on the input. Returns the result of int(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.local...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "IntegerField", ",", "self", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "l...
[ 260, 4 ]
[ 274, 20 ]
python
en
['en', 'error', 'th']
False
FloatField.to_python
(self, value)
Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values.
Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values.
def to_python(self, value): """ Validates that float() can be called on the input. Returns the result of float(). Returns None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.l...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "IntegerField", ",", "self", ")", ".", "to_python", "(", "value", ")", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "l...
[ 291, 4 ]
[ 305, 20 ]
python
en
['en', 'error', 'th']
False
DecimalField.to_python
(self, value)
Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point.
Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures 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): """ Validates that the input is a decimal number. Returns a Decimal instance. Returns None for empty values. Ensures 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", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "self", ".", "localize", ":", "value", "=", "formats", ".", "sanitize_separators", "(", "value", ")", "value", "=", ...
[ 344, 4 ]
[ 360, 20 ]
python
en
['en', 'error', 'th']
False
DateField.to_python
(self, value)
Validates that the input can be converted to a date. Returns a Python datetime.date object.
Validates that the input can be converted to a date. Returns a Python datetime.date object.
def to_python(self, value): """ Validates that the input can be converted to a date. Returns a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isins...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "value", ".", "date", "(", ")", ...
[ 449, 4 ]
[ 460, 54 ]
python
en
['en', 'error', 'th']
False
TimeField.to_python
(self, value)
Validates that the input can be converted to a time. Returns a Python datetime.time object.
Validates that the input can be converted to a time. Returns a Python datetime.time object.
def to_python(self, value): """ Validates that the input can be converted to a time. Returns a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super(TimeFi...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "time", ")", ":", "return", "value", "return", "super", "(", "Time...
[ 473, 4 ]
[ 482, 54 ]
python
en
['en', 'error', 'th']
False
DateTimeField.to_python
(self, value)
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object.
def to_python(self, value): """ Validates that the input can be converted to a datetime. Returns a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "None", "if", "isinstance", "(", "value", ",", "datetime", ".", "datetime", ")", ":", "return", "from_current_timezone", "(", "value",...
[ 500, 4 ]
[ 525, 44 ]
python
en
['en', 'error', 'th']
False
RegexField.__init__
(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs)
regex can be either a string or a compiled regular expression object. error_message is an optional error message to use, if 'Enter a valid value' is too generic for you.
regex can be either a string or a compiled regular expression object. error_message is an optional error message to use, if 'Enter a valid value' is too generic for you.
def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs): """ regex can be either a string or a compiled regular expression object. error_message is an optional error message to use, if 'Enter a valid value' is too generic for you. """ ...
[ "def", "__init__", "(", "self", ",", "regex", ",", "max_length", "=", "None", ",", "min_length", "=", "None", ",", "error_message", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# error_message is just kept for backwards compatibility:", "...
[ 532, 4 ]
[ 549, 30 ]
python
en
['en', 'error', 'th']
False
ImageField.to_python
(self, data)
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports).
def to_python(self, data): """ Checks that the file-upload field data contains a valid image (GIF, JPG, PNG, possibly others -- whatever the Python Imaging Library supports). """ f = super(ImageField, self).to_python(data) if f is None: return None fr...
[ "def", "to_python", "(", "self", ",", "data", ")", ":", "f", "=", "super", "(", "ImageField", ",", "self", ")", ".", "to_python", "(", "data", ")", "if", "f", "is", "None", ":", "return", "None", "from", "PIL", "import", "Image", "# We need to get a fi...
[ 652, 4 ]
[ 691, 16 ]
python
en
['en', 'error', 'th']
False
BooleanField.to_python
(self, value)
Returns a Python boolean object.
Returns a Python boolean object.
def to_python(self, value): """Returns 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 d...
[ "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...
[ 740, 4 ]
[ 750, 57 ]
python
en
['en', 'en', 'en']
True
NullBooleanField.to_python
(self, value)
Explicitly checks 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 th...
Explicitly checks 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 th...
def to_python(self, value): """ Explicitly checks 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 Ra...
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "(", "True", ",", "'True'", ",", "'true'", ",", "'1'", ")", ":", "return", "True", "elif", "value", "in", "(", "False", ",", "'False'", ",", "'false'", ",", "'0'", ")", ...
[ 772, 4 ]
[ 786, 23 ]
python
en
['en', 'error', 'th']
False
ChoiceField.to_python
(self, value)
Returns a Unicode object.
Returns a Unicode object.
def to_python(self, value): "Returns a Unicode object." if value in self.empty_values: return '' return smart_text(value)
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "value", "in", "self", ".", "empty_values", ":", "return", "''", "return", "smart_text", "(", "value", ")" ]
[ 828, 4 ]
[ 832, 32 ]
python
en
['en', 'bg', 'en']
True
ChoiceField.validate
(self, value)
Validates that the input is in self.choices.
Validates that the input is in self.choices.
def validate(self, value): """ Validates that the input is in self.choices. """ super(ChoiceField, self).validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages['invalid_choice'], code='inval...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "super", "(", "ChoiceField", ",", "self", ")", ".", "validate", "(", "value", ")", "if", "value", "and", "not", "self", ".", "valid_value", "(", "value", ")", ":", "raise", "ValidationError", "(",...
[ 834, 4 ]
[ 844, 13 ]
python
en
['en', 'error', 'th']
False
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 = force_text(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", "=", "force_text", "(", "value", ")", "for", "k", ",", "v", "in", "self", ".", "choices", ":", "if", "isinstance", "(", "v", ",", "(", "list", ",", "tuple", ")", ")", ":", "...
[ 846, 4 ]
[ 858, 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", "(", ...
[ 867, 4 ]
[ 881, 20 ]
python
en
['en', 'error', 'th']
False
MultipleChoiceField.validate
(self, value)
Validates that the input is a list or tuple.
Validates that the input is a list or tuple.
def validate(self, value): """ Validates 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 ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "if", "self", ".", "required", "and", "not", "value", ":", "raise", "ValidationError", "(", "self", ".", "error_messages", "[", "'required'", "]", ",", "code", "=", "'required'", ")", "# Validate that...
[ 903, 4 ]
[ 916, 17 ]
python
en
['en', 'error', 'th']
False
TypedMultipleChoiceField._coerce
(self, value)
Validates that the values are in self.choices and can be coerced to the right type.
Validates that the values are in self.choices and can be coerced to the right type.
def _coerce(self, value): """ Validates 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: tr...
[ "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...
[ 936, 4 ]
[ 953, 24 ]
python
en
['en', 'error', 'th']
False
ComboField.clean
(self, value)
Validates the given value against all of self.fields, which is a list of Field instances.
Validates the given value against all of self.fields, which is a list of Field instances.
def clean(self, value): """ Validates the given value against all of self.fields, which is a list of Field instances. """ super(ComboField, self).clean(value) for field in self.fields: value = field.clean(value) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "super", "(", "ComboField", ",", "self", ")", ".", "clean", "(", "value", ")", "for", "field", "in", "self", ".", "fields", ":", "value", "=", "field", ".", "clean", "(", "value", ")", "return", ...
[ 979, 4 ]
[ 987, 20 ]
python
en
['en', 'error', 'th']
False
MultiValueField.clean
(self, value)
Validates 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])...
Validates every value in the given list. A value is validated against the corresponding Field in self.fields.
def clean(self, value): """ Validates 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(valu...
[ "def", "clean", "(", "self", ",", "value", ")", ":", "clean_data", "=", "[", "]", "errors", "=", "[", "]", "if", "not", "value", "or", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "not", "value", "or", "not", ...
[ 1033, 4 ]
[ 1083, 18 ]
python
en
['en', 'error', 'th']
False
MultiValueField.compress
(self, data_list)
Returns 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. ...
Returns a single value for the given list of values. The values can be assumed to be valid.
def compress(self, data_list): """ Returns 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 com...
[ "def", "compress", "(", "self", ",", "data_list", ")", ":", "raise", "NotImplementedError", "(", "'Subclasses must implement this method.'", ")" ]
[ 1085, 4 ]
[ 1094, 75 ]
python
en
['en', 'error', 'th']
False
Package.__init__
( self, name: str, specs: List[Tuple[str, str]], path: Optional[Path] = None, uri: Optional[str] = None, vcs: Optional[str] = None, revision: Optional[str] = None, line: Optional[str] = None, **kwargs, )
Generic Python Dependency. Args: name (str): Name of package specs (List[Tuple[str, str]]): Package constraints. path: path to package
Generic Python Dependency.
def __init__( self, name: str, specs: List[Tuple[str, str]], path: Optional[Path] = None, uri: Optional[str] = None, vcs: Optional[str] = None, revision: Optional[str] = None, line: Optional[str] = None, **kwargs, ): """Generic Python D...
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "specs", ":", "List", "[", "Tuple", "[", "str", ",", "str", "]", "]", ",", "path", ":", "Optional", "[", "Path", "]", "=", "None", ",", "uri", ":", "Optional", "[", "str", "]", "=", ...
[ 11, 4 ]
[ 37, 46 ]
python
en
['en', 'en', 'en']
True
Package.from_text
(cls, name: str, specs: str)
Create package from text. Args: name: name of package specs: package constraints Returns: Package instance
Create package from text.
def from_text(cls, name: str, specs: str) -> "Package": """Create package from text. Args: name: name of package specs: package constraints Returns: Package instance """ if "http" in specs: req = next(requirements.parse(specs)) ...
[ "def", "from_text", "(", "cls", ",", "name", ":", "str", ",", "specs", ":", "str", ")", "->", "\"Package\"", ":", "if", "\"http\"", "in", "specs", ":", "req", "=", "next", "(", "requirements", ".", "parse", "(", "specs", ")", ")", "return", "cls", ...
[ 94, 4 ]
[ 115, 39 ]
python
en
['en', 'en', 'en']
True
load_images
(input_dir, batch_shape)
Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this list could be less than batch_size, in this case o...
Read png images from input directory in batches.
def load_images(input_dir, batch_shape): """Read png images from input directory in batches. Args: input_dir: input directory batch_shape: shape of minibatch array, i.e. [batch_size, height, width, 3] Yields: filenames: list file names without path of each image Lenght of this li...
[ "def", "load_images", "(", "input_dir", ",", "batch_shape", ")", ":", "images", "=", "np", ".", "zeros", "(", "batch_shape", ")", "filenames", "=", "[", "]", "idx", "=", "0", "batch_size", "=", "batch_shape", "[", "0", "]", "for", "filepath", "in", "tf...
[ 32, 0 ]
[ 60, 31 ]
python
en
['en', 'en', 'en']
True
save_images
(images, filenames, output_dir)
Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filenames) images will be saved. output_dir: directory ...
Saves images to the output directory.
def save_images(images, filenames, output_dir): """Saves images to the output directory. Args: images: array with minibatch of images filenames: list of filenames without path If number of file names in this list less than number of images in the minibatch then only first len(filena...
[ "def", "save_images", "(", "images", ",", "filenames", ",", "output_dir", ")", ":", "for", "i", ",", "filename", "in", "enumerate", "(", "filenames", ")", ":", "with", "tf", ".", "gfile", ".", "Open", "(", "os", ".", "path", ".", "join", "(", "output...
[ 63, 0 ]
[ 75, 55 ]
python
en
['en', 'en', 'en']
True
main
(_)
Run the sample attack
Run the sample attack
def main(_): """Run the sample attack""" eps = FLAGS.max_epsilon / 255.0 batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3] with tf.Graph().as_default(): x_input = tf.placeholder(tf.float32, shape=batch_shape) noisy_images = x_input + eps * tf.sign(tf.random_norm...
[ "def", "main", "(", "_", ")", ":", "eps", "=", "FLAGS", ".", "max_epsilon", "/", "255.0", "batch_shape", "=", "[", "FLAGS", ".", "batch_size", ",", "FLAGS", ".", "image_height", ",", "FLAGS", ".", "image_width", ",", "3", "]", "with", "tf", ".", "Gra...
[ 78, 0 ]
[ 91, 68 ]
python
en
['en', 'it', 'en']
True
start
(io_loop=None, check_time=500)
Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated.
Begins watching source files for changes.
def start(io_loop=None, check_time=500): """Begins watching source files for changes. .. versionchanged:: 4.1 The ``io_loop`` argument is deprecated. """ io_loop = io_loop or ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True if len(_io_loops) >...
[ "def", "start", "(", "io_loop", "=", "None", ",", "check_time", "=", "500", ")", ":", "io_loop", "=", "io_loop", "or", "ioloop", ".", "IOLoop", ".", "current", "(", ")", "if", "io_loop", "in", "_io_loops", ":", "return", "_io_loops", "[", "io_loop", "]...
[ 83, 0 ]
[ 98, 21 ]
python
en
['en', 'en', 'en']
True
wait
()
Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`)
Wait for a watched file to change, then restart the process.
def wait(): """Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`) """ io_loop = ioloop.IOLoop() start(io_loop)...
[ "def", "wait", "(", ")", ":", "io_loop", "=", "ioloop", ".", "IOLoop", "(", ")", "start", "(", "io_loop", ")", "io_loop", ".", "start", "(", ")" ]
[ 101, 0 ]
[ 110, 19 ]
python
en
['en', 'en', 'en']
True
watch
(filename)
Add a file to the watch list. All imported modules are watched by default.
Add a file to the watch list.
def watch(filename): """Add a file to the watch list. All imported modules are watched by default. """ _watched_files.add(filename)
[ "def", "watch", "(", "filename", ")", ":", "_watched_files", ".", "add", "(", "filename", ")" ]
[ 113, 0 ]
[ 118, 32 ]
python
en
['en', 'en', 'en']
True
add_reload_hook
(fn)
Add a function to be called before reloading the process. Note that for open file and socket handles it is generally preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or ``tornado.platform.auto.set_close_exec``) instead of using a reload hook to close them.
Add a function to be called before reloading the process.
def add_reload_hook(fn): """Add a function to be called before reloading the process. Note that for open file and socket handles it is generally preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or ``tornado.platform.auto.set_close_exec``) instead of using a reload hook to close them. ""...
[ "def", "add_reload_hook", "(", "fn", ")", ":", "_reload_hooks", ".", "append", "(", "fn", ")" ]
[ 121, 0 ]
[ 129, 28 ]
python
en
['en', 'en', 'en']
True
RespaExchangeAppConfig.ready
(self)
Wire up the signals for uploading reservations.
Wire up the signals for uploading reservations.
def ready(self): """ Wire up the signals for uploading reservations. """ from respa_exchange.signals import handle_reservation_delete, handle_reservation_save post_save.connect( handle_reservation_save, sender='resources.Reservation', dispatch_...
[ "def", "ready", "(", "self", ")", ":", "from", "respa_exchange", ".", "signals", "import", "handle_reservation_delete", ",", "handle_reservation_save", "post_save", ".", "connect", "(", "handle_reservation_save", ",", "sender", "=", "'resources.Reservation'", ",", "di...
[ 8, 4 ]
[ 22, 9 ]
python
en
['en', 'error', 'th']
False
test_get_price_correct
(order_line_price)
Test price calculation works correctly for prices with tax Two hour reservation of one product with a price of 12.40, plus individual product tax of 24% should equal 24.80
Test price calculation works correctly for prices with tax
def test_get_price_correct(order_line_price): """Test price calculation works correctly for prices with tax Two hour reservation of one product with a price of 12.40, plus individual product tax of 24% should equal 24.80""" price = order_line_price.get_price() assert price == Decimal('24.80')
[ "def", "test_get_price_correct", "(", "order_line_price", ")", ":", "price", "=", "order_line_price", ".", "get_price", "(", ")", "assert", "price", "==", "Decimal", "(", "'24.80'", ")" ]
[ 26, 0 ]
[ 32, 36 ]
python
en
['en', 'en', 'en']
True
single_run_max_confidence_recipe
( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, )
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack (noise, targeted...
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. This recipe uses both uniform noise and randomly-initialized PGD targeted attacks.
def single_run_max_confidence_recipe( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, ): """A reasonable attack bundling recipe for a max norm threat model and a defender that ...
[ "def", "single_run_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "eps_iter", ",", "nb_iter", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "eps_it...
[ 42, 0 ]
[ 126, 5 ]
python
en
['en', 'en', 'en']
True
basic_max_confidence_recipe
( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, )
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs indefinitely, updating the report on disk continuously. :param sess: tf.Session :param model: cleverhans.m...
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding.
def basic_max_confidence_recipe( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, ): """A reasonable attack bundling recipe for a max norm threat model and a defender that uses ...
[ "def", "basic_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "eps_iter", ",", "nb_iter", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "eps_iter_sm...
[ 129, 0 ]
[ 210, 73 ]
python
en
['en', 'en', 'en']
True
fixed_max_confidence_recipe
( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, )
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding. References: https://openreview.net/forum?id=H1g0piA9tQ This version runs each attack a fixed number of times. It is more exhaustive than `single_run_max_confidence_recipe` but because ...
A reasonable attack bundling recipe for a max norm threat model and a defender that uses confidence thresholding.
def fixed_max_confidence_recipe( sess, model, x, y, nb_classes, eps, clip_min, clip_max, eps_iter, nb_iter, report_path, batch_size=BATCH_SIZE, eps_iter_small=None, ): """A reasonable attack bundling recipe for a max norm threat model and a defender that uses ...
[ "def", "fixed_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "nb_classes", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "eps_iter", ",", "nb_iter", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "eps_iter_sm...
[ 214, 0 ]
[ 298, 73 ]
python
en
['en', 'en', 'en']
True
random_search_max_confidence_recipe
( sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000, )
Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_confidence procedure used for the bundling in this recipe https://arxiv.org/abs/1802.00420 Describes using random search with 1e5 or more random points to avoid gradient masking. ...
Max confidence using random search.
def random_search_max_confidence_recipe( sess, model, x, y, eps, clip_min, clip_max, report_path, batch_size=BATCH_SIZE, num_noise_points=10000, ): """Max confidence using random search. References: https://openreview.net/forum?id=H1g0piA9tQ Describes the max_c...
[ "def", "random_search_max_confidence_recipe", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "eps", ",", "clip_min", ",", "clip_max", ",", "report_path", ",", "batch_size", "=", "BATCH_SIZE", ",", "num_noise_points", "=", "10000", ",", ")", ":", "noise_...
[ 301, 0 ]
[ 342, 73 ]
python
en
['en', 'it', 'en']
True
bundle_attacks
( sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE, )
Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example ...
Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above.
def bundle_attacks( sess, model, x, y, attack_configs, goals, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE, ): """ Runs attack bundling. Users of cleverhans may call this function but are more likely to call one of the recipes above. Refe...
[ "def", "bundle_attacks", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "attack_configs", ",", "goals", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", "BATCH_SIZE", ",", ")", ":", "assert", "isinstance", "(...
[ 373, 0 ]
[ 457, 28 ]
python
en
['en', 'error', 'th']
False
bundle_attacks_with_goal
( sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE, )
Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`. Reference: https://openreview.net/forum?id=H1g0piA9tQ :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean exampl...
Runs attack bundling, working on one specific AttackGoal. This function is mostly intended to be called by `bundle_attacks`.
def bundle_attacks_with_goal( sess, model, x, y, adv_x, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, eval_batch_size=BATCH_SIZE, ): """ Runs attack bundling, working on one specific AttackGoal. This function is mostly in...
[ "def", "bundle_attacks_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", "eval_batch_size", "=", ...
[ 460, 0 ]
[ 520, 46 ]
python
en
['en', 'error', 'th']
False
run_batch_with_goal
( sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, )
Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`. :param sess: tf.session.Session :param model: cleverhans.model.Model :param x: numpy array containing clean example inputs to attack :param y: numpy array containing true...
Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle_attacks_with_goal`.
def run_batch_with_goal( sess, model, x, y, adv_x_val, criteria, attack_configs, run_counts, goal, report, report_path, attack_batch_size=BATCH_SIZE, ): """ Runs attack bundling on one batch of data. This function is mostly intended to be called by `bundle...
[ "def", "run_batch_with_goal", "(", "sess", ",", "model", ",", "x", ",", "y", ",", "adv_x_val", ",", "criteria", ",", "attack_configs", ",", "run_counts", ",", "goal", ",", "report", ",", "report_path", ",", "attack_batch_size", "=", "BATCH_SIZE", ",", ")", ...
[ 523, 0 ]
[ 602, 54 ]
python
en
['en', 'error', 'th']
False