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
ViewTest.test_get_and_post
(self)
Test a view which only allows both GET and POST.
Test a view which only allows both GET and POST.
def test_get_and_post(self): """ Test a view which only allows both GET and POST. """ self._assert_simple(SimplePostView.as_view()(self.rf.get('/'))) self._assert_simple(SimplePostView.as_view()(self.rf.post('/'))) self.assertEqual(SimplePostView.as_view()( se...
[ "def", "test_get_and_post", "(", "self", ")", ":", "self", ".", "_assert_simple", "(", "SimplePostView", ".", "as_view", "(", ")", "(", "self", ".", "rf", ".", "get", "(", "'/'", ")", ")", ")", "self", ".", "_assert_simple", "(", "SimplePostView", ".", ...
[ 127, 4 ]
[ 135, 27 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_invalid_keyword_argument
(self)
Test that view arguments must be predefined on the class and can't be named like a HTTP method.
Test that view arguments must be predefined on the class and can't be named like a HTTP method.
def test_invalid_keyword_argument(self): """ Test that view arguments must be predefined on the class and can't be named like a HTTP method. """ # Check each of the allowed method names for method in SimpleView.http_method_names: kwargs = dict(((method, "value...
[ "def", "test_invalid_keyword_argument", "(", "self", ")", ":", "# Check each of the allowed method names", "for", "method", "in", "SimpleView", ".", "http_method_names", ":", "kwargs", "=", "dict", "(", "(", "(", "method", ",", "\"value\"", ")", ",", ")", ")", "...
[ 137, 4 ]
[ 150, 78 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_calling_more_than_once
(self)
Test a view can only be called once.
Test a view can only be called once.
def test_calling_more_than_once(self): """ Test a view can only be called once. """ request = self.rf.get('/') view = InstanceView.as_view() self.assertNotEqual(view(request), view(request))
[ "def", "test_calling_more_than_once", "(", "self", ")", ":", "request", "=", "self", ".", "rf", ".", "get", "(", "'/'", ")", "view", "=", "InstanceView", ".", "as_view", "(", ")", "self", ".", "assertNotEqual", "(", "view", "(", "request", ")", ",", "v...
[ 152, 4 ]
[ 158, 57 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_class_attributes
(self)
Test that the callable returned from as_view() has proper docstring, name and module.
Test that the callable returned from as_view() has proper docstring, name and module.
def test_class_attributes(self): """ Test that the callable returned from as_view() has proper docstring, name and module. """ self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__) self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__) s...
[ "def", "test_class_attributes", "(", "self", ")", ":", "self", ".", "assertEqual", "(", "SimpleView", ".", "__doc__", ",", "SimpleView", ".", "as_view", "(", ")", ".", "__doc__", ")", "self", ".", "assertEqual", "(", "SimpleView", ".", "__name__", ",", "Si...
[ 160, 4 ]
[ 167, 80 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_dispatch_decoration
(self)
Test that attributes set by decorators on the dispatch method are also present on the closure.
Test that attributes set by decorators on the dispatch method are also present on the closure.
def test_dispatch_decoration(self): """ Test that attributes set by decorators on the dispatch method are also present on the closure. """ self.assertTrue(DecoratedDispatchView.as_view().is_decorated)
[ "def", "test_dispatch_decoration", "(", "self", ")", ":", "self", ".", "assertTrue", "(", "DecoratedDispatchView", ".", "as_view", "(", ")", ".", "is_decorated", ")" ]
[ 169, 4 ]
[ 174, 69 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_options
(self)
Test that views respond to HTTP OPTIONS requests with an Allow header appropriate for the methods implemented by the view class.
Test that views respond to HTTP OPTIONS requests with an Allow header appropriate for the methods implemented by the view class.
def test_options(self): """ Test that views respond to HTTP OPTIONS requests with an Allow header appropriate for the methods implemented by the view class. """ request = self.rf.options('/') view = SimpleView.as_view() response = view(request) self.assert...
[ "def", "test_options", "(", "self", ")", ":", "request", "=", "self", ".", "rf", ".", "options", "(", "'/'", ")", "view", "=", "SimpleView", ".", "as_view", "(", ")", "response", "=", "view", "(", "request", ")", "self", ".", "assertEqual", "(", "200...
[ 176, 4 ]
[ 185, 42 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_options_for_get_view
(self)
Test that a view implementing GET allows GET and HEAD.
Test that a view implementing GET allows GET and HEAD.
def test_options_for_get_view(self): """ Test that a view implementing GET allows GET and HEAD. """ request = self.rf.options('/') view = SimpleView.as_view() response = view(request) self._assert_allows(response, 'GET', 'HEAD')
[ "def", "test_options_for_get_view", "(", "self", ")", ":", "request", "=", "self", ".", "rf", ".", "options", "(", "'/'", ")", "view", "=", "SimpleView", ".", "as_view", "(", ")", "response", "=", "view", "(", "request", ")", "self", ".", "_assert_allows...
[ 187, 4 ]
[ 194, 52 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_options_for_get_and_post_view
(self)
Test that a view implementing GET and POST allows GET, HEAD, and POST.
Test that a view implementing GET and POST allows GET, HEAD, and POST.
def test_options_for_get_and_post_view(self): """ Test that a view implementing GET and POST allows GET, HEAD, and POST. """ request = self.rf.options('/') view = SimplePostView.as_view() response = view(request) self._assert_allows(response, 'GET', 'HEAD', 'POST'...
[ "def", "test_options_for_get_and_post_view", "(", "self", ")", ":", "request", "=", "self", ".", "rf", ".", "options", "(", "'/'", ")", "view", "=", "SimplePostView", ".", "as_view", "(", ")", "response", "=", "view", "(", "request", ")", "self", ".", "_...
[ 196, 4 ]
[ 203, 60 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_options_for_post_view
(self)
Test that a view implementing POST allows POST.
Test that a view implementing POST allows POST.
def test_options_for_post_view(self): """ Test that a view implementing POST allows POST. """ request = self.rf.options('/') view = PostOnlyView.as_view() response = view(request) self._assert_allows(response, 'POST')
[ "def", "test_options_for_post_view", "(", "self", ")", ":", "request", "=", "self", ".", "rf", ".", "options", "(", "'/'", ")", "view", "=", "PostOnlyView", ".", "as_view", "(", ")", "response", "=", "view", "(", "request", ")", "self", ".", "_assert_all...
[ 205, 4 ]
[ 212, 45 ]
python
en
['en', 'error', 'th']
False
ViewTest._assert_allows
(self, response, *expected_methods)
Assert allowed HTTP methods reported in the Allow response header
Assert allowed HTTP methods reported in the Allow response header
def _assert_allows(self, response, *expected_methods): "Assert allowed HTTP methods reported in the Allow response header" response_allows = set(response['Allow'].split(', ')) self.assertEqual(set(expected_methods + ('OPTIONS',)), response_allows)
[ "def", "_assert_allows", "(", "self", ",", "response", ",", "*", "expected_methods", ")", ":", "response_allows", "=", "set", "(", "response", "[", "'Allow'", "]", ".", "split", "(", "', '", ")", ")", "self", ".", "assertEqual", "(", "set", "(", "expecte...
[ 214, 4 ]
[ 217, 79 ]
python
en
['en', 'en', 'en']
True
ViewTest.test_args_kwargs_request_on_self
(self)
Test a view only has args, kwargs & request once `as_view` has been called.
Test a view only has args, kwargs & request once `as_view` has been called.
def test_args_kwargs_request_on_self(self): """ Test a view only has args, kwargs & request once `as_view` has been called. """ bare_view = InstanceView() view = InstanceView.as_view()(self.rf.get('/')) for attribute in ('args', 'kwargs', 'request'): s...
[ "def", "test_args_kwargs_request_on_self", "(", "self", ")", ":", "bare_view", "=", "InstanceView", "(", ")", "view", "=", "InstanceView", ".", "as_view", "(", ")", "(", "self", ".", "rf", ".", "get", "(", "'/'", ")", ")", "for", "attribute", "in", "(", ...
[ 219, 4 ]
[ 228, 47 ]
python
en
['en', 'error', 'th']
False
ViewTest.test_direct_instantiation
(self)
It should be possible to use the view by directly instantiating it without going through .as_view() (#21564).
It should be possible to use the view by directly instantiating it without going through .as_view() (#21564).
def test_direct_instantiation(self): """ It should be possible to use the view by directly instantiating it without going through .as_view() (#21564). """ view = PostOnlyView() response = view.dispatch(self.rf.head('/')) self.assertEqual(response.status_code, 405)
[ "def", "test_direct_instantiation", "(", "self", ")", ":", "view", "=", "PostOnlyView", "(", ")", "response", "=", "view", ".", "dispatch", "(", "self", ".", "rf", ".", "head", "(", "'/'", ")", ")", "self", ".", "assertEqual", "(", "response", ".", "st...
[ 230, 4 ]
[ 237, 51 ]
python
en
['en', 'error', 'th']
False
SingleObjectTemplateResponseMixinTest.test_template_mixin_without_template
(self)
We want to makes sure that if you use a template mixin, but forget the template, it still tells you it's ImproperlyConfigured instead of TemplateDoesNotExist.
We want to makes sure that if you use a template mixin, but forget the template, it still tells you it's ImproperlyConfigured instead of TemplateDoesNotExist.
def test_template_mixin_without_template(self): """ We want to makes sure that if you use a template mixin, but forget the template, it still tells you it's ImproperlyConfigured instead of TemplateDoesNotExist. """ view = views.TemplateResponseWithoutTemplate() se...
[ "def", "test_template_mixin_without_template", "(", "self", ")", ":", "view", "=", "views", ".", "TemplateResponseWithoutTemplate", "(", ")", "self", ".", "assertRaises", "(", "ImproperlyConfigured", ",", "view", ".", "get_template_names", ")" ]
[ 493, 4 ]
[ 500, 72 ]
python
en
['en', 'error', 'th']
False
construct_instance
(form, instance, fields=None, exclude=None)
Constructs and returns a model instance from the bound ``form``'s ``cleaned_data``, but does not save the returned instance to the database.
Constructs and returns a model instance from the bound ``form``'s ``cleaned_data``, but does not save the returned instance to the database.
def construct_instance(form, instance, fields=None, exclude=None): """ Constructs and returns a model instance from the bound ``form``'s ``cleaned_data``, but does not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form....
[ "def", "construct_instance", "(", "form", ",", "instance", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "from", "django", ".", "db", "import", "models", "opts", "=", "instance", ".", "_meta", "cleaned_data", "=", "form", ".", "clean...
[ 35, 0 ]
[ 64, 19 ]
python
en
['en', 'error', 'th']
False
save_instance
(form, instance, fields=None, fail_message='saved', commit=True, exclude=None, construct=True)
Saves bound Form ``form``'s cleaned_data into model instance ``instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``instance``. If construct=False, assume ``instance`` has already been constructed and just needs to be saved.
Saves bound Form ``form``'s cleaned_data into model instance ``instance``.
def save_instance(form, instance, fields=None, fail_message='saved', commit=True, exclude=None, construct=True): """ Saves bound Form ``form``'s cleaned_data into model instance ``instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``ins...
[ "def", "save_instance", "(", "form", ",", "instance", ",", "fields", "=", "None", ",", "fail_message", "=", "'saved'", ",", "commit", "=", "True", ",", "exclude", "=", "None", ",", "construct", "=", "True", ")", ":", "if", "construct", ":", "instance", ...
[ 67, 0 ]
[ 108, 19 ]
python
en
['en', 'error', 'th']
False
model_to_dict
(instance, fields=None, exclude=None)
Returns a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ``exclude`` is an optional list of field names. If provided, t...
Returns a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument.
def model_to_dict(instance, fields=None, exclude=None): """ Returns a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned dict. ...
[ "def", "model_to_dict", "(", "instance", ",", "fields", "=", "None", ",", "exclude", "=", "None", ")", ":", "# avoid a circular import", "from", "django", ".", "db", ".", "models", ".", "fields", ".", "related", "import", "ManyToManyField", "opts", "=", "ins...
[ 113, 0 ]
[ 151, 15 ]
python
en
['en', 'error', 'th']
False
fields_for_model
(model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None)
Returns a ``OrderedDict`` containing form fields for the given model. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned fields. ``exclude`` is an optional list of field names. If provided, the named fields will be excluded from the ...
Returns a ``OrderedDict`` containing form fields for the given model.
def fields_for_model(model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None): """ Returns a ``OrderedDict`` containing form fields for the given model. ``fields`` is an optio...
[ "def", "fields_for_model", "(", "model", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "widgets", "=", "None", ",", "formfield_callback", "=", "None", ",", "localized_fields", "=", "None", ",", "labels", "=", "None", ",", "help_texts", "=",...
[ 154, 0 ]
[ 225, 21 ]
python
en
['en', 'error', 'th']
False
modelform_factory
(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None)
Returns a ModelForm containing form fields for the given model. ``fields`` is an optional list of field names. If provided, only the named fields will be included in the returned fields. If omitted or '__all__', all fields will be used. ``exclude`` is an optional list of field names. If provided,...
Returns a ModelForm containing form fields for the given model.
def modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None): """ Returns a ModelForm containing form fields for the given model. ``fields`...
[ "def", "modelform_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "formfield_callback", "=", "None", ",", "widgets", "=", "None", ",", "localized_fields", "=", "None", ",", "labels", "=",...
[ 471, 0 ]
[ 544, 60 ]
python
en
['en', 'error', 'th']
False
modelformset_factory
(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, lab...
Returns a FormSet class for the given Django model class.
Returns a FormSet class for the given Django model class.
def modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, ...
[ "def", "modelformset_factory", "(", "model", ",", "form", "=", "ModelForm", ",", "formfield_callback", "=", "None", ",", "formset", "=", "BaseModelFormSet", ",", "extra", "=", "1", ",", "can_delete", "=", "False", ",", "can_order", "=", "False", ",", "max_nu...
[ 812, 0 ]
[ 839, 18 ]
python
en
['en', 'error', 'th']
False
_get_foreign_key
(parent_model, model, fk_name=None, can_fail=False)
Finds and returns the ForeignKey from model to parent if there is one (returns None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, an exception is raised if there is no ForeignKey from model to parent_mo...
Finds and returns the ForeignKey from model to parent if there is one (returns None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is True, an exception is raised if there is no ForeignKey from model to parent_mo...
def _get_foreign_key(parent_model, model, fk_name=None, can_fail=False): """ Finds and returns the ForeignKey from model to parent if there is one (returns None if can_fail is True and no such field exists). If fk_name is provided, assume it is the name of the ForeignKey field. Unless can_fail is Tr...
[ "def", "_get_foreign_key", "(", "parent_model", ",", "model", ",", "fk_name", "=", "None", ",", "can_fail", "=", "False", ")", ":", "# avoid circular import", "from", "django", ".", "db", ".", "models", "import", "ForeignKey", "opts", "=", "model", ".", "_me...
[ 932, 0 ]
[ 987, 13 ]
python
en
['en', 'error', 'th']
False
inlineformset_factory
(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=F...
Returns an ``InlineFormSet`` for the given kwargs. You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey`` to ``parent_model``.
Returns an ``InlineFormSet`` for the given kwargs.
def inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, wid...
[ "def", "inlineformset_factory", "(", "parent_model", ",", "model", ",", "form", "=", "ModelForm", ",", "formset", "=", "BaseInlineFormSet", ",", "fk_name", "=", "None", ",", "fields", "=", "None", ",", "exclude", "=", "None", ",", "extra", "=", "3", ",", ...
[ 990, 0 ]
[ 1028, 18 ]
python
en
['en', 'error', 'th']
False
BaseModelForm._get_validation_exclusions
(self)
For backwards-compatibility, several types of fields need to be excluded from model validation. See the following tickets for details: #12507, #12521, #12553
For backwards-compatibility, several types of fields need to be excluded from model validation. See the following tickets for details: #12507, #12521, #12553
def _get_validation_exclusions(self): """ For backwards-compatibility, several types of fields need to be excluded from model validation. See the following tickets for details: #12507, #12521, #12553 """ exclude = [] # Build up a list of fields that should be excl...
[ "def", "_get_validation_exclusions", "(", "self", ")", ":", "exclude", "=", "[", "]", "# Build up a list of fields that should be excluded from model field", "# validation and unique checks.", "for", "f", "in", "self", ".", "instance", ".", "_meta", ".", "fields", ":", ...
[ 337, 4 ]
[ 377, 22 ]
python
en
['en', 'error', 'th']
False
BaseModelForm.validate_unique
(self)
Calls the instance's validate_unique() method and updates the form's validation errors if any were raised.
Calls the instance's validate_unique() method and updates the form's validation errors if any were raised.
def validate_unique(self): """ Calls the instance's validate_unique() method and updates the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except Validat...
[ "def", "validate_unique", "(", "self", ")", ":", "exclude", "=", "self", ".", "_get_validation_exclusions", "(", ")", "try", ":", "self", ".", "instance", ".", "validate_unique", "(", "exclude", "=", "exclude", ")", "except", "ValidationError", "as", "e", ":...
[ 437, 4 ]
[ 446, 34 ]
python
en
['en', 'error', 'th']
False
BaseModelForm.save
(self, commit=True)
Saves this ``form``'s cleaned_data into model instance ``self.instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``instance``.
Saves this ``form``'s cleaned_data into model instance ``self.instance``.
def save(self, commit=True): """ Saves this ``form``'s cleaned_data into model instance ``self.instance``. If commit=True, then the changes to ``instance`` will be saved to the database. Returns ``instance``. """ if self.instance.pk is None: fail_mess...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "self", ".", "instance", ".", "pk", "is", "None", ":", "fail_message", "=", "'created'", "else", ":", "fail_message", "=", "'changed'", "return", "save_instance", "(", "self", ",", ...
[ 448, 4 ]
[ 462, 45 ]
python
en
['en', 'error', 'th']
False
BaseModelFormSet.initial_form_count
(self)
Returns the number of forms that are required in this FormSet.
Returns the number of forms that are required in this FormSet.
def initial_form_count(self): """Returns the number of forms that are required in this FormSet.""" if not (self.data or self.files): return len(self.get_queryset()) return super(BaseModelFormSet, self).initial_form_count()
[ "def", "initial_form_count", "(", "self", ")", ":", "if", "not", "(", "self", ".", "data", "or", "self", ".", "files", ")", ":", "return", "len", "(", "self", ".", "get_queryset", "(", ")", ")", "return", "super", "(", "BaseModelFormSet", ",", "self", ...
[ 563, 4 ]
[ 567, 65 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet._get_to_python
(self, field)
If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) get_prep_value.
If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) get_prep_value.
def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) get_prep_value. """ while field.rel is not None: field = field.rel.get_related_field() return field.to_python
[ "def", "_get_to_python", "(", "self", ",", "field", ")", ":", "while", "field", ".", "rel", "is", "not", "None", ":", "field", "=", "field", ".", "rel", ".", "get_related_field", "(", ")", "return", "field", ".", "to_python" ]
[ 574, 4 ]
[ 581, 30 ]
python
en
['en', 'error', 'th']
False
BaseModelFormSet.save_new
(self, form, commit=True)
Saves and returns a new model instance for the given form.
Saves and returns a new model instance for the given form.
def save_new(self, form, commit=True): """Saves and returns a new model instance for the given form.""" return form.save(commit=commit)
[ "def", "save_new", "(", "self", ",", "form", ",", "commit", "=", "True", ")", ":", "return", "form", ".", "save", "(", "commit", "=", "commit", ")" ]
[ 620, 4 ]
[ 622, 39 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.save_existing
(self, form, instance, commit=True)
Saves and returns an existing model instance for the given form.
Saves and returns an existing model instance for the given form.
def save_existing(self, form, instance, commit=True): """Saves and returns an existing model instance for the given form.""" return form.save(commit=commit)
[ "def", "save_existing", "(", "self", ",", "form", ",", "instance", ",", "commit", "=", "True", ")", ":", "return", "form", ".", "save", "(", "commit", "=", "commit", ")" ]
[ 624, 4 ]
[ 626, 39 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.save
(self, commit=True)
Saves model instances for every form, adding and changing instances as necessary, and returns the list of instances.
Saves model instances for every form, adding and changing instances as necessary, and returns the list of instances.
def save(self, commit=True): """Saves model instances for every form, adding and changing instances as necessary, and returns the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: ...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "not", "commit", ":", "self", ".", "saved_forms", "=", "[", "]", "def", "save_m2m", "(", ")", ":", "for", "form", "in", "self", ".", "saved_forms", ":", "form", ".", "save_m2m"...
[ 628, 4 ]
[ 639, 81 ]
python
en
['en', 'en', 'en']
True
BaseModelFormSet.add_fields
(self, form, index)
Add a hidden field for the object's primary key.
Add a hidden field for the object's primary key.
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it her...
[ "def", "add_fields", "(", "self", ",", "form", ",", "index", ")", ":", "from", "django", ".", "db", ".", "models", "import", "AutoField", ",", "OneToOneField", ",", "ForeignKey", "self", ".", "_pk_field", "=", "pk", "=", "self", ".", "model", ".", "_me...
[ 775, 4 ]
[ 809, 61 ]
python
en
['en', 'en', 'en']
True
ModelChoiceField.label_from_instance
(self, obj)
This method is used to convert objects into strings; it's used to generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices.
This method is used to convert objects into strings; it's used to generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices.
def label_from_instance(self, obj): """ This method is used to convert objects into strings; it's used to generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return smart_text(obj)
[ "def", "label_from_instance", "(", "self", ",", "obj", ")", ":", "return", "smart_text", "(", "obj", ")" ]
[ 1152, 4 ]
[ 1158, 30 ]
python
en
['en', 'error', 'th']
False
Marker.evaluate
(self, environment=None)
Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process.
Evaluate a marker.
def evaluate(self, environment=None): # type: (Optional[Dict[str, str]]) -> bool """Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. ...
[ "def", "evaluate", "(", "self", ",", "environment", "=", "None", ")", ":", "# type: (Optional[Dict[str, str]]) -> bool", "current_environment", "=", "default_environment", "(", ")", "if", "environment", "is", "not", "None", ":", "current_environment", ".", "update", ...
[ 313, 4 ]
[ 327, 68 ]
python
en
['en', 'en', 'en']
True
safe_join
(base, *paths)
Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path. Raise ValueError if the final path isn't located inside of the base path component.
Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path.
def safe_join(base, *paths): """ Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path. Raise ValueError if the final path isn't located inside of the base path component. """ final_path = abspath(join(base, *paths...
[ "def", "safe_join", "(", "base", ",", "*", "paths", ")", ":", "final_path", "=", "abspath", "(", "join", "(", "base", ",", "*", "paths", ")", ")", "base_path", "=", "abspath", "(", "base", ")", "# Ensure final_path starts with base_path (using normcase to ensure...
[ 8, 0 ]
[ 31, 21 ]
python
en
['en', 'error', 'th']
False
symlinks_supported
()
Return whether or not creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions).
Return whether or not creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions).
def symlinks_supported(): """ Return whether or not creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions). """ with tempfile.TemporaryDirectory() as temp_dir: original_path = os.path.join(temp_dir, 'o...
[ "def", "symlinks_supported", "(", ")", ":", "with", "tempfile", ".", "TemporaryDirectory", "(", ")", "as", "temp_dir", ":", "original_path", "=", "os", ".", "path", ".", "join", "(", "temp_dir", ",", "'original'", ")", "symlink_path", "=", "os", ".", "path...
[ 34, 0 ]
[ 49, 24 ]
python
en
['en', 'error', 'th']
False
to_path
(value)
Convert value to a pathlib.Path instance, if not already a Path.
Convert value to a pathlib.Path instance, if not already a Path.
def to_path(value): """Convert value to a pathlib.Path instance, if not already a Path.""" if isinstance(value, Path): return value elif not isinstance(value, str): raise TypeError('Invalid path type: %s' % type(value).__name__) return Path(value)
[ "def", "to_path", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Path", ")", ":", "return", "value", "elif", "not", "isinstance", "(", "value", ",", "str", ")", ":", "raise", "TypeError", "(", "'Invalid path type: %s'", "%", "type", "(",...
[ 52, 0 ]
[ 58, 22 ]
python
en
['en', 'en', 'en']
True
Command.fetch_viewpoints
(self, base_url)
Populate accessibility viewpoints from the accessibility API
Populate accessibility viewpoints from the accessibility API
def fetch_viewpoints(self, base_url): """ Populate accessibility viewpoints from the accessibility API """ url = '{}/api/v1/accessibility/viewpoints'.format(base_url) data = self.make_request(url) vp_ids = [] for viewpoint_data in data: vp_id = viewpoint_data['viewpo...
[ "def", "fetch_viewpoints", "(", "self", ",", "base_url", ")", ":", "url", "=", "'{}/api/v1/accessibility/viewpoints'", ".", "format", "(", "base_url", ")", "data", "=", "self", ".", "make_request", "(", "url", ")", "vp_ids", "=", "[", "]", "for", "viewpoint_...
[ 42, 4 ]
[ 76, 70 ]
python
en
['en', 'en', 'en']
True
Command.fetch_resource_accessibility_data
(self, base_url)
Populate resource accessibility data from the accessibility API
Populate resource accessibility data from the accessibility API
def fetch_resource_accessibility_data(self, base_url): """ Populate resource accessibility data from the accessibility API """ url = "{base_url}/api/v1/accessibility/targets/{system_id}/summary".format( base_url=base_url, system_id=settings.RESPA_ACCESSIBILITY_API_SYSTEM_ID) data = s...
[ "def", "fetch_resource_accessibility_data", "(", "self", ",", "base_url", ")", ":", "url", "=", "\"{base_url}/api/v1/accessibility/targets/{system_id}/summary\"", ".", "format", "(", "base_url", "=", "base_url", ",", "system_id", "=", "settings", ".", "RESPA_ACCESSIBILITY...
[ 78, 4 ]
[ 113, 22 ]
python
en
['en', 'en', 'en']
True
Command.fetch_unit_accessibility_data
(self, base_url)
Populate unit accessibility data from the accessibility API. Requests only servicepoints we have, the api contains lots of stuff we don't care about.
Populate unit accessibility data from the accessibility API. Requests only servicepoints we have, the api contains lots of stuff we don't care about.
def fetch_unit_accessibility_data(self, base_url): """ Populate unit accessibility data from the accessibility API. Requests only servicepoints we have, the api contains lots of stuff we don't care about. """ url = "{base_url}/api/v1/accessibility/servicepoints/{system_id}/{{servicep...
[ "def", "fetch_unit_accessibility_data", "(", "self", ",", "base_url", ")", ":", "url", "=", "\"{base_url}/api/v1/accessibility/servicepoints/{system_id}/{{servicepoint_id}}/summary\"", ".", "format", "(", "base_url", "=", "base_url", ",", "system_id", "=", "settings", ".", ...
[ 115, 4 ]
[ 156, 26 ]
python
en
['en', 'en', 'en']
True
Command.get_or_create_value
(self, value_data)
Accessibility API represents accessibility summaries in words like "red", "green" default ordering levels set here are - green: 10 - unknown: 0 - red: -10 These can be changed later in django admin. Resources which don't have data in Accessibility database are considered...
Accessibility API represents accessibility summaries in words like "red", "green" default ordering levels set here are - green: 10 - unknown: 0 - red: -10
def get_or_create_value(self, value_data): """Accessibility API represents accessibility summaries in words like "red", "green" default ordering levels set here are - green: 10 - unknown: 0 - red: -10 These can be changed later in django admin. Resources which don't have...
[ "def", "get_or_create_value", "(", "self", ",", "value_data", ")", ":", "accessibility_value", ",", "created", "=", "AccessibilityValue", ".", "objects", ".", "get_or_create", "(", "value", "=", "value_data", ")", "if", "created", ":", "if", "accessibility_value",...
[ 170, 4 ]
[ 188, 34 ]
python
en
['en', 'en', 'en']
True
MigrationAutodetector.changes
(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None)
Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed)
Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed)
def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes ...
[ "def", "changes", "(", "self", ",", "graph", ",", "trim_to_apps", "=", "None", ",", "convert_apps", "=", "None", ",", "migration_name", "=", "None", ")", ":", "changes", "=", "self", ".", "_detect_changes", "(", "convert_apps", ",", "graph", ")", "changes"...
[ 36, 4 ]
[ 46, 22 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.deep_deconstruct
(self, obj)
Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly.
Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly.
def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstr...
[ "def", "deep_deconstruct", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "self", ".", "deep_deconstruct", "(", "value", ")", "for", "value", "in", "obj", "]", "elif", "isinstance", "(", "obj", ...
[ 48, 4 ]
[ 86, 22 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.only_relation_agnostic_fields
(self, fields)
Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as, of course, the related fields change during renames).
Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as, of course, the related fields change during renames).
def only_relation_agnostic_fields(self, fields): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as, of course, the related fields change during renames). """ fields_def = [] fo...
[ "def", "only_relation_agnostic_fields", "(", "self", ",", "fields", ")", ":", "fields_def", "=", "[", "]", "for", "name", ",", "field", "in", "sorted", "(", "fields", ")", ":", "deconstruction", "=", "self", ".", "deep_deconstruct", "(", "field", ")", "if"...
[ 88, 4 ]
[ 100, 25 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._detect_changes
(self, convert_apps=None, graph=None)
Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. con...
Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values.
def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the ...
[ "def", "_detect_changes", "(", "self", ",", "convert_apps", "=", "None", ",", "graph", "=", "None", ")", ":", "# The first phase is generating all the operations for each app", "# and gathering them into a big per-app list.", "# Then go through that list, order it, and split into mig...
[ 102, 4 ]
[ 197, 30 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._prepare_field_lists
(self)
Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it.
Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it.
def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_mode...
[ "def", "_prepare_field_lists", "(", "self", ")", ":", "self", ".", "kept_model_keys", "=", "self", ".", "old_model_keys", "&", "self", ".", "new_model_keys", "self", ".", "kept_proxy_keys", "=", "self", ".", "old_proxy_keys", "&", "self", ".", "new_proxy_keys", ...
[ 199, 4 ]
[ 221, 9 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._generate_through_model_map
(self)
Through model map generation.
Through model map generation.
def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_state = self.from_state.models[app_label, old_model_name] ...
[ "def", "_generate_through_model_map", "(", "self", ")", ":", "for", "app_label", ",", "model_name", "in", "sorted", "(", "self", ".", "old_model_keys", ")", ":", "old_model_name", "=", "self", ".", "renamed_models", ".", "get", "(", "(", "app_label", ",", "m...
[ 223, 4 ]
[ 236, 93 ]
python
en
['en', 'ja', 'en']
True
MigrationAutodetector._resolve_dependency
(dependency)
Return the resolved dependency and a boolean denoting whether or not it was swappable.
Return the resolved dependency and a boolean denoting whether or not it was swappable.
def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != '__setting__': return dependency, False resolved_app_label, resolved_object_name = getattr(settings, depende...
[ "def", "_resolve_dependency", "(", "dependency", ")", ":", "if", "dependency", "[", "0", "]", "!=", "'__setting__'", ":", "return", "dependency", ",", "False", "resolved_app_label", ",", "resolved_object_name", "=", "getattr", "(", "settings", ",", "dependency", ...
[ 239, 4 ]
[ 247, 88 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._build_migration_list
(self, graph=None)
Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off th...
Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off th...
def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (has...
[ "def", "_build_migration_list", "(", "self", ",", "graph", "=", "None", ")", ":", "self", ".", "migrations", "=", "{", "}", "num_ops", "=", "sum", "(", "len", "(", "x", ")", "for", "x", "in", "self", ".", "generated_operations", ".", "values", "(", "...
[ 249, 4 ]
[ 334, 33 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._sort_migrations
(self)
Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app.
Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app.
def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): # construct a dependency graph for intra-app dependencies ...
[ "def", "_sort_migrations", "(", "self", ")", ":", "for", "app_label", ",", "ops", "in", "sorted", "(", "self", ".", "generated_operations", ".", "items", "(", ")", ")", ":", "# construct a dependency graph for intra-app dependencies", "dependency_graph", "=", "{", ...
[ 336, 4 ]
[ 355, 97 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.check_dependency
(self, operation, dependency)
Return True if the given operation depends on the given dependency, False otherwise.
Return True if the given operation depends on the given dependency, False otherwise.
def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, o...
[ "def", "check_dependency", "(", "self", ",", "operation", ",", "dependency", ")", ":", "# Created model", "if", "dependency", "[", "2", "]", "is", "None", "and", "dependency", "[", "3", "]", "is", "True", ":", "return", "(", "isinstance", "(", "operation",...
[ 373, 4 ]
[ 434, 74 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.swappable_first_key
(self, item)
Place potential swappable models first in lists of created models (only real way to solve #22783).
Place potential swappable models first in lists of created models (only real way to solve #22783).
def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model = self.new_apps.get_model(item[0], item[1]) base_names = [base.__name__ for base in model.__bases__] ...
[ "def", "swappable_first_key", "(", "self", ",", "item", ")", ":", "try", ":", "model", "=", "self", ".", "new_apps", ".", "get_model", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ")", "base_names", "=", "[", "base", ".", "__name__", "fo...
[ 444, 4 ]
[ 462, 19 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_renamed_models
(self)
Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation.
Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation.
def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} adde...
[ "def", "generate_renamed_models", "(", "self", ")", ":", "self", ".", "renamed_models", "=", "{", "}", "self", ".", "renamed_models_rel", "=", "{", "}", "added_models", "=", "self", ".", "new_model_keys", "-", "self", ".", "old_model_keys", "for", "app_label",...
[ 464, 4 ]
[ 505, 33 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_created_models
(self)
Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might ...
Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible).
def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options tha...
[ "def", "generate_created_models", "(", "self", ")", ":", "old_keys", "=", "self", ".", "old_model_keys", "|", "self", ".", "old_unmanaged_keys", "added_models", "=", "self", ".", "new_model_keys", "-", "old_keys", "added_unmanaged_models", "=", "self", ".", "new_u...
[ 507, 4 ]
[ 670, 21 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_created_proxies
(self)
Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but of course for proxy models it's safe to skip all the pointless field stuff and just chuck out an operation.
Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but of course for proxy models it's safe to skip all the pointless field stuff and just chuck out an operation.
def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but of course for proxy models it's safe to skip all the pointless field stuff and just chuck out an operation. """ ...
[ "def", "generate_created_proxies", "(", "self", ")", ":", "added", "=", "self", ".", "new_proxy_keys", "-", "self", ".", "old_proxy_keys", "for", "app_label", ",", "model_name", "in", "sorted", "(", "added", ")", ":", "model_state", "=", "self", ".", "to_sta...
[ 672, 4 ]
[ 704, 13 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_deleted_models
(self)
Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to coll...
Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible).
def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal o...
[ "def", "generate_deleted_models", "(", "self", ")", ":", "new_keys", "=", "self", ".", "new_model_keys", "|", "self", ".", "new_unmanaged_keys", "deleted_models", "=", "self", ".", "old_model_keys", "-", "new_keys", "deleted_unmanaged_models", "=", "self", ".", "o...
[ 706, 4 ]
[ 793, 13 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_deleted_proxies
(self)
Make DeleteModel options for proxy models.
Make DeleteModel options for proxy models.
def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.ge...
[ "def", "generate_deleted_proxies", "(", "self", ")", ":", "deleted", "=", "self", ".", "old_proxy_keys", "-", "self", ".", "new_proxy_keys", "for", "app_label", ",", "model_name", "in", "sorted", "(", "deleted", ")", ":", "model_state", "=", "self", ".", "fr...
[ 795, 4 ]
[ 806, 13 ]
python
en
['en', 'da', 'en']
True
MigrationAutodetector.generate_renamed_fields
(self)
Work out renamed fields.
Work out renamed fields.
def generate_renamed_fields(self): """Work out renamed fields.""" self.renamed_fields = {} for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys): old_model_name = self.renamed_models.get((app_label, model_name), model_name) old_model_s...
[ "def", "generate_renamed_fields", "(", "self", ")", ":", "self", ".", "renamed_fields", "=", "{", "}", "for", "app_label", ",", "model_name", ",", "field_name", "in", "sorted", "(", "self", ".", "new_field_keys", "-", "self", ".", "old_field_keys", ")", ":",...
[ 808, 4 ]
[ 844, 33 ]
python
en
['en', 'en', 'en']
True
MigrationAutodetector.generate_added_fields
(self)
Make AddField operations.
Make AddField operations.
def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted(self.new_field_keys - self.old_field_keys): self._generate_added_field(app_label, model_name, field_name)
[ "def", "generate_added_fields", "(", "self", ")", ":", "for", "app_label", ",", "model_name", ",", "field_name", "in", "sorted", "(", "self", ".", "new_field_keys", "-", "self", ".", "old_field_keys", ")", ":", "self", ".", "_generate_added_field", "(", "app_l...
[ 846, 4 ]
[ 849, 73 ]
python
en
['en', 'ny', 'en']
True
MigrationAutodetector.generate_removed_fields
(self)
Make RemoveField operations.
Make RemoveField operations.
def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted(self.old_field_keys - self.new_field_keys): self._generate_removed_field(app_label, model_name, field_name)
[ "def", "generate_removed_fields", "(", "self", ")", ":", "for", "app_label", ",", "model_name", ",", "field_name", "in", "sorted", "(", "self", ".", "old_field_keys", "-", "self", ".", "new_field_keys", ")", ":", "self", ".", "_generate_removed_field", "(", "a...
[ 882, 4 ]
[ 885, 75 ]
python
en
['en', 'en', 'en']
True
MigrationAutodetector.generate_altered_fields
(self)
Make AlterField operations, or possibly RemovedField/AddField if alter isn's possible.
Make AlterField operations, or possibly RemovedField/AddField if alter isn's possible.
def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn's possible. """ for app_label, model_name, field_name in sorted(self.old_field_keys & self.new_field_keys): # Did the field change? old_model_...
[ "def", "generate_altered_fields", "(", "self", ")", ":", "for", "app_label", ",", "model_name", ",", "field_name", "in", "sorted", "(", "self", ".", "old_field_keys", "&", "self", ".", "new_field_keys", ")", ":", "# Did the field change?", "old_model_name", "=", ...
[ 903, 4 ]
[ 984, 81 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.generate_altered_options
(self)
Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them).
Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them).
def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.ke...
[ "def", "generate_altered_options", "(", "self", ")", ":", "models_to_check", "=", "self", ".", "kept_model_keys", ".", "union", "(", "self", ".", "kept_proxy_keys", ",", "self", ".", "kept_unmanaged_keys", ",", "# unmanaged converted to managed", "self", ".", "old_u...
[ 1145, 4 ]
[ 1179, 17 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.arrange_for_graph
(self, changes, graph, migration_name=None)
Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app.
Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app.
def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() na...
[ "def", "arrange_for_graph", "(", "self", ",", "changes", ",", "graph", ",", "migration_name", "=", "None", ")", ":", "leaves", "=", "graph", ".", "leaf_nodes", "(", ")", "name_map", "=", "{", "}", "for", "app_label", ",", "migrations", "in", "list", "(",...
[ 1222, 4 ]
[ 1269, 22 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector._trim_to_apps
(self, changes, app_labels)
Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies.
Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies.
def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as t...
[ "def", "_trim_to_apps", "(", "self", ",", "changes", ",", "app_labels", ")", ":", "# Gather other app dependencies in a first pass", "app_dependencies", "=", "{", "}", "for", "app_label", ",", "migrations", "in", "changes", ".", "items", "(", ")", ":", "for", "m...
[ 1271, 4 ]
[ 1294, 22 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.suggest_name
(cls, ops)
Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible.
Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible.
def suggest_name(cls, ops): """ Given a set of operations, suggest a name for the migration they might represent. Names are not guaranteed to be unique, but put some effort into the fallback name to avoid VCS conflicts if possible. """ if len(ops) == 1: if isi...
[ "def", "suggest_name", "(", "cls", ",", "ops", ")", ":", "if", "len", "(", "ops", ")", "==", "1", ":", "if", "isinstance", "(", "ops", "[", "0", "]", ",", "operations", ".", "CreateModel", ")", ":", "return", "ops", "[", "0", "]", ".", "name_lowe...
[ 1297, 4 ]
[ 1315, 57 ]
python
en
['en', 'error', 'th']
False
MigrationAutodetector.parse_number
(cls, name)
Given a migration name, try to extract a number from the beginning of it. If no number is found, return None.
Given a migration name, try to extract a number from the beginning of it. If no number is found, return None.
def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. If no number is found, return None. """ match = re.match(r'^\d+', name) if match: return int(match.group()) return None
[ "def", "parse_number", "(", "cls", ",", "name", ")", ":", "match", "=", "re", ".", "match", "(", "r'^\\d+'", ",", "name", ")", "if", "match", ":", "return", "int", "(", "match", ".", "group", "(", ")", ")", "return", "None" ]
[ 1318, 4 ]
[ 1326, 19 ]
python
en
['en', 'error', 'th']
False
Operation.deconstruct
(self)
Return a 3-tuple of class import path (or just name if it lives under django.db.migrations), positional arguments, and keyword arguments.
Return a 3-tuple of class import path (or just name if it lives under django.db.migrations), positional arguments, and keyword arguments.
def deconstruct(self): """ Return a 3-tuple of class import path (or just name if it lives under django.db.migrations), positional arguments, and keyword arguments. """ return ( self.__class__.__name__, self._constructor_args[0], self._...
[ "def", "deconstruct", "(", "self", ")", ":", "return", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "_constructor_args", "[", "0", "]", ",", "self", ".", "_constructor_args", "[", "1", "]", ",", ")" ]
[ 42, 4 ]
[ 52, 9 ]
python
en
['en', 'error', 'th']
False
Operation.state_forwards
(self, app_label, state)
Take the state from the previous migration, and mutate it so that it matches what this migration would perform.
Take the state from the previous migration, and mutate it so that it matches what this migration would perform.
def state_forwards(self, app_label, state): """ Take the state from the previous migration, and mutate it so that it matches what this migration would perform. """ raise NotImplementedError('subclasses of Operation must provide a state_forwards() method')
[ "def", "state_forwards", "(", "self", ",", "app_label", ",", "state", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Operation must provide a state_forwards() method'", ")" ]
[ 54, 4 ]
[ 59, 99 ]
python
en
['en', 'error', 'th']
False
Operation.database_forwards
(self, app_label, schema_editor, from_state, to_state)
Perform the mutation on the database schema in the normal (forwards) direction.
Perform the mutation on the database schema in the normal (forwards) direction.
def database_forwards(self, app_label, schema_editor, from_state, to_state): """ Perform the mutation on the database schema in the normal (forwards) direction. """ raise NotImplementedError('subclasses of Operation must provide a database_forwards() method')
[ "def", "database_forwards", "(", "self", ",", "app_label", ",", "schema_editor", ",", "from_state", ",", "to_state", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Operation must provide a database_forwards() method'", ")" ]
[ 61, 4 ]
[ 66, 102 ]
python
en
['en', 'error', 'th']
False
Operation.database_backwards
(self, app_label, schema_editor, from_state, to_state)
Perform the mutation on the database schema in the reverse direction - e.g. if this were CreateModel, it would in fact drop the model's table.
Perform the mutation on the database schema in the reverse direction - e.g. if this were CreateModel, it would in fact drop the model's table.
def database_backwards(self, app_label, schema_editor, from_state, to_state): """ Perform the mutation on the database schema in the reverse direction - e.g. if this were CreateModel, it would in fact drop the model's table. """ raise NotImplementedError('subclasses of Op...
[ "def", "database_backwards", "(", "self", ",", "app_label", ",", "schema_editor", ",", "from_state", ",", "to_state", ")", ":", "raise", "NotImplementedError", "(", "'subclasses of Operation must provide a database_backwards() method'", ")" ]
[ 68, 4 ]
[ 74, 103 ]
python
en
['en', 'error', 'th']
False
Operation.describe
(self)
Output a brief summary of what the action does.
Output a brief summary of what the action does.
def describe(self): """ Output a brief summary of what the action does. """ return "%s: %s" % (self.__class__.__name__, self._constructor_args)
[ "def", "describe", "(", "self", ")", ":", "return", "\"%s: %s\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "_constructor_args", ")" ]
[ 76, 4 ]
[ 80, 75 ]
python
en
['en', 'error', 'th']
False
Operation.references_model
(self, name, app_label=None)
Return True if there is a chance this operation references the given model name (as a string), with an optional app label for accuracy. Used for optimization. If in doubt, return True; returning a false positive will merely make the optimizer a little less efficient, while retu...
Return True if there is a chance this operation references the given model name (as a string), with an optional app label for accuracy.
def references_model(self, name, app_label=None): """ Return True if there is a chance this operation references the given model name (as a string), with an optional app label for accuracy. Used for optimization. If in doubt, return True; returning a false positive will merely m...
[ "def", "references_model", "(", "self", ",", "name", ",", "app_label", "=", "None", ")", ":", "return", "True" ]
[ 82, 4 ]
[ 92, 19 ]
python
en
['en', 'error', 'th']
False
Operation.references_field
(self, model_name, name, app_label=None)
Return True if there is a chance this operation references the given field name, with an optional app label for accuracy. Used for optimization. If in doubt, return True.
Return True if there is a chance this operation references the given field name, with an optional app label for accuracy.
def references_field(self, model_name, name, app_label=None): """ Return True if there is a chance this operation references the given field name, with an optional app label for accuracy. Used for optimization. If in doubt, return True. """ return self.references_model(m...
[ "def", "references_field", "(", "self", ",", "model_name", ",", "name", ",", "app_label", "=", "None", ")", ":", "return", "self", ".", "references_model", "(", "model_name", ",", "app_label", ")" ]
[ 94, 4 ]
[ 101, 59 ]
python
en
['en', 'error', 'th']
False
Operation.allow_migrate_model
(self, connection_alias, model)
Return whether or not a model may be migrated. This is a thin wrapper around router.allow_migrate_model() that preemptively rejects any proxy, swapped out, or unmanaged model.
Return whether or not a model may be migrated.
def allow_migrate_model(self, connection_alias, model): """ Return whether or not a model may be migrated. This is a thin wrapper around router.allow_migrate_model() that preemptively rejects any proxy, swapped out, or unmanaged model. """ if not model._meta.can_migrate(...
[ "def", "allow_migrate_model", "(", "self", ",", "connection_alias", ",", "model", ")", ":", "if", "not", "model", ".", "_meta", ".", "can_migrate", "(", "connection_alias", ")", ":", "return", "False", "return", "router", ".", "allow_migrate_model", "(", "conn...
[ 103, 4 ]
[ 113, 66 ]
python
en
['en', 'error', 'th']
False
Operation.reduce
(self, operation, app_label=None)
Return either a list of operations the actual operation should be replaced with or a boolean that indicates whether or not the specified operation can be optimized across.
Return either a list of operations the actual operation should be replaced with or a boolean that indicates whether or not the specified operation can be optimized across.
def reduce(self, operation, app_label=None): """ Return either a list of operations the actual operation should be replaced with or a boolean that indicates whether or not the specified operation can be optimized across. """ if self.elidable: return [operation...
[ "def", "reduce", "(", "self", ",", "operation", ",", "app_label", "=", "None", ")", ":", "if", "self", ".", "elidable", ":", "return", "[", "operation", "]", "elif", "operation", ".", "elidable", ":", "return", "[", "self", "]", "return", "False" ]
[ 115, 4 ]
[ 125, 20 ]
python
en
['en', 'error', 'th']
False
literals
(choices, prefix="", suffix="")
Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually.
Create a regex from a space-separated list of literal `choices`.
def literals(choices, prefix="", suffix=""): """ Create a regex from a space-separated list of literal `choices`. If provided, `prefix` and `suffix` will be attached to each choice individually. """ return "|".join(prefix + re.escape(c) + suffix for c in choices.split())
[ "def", "literals", "(", "choices", ",", "prefix", "=", "\"\"", ",", "suffix", "=", "\"\"", ")", ":", "return", "\"|\"", ".", "join", "(", "prefix", "+", "re", ".", "escape", "(", "c", ")", "+", "suffix", "for", "c", "in", "choices", ".", "split", ...
[ 19, 0 ]
[ 26, 76 ]
python
en
['en', 'error', 'th']
False
prepare_js_for_gettext
(js)
Convert the Javascript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX".
Convert the Javascript source `js` into something resembling C for xgettext.
def prepare_js_for_gettext(js): """ Convert the Javascript source `js` into something resembling C for xgettext. What actually happens is that all the regex literals are replaced with "REGEX". """ def escape_quotes(m): """Used in a regex to properly escape double quotes.""" ...
[ "def", "prepare_js_for_gettext", "(", "js", ")", ":", "def", "escape_quotes", "(", "m", ")", ":", "\"\"\"Used in a regex to properly escape double quotes.\"\"\"", "s", "=", "m", ".", "group", "(", "0", ")", "if", "s", "==", "'\"'", ":", "return", "r'\\\"'", "e...
[ 184, 0 ]
[ 219, 21 ]
python
en
['en', 'error', 'th']
False
Lexer.lex
(self, text)
Lexically analyze `text`. Yield pairs (`name`, `tokentext`).
Lexically analyze `text`.
def lex(self, text): """ Lexically analyze `text`. Yield pairs (`name`, `tokentext`). """ end = len(text) state = self.state regexes = self.regexes toks = self.toks start = 0 while start < end: for match in regexes[state].find...
[ "def", "lex", "(", "self", ",", "text", ")", ":", "end", "=", "len", "(", "text", ")", "state", "=", "self", ".", "state", "regexes", "=", "self", ".", "regexes", "toks", "=", "self", ".", "toks", "start", "=", "0", "while", "start", "<", "end", ...
[ 48, 4 ]
[ 72, 26 ]
python
en
['en', 'error', 'th']
False
test_get_price_correct
(order_with_products)
Test price calculation returns the correct combined sum for products Two hour reservation of two order lines with a price of 10, where one product has an hourly rate and one is with a fixed price, plus individual product tax of 24% should equal 37.20
Test price calculation returns the correct combined sum for products
def test_get_price_correct(order_with_products): """Test price calculation returns the correct combined sum for products Two hour reservation of two order lines with a price of 10, where one product has an hourly rate and one is with a fixed price, plus individual product tax of 24% should equal 37.20"...
[ "def", "test_get_price_correct", "(", "order_with_products", ")", ":", "price", "=", "order_with_products", ".", "get_price", "(", ")", "assert", "price", "==", "Decimal", "(", "'37.20'", ")" ]
[ 16, 0 ]
[ 23, 36 ]
python
en
['en', 'en', 'en']
True
EmailBackend._get_filename
(self)
Return a unique file name.
Return a unique file name.
def _get_filename(self): """Return a unique file name.""" if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") fname = "%s-%s.log" % (timestamp, abs(id(self))) self._fname = os.path.join(self.file_path, fname) return self._fnam...
[ "def", "_get_filename", "(", "self", ")", ":", "if", "self", ".", "_fname", "is", "None", ":", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d-%H%M%S\"", ")", "fname", "=", "\"%s-%s.log\"", "%", "(", ...
[ 47, 4 ]
[ 53, 26 ]
python
en
['fr', 'it', 'en']
False
DatabaseOperations.force_no_ordering
(self)
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on.
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on.
def force_no_ordering(self): """ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on. """ return [(None, ("NULL", [], False))]
[ "def", "force_no_ordering", "(", "self", ")", ":", "return", "[", "(", "None", ",", "(", "\"NULL\"", ",", "[", "]", ",", "False", ")", ")", "]" ]
[ 144, 4 ]
[ 150, 44 ]
python
en
['en', 'error', 'th']
False
BaseMemcachedCache._cache
(self)
Implements transparent thread-safe access to a memcached client.
Implements transparent thread-safe access to a memcached client.
def _cache(self): """ Implements transparent thread-safe access to a memcached client. """ if getattr(self, '_client', None) is None: self._client = self._lib.Client(self._servers) return self._client
[ "def", "_cache", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_client'", ",", "None", ")", "is", "None", ":", "self", ".", "_client", "=", "self", ".", "_lib", ".", "Client", "(", "self", ".", "_servers", ")", "return", "self", ".", ...
[ 36, 4 ]
[ 43, 27 ]
python
en
['en', 'error', 'th']
False
BaseMemcachedCache.get_backend_timeout
(self, timeout=DEFAULT_TIMEOUT)
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout if timeo...
[ "def", "get_backend_timeout", "(", "self", ",", "timeout", "=", "DEFAULT_TIMEOUT", ")", ":", "if", "timeout", "==", "DEFAULT_TIMEOUT", ":", "timeout", "=", "self", ".", "default_timeout", "if", "timeout", "is", "None", ":", "# Using 0 in memcache sets a non-expiring...
[ 45, 4 ]
[ 69, 27 ]
python
en
['en', 'error', 'th']
False
RemoteUserMiddleware.clean_username
(self, username, request)
Allows the backend to clean the username, if the backend defines a clean_username method.
Allows the backend to clean the username, if the backend defines a clean_username method.
def clean_username(self, username, request): """ Allows the backend to clean the username, if the backend defines a clean_username method. """ backend_str = request.session[auth.BACKEND_SESSION_KEY] backend = auth.load_backend(backend_str) try: usernam...
[ "def", "clean_username", "(", "self", ",", "username", ",", "request", ")", ":", "backend_str", "=", "request", ".", "session", "[", "auth", ".", "BACKEND_SESSION_KEY", "]", "backend", "=", "auth", ".", "load_backend", "(", "backend_str", ")", "try", ":", ...
[ 100, 4 ]
[ 111, 23 ]
python
en
['en', 'error', 'th']
False
RemoteUserMiddleware._remove_invalid_user
(self, request)
Removes the current authenticated user in the request which is invalid but only if the user is authenticated via the RemoteUserBackend.
Removes the current authenticated user in the request which is invalid but only if the user is authenticated via the RemoteUserBackend.
def _remove_invalid_user(self, request): """ Removes the current authenticated user in the request which is invalid but only if the user is authenticated via the RemoteUserBackend. """ try: stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''...
[ "def", "_remove_invalid_user", "(", "self", ",", "request", ")", ":", "try", ":", "stored_backend", "=", "load_backend", "(", "request", ".", "session", ".", "get", "(", "auth", ".", "BACKEND_SESSION_KEY", ",", "''", ")", ")", "except", "ImportError", ":", ...
[ 113, 4 ]
[ 125, 36 ]
python
en
['en', 'error', 'th']
False
projected_gradient_descent
( model_fn, x, eps, eps_iter, nb_iter, norm, loss_fn=None, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=None, sanity_checks=False, )
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf...
This class implements either the Basic Iterative Method (Kurakin et al. 2016) when rand_init is set to 0. or the Madry et al. (2017) method when rand_minmax is larger than 0. Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf Paper link (Madry et al. 2017): https://arxiv.org/pdf...
def projected_gradient_descent( model_fn, x, eps, eps_iter, nb_iter, norm, loss_fn=None, clip_min=None, clip_max=None, y=None, targeted=False, rand_init=None, rand_minmax=None, sanity_checks=False, ): """ This class implements either the Basic Iterative Me...
[ "def", "projected_gradient_descent", "(", "model_fn", ",", "x", ",", "eps", ",", "eps_iter", ",", "nb_iter", ",", "norm", ",", "loss_fn", "=", "None", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y", "=", "None", ",", "targeted", "...
[ 9, 0 ]
[ 137, 16 ]
python
en
['en', 'error', 'th']
False
clear_preregistrationuser_invited_as_admin
( apps: StateApps, schema_editor: DatabaseSchemaEditor )
This migration fixes any PreregistrationUser objects that might have been already corrupted to have the administrator role by the buggy original version of migration 0198_preregistrationuser_invited_as. Since invitations that create new users as administrators are rare, it is cleaner to just remove...
This migration fixes any PreregistrationUser objects that might have been already corrupted to have the administrator role by the buggy original version of migration 0198_preregistrationuser_invited_as.
def clear_preregistrationuser_invited_as_admin( apps: StateApps, schema_editor: DatabaseSchemaEditor ) -> None: """This migration fixes any PreregistrationUser objects that might have been already corrupted to have the administrator role by the buggy original version of migration 0198_preregistratio...
[ "def", "clear_preregistrationuser_invited_as_admin", "(", "apps", ":", "StateApps", ",", "schema_editor", ":", "DatabaseSchemaEditor", ")", "->", "None", ":", "INVITED_AS_MEMBER", "=", "1", "INVITED_AS_REALM_ADMIN", "=", "2", "PreregistrationUser", "=", "apps", ".", "...
[ 9, 0 ]
[ 30, 5 ]
python
en
['en', 'en', 'en']
True
salted_hmac
(key_salt, value, secret=None)
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC.
Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY).
def salted_hmac(key_salt, value, secret=None): """ Returns the HMAC-SHA1 of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings...
[ "def", "salted_hmac", "(", "key_salt", ",", "value", ",", "secret", "=", "None", ")", ":", "if", "secret", "is", "None", ":", "secret", "=", "settings", ".", "SECRET_KEY", "key_salt", "=", "force_bytes", "(", "key_salt", ")", "secret", "=", "force_bytes", ...
[ 28, 0 ]
[ 50, 72 ]
python
en
['en', 'error', 'th']
False
get_random_string
(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
Returns a securely generated random string.
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit v...
[ "def", "get_random_string", "(", "length", "=", "12", ",", "allowed_chars", "=", "'abcdefghijklmnopqrstuvwxyz'", "'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'", ")", ":", "if", "not", "using_sysrandom", ":", "# This is ugly, and a hack, but it makes things better than", "# the alternat...
[ 53, 0 ]
[ 76, 71 ]
python
en
['en', 'error', 'th']
False
_bin_to_long
(x)
Convert a binary string into a long integer This is a clever optimization for fast xor vector math
Convert a binary string into a long integer
def _bin_to_long(x): """ Convert a binary string into a long integer This is a clever optimization for fast xor vector math """ return int(binascii.hexlify(x), 16)
[ "def", "_bin_to_long", "(", "x", ")", ":", "return", "int", "(", "binascii", ".", "hexlify", "(", "x", ")", ",", "16", ")" ]
[ 107, 0 ]
[ 113, 39 ]
python
en
['en', 'error', 'th']
False
_long_to_bin
(x, hex_format_string)
Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters.
Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters.
def _long_to_bin(x, hex_format_string): """ Convert a long integer into a binary string. hex_format_string is like "%020x" for padding 10 characters. """ return binascii.unhexlify((hex_format_string % x).encode('ascii'))
[ "def", "_long_to_bin", "(", "x", ",", "hex_format_string", ")", ":", "return", "binascii", ".", "unhexlify", "(", "(", "hex_format_string", "%", "x", ")", ".", "encode", "(", "'ascii'", ")", ")" ]
[ 116, 0 ]
[ 121, 70 ]
python
en
['en', 'error', 'th']
False
AccessibilityValue.save
(self, *args, **kwargs)
Update the cached ordering of related ResourceAccessibility objects
Update the cached ordering of related ResourceAccessibility objects
def save(self, *args, **kwargs): """ Update the cached ordering of related ResourceAccessibility objects """ if self.id: ResourceAccessibility.objects.filter(value=self).update(order=self.order) return super().save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "id", ":", "ResourceAccessibility", ".", "objects", ".", "filter", "(", "value", "=", "self", ")", ".", "update", "(", "order", "=", "self", ".", ...
[ 64, 4 ]
[ 68, 44 ]
python
en
['en', 'en', 'en']
True
timesince
(d, now=None, reversed=False)
Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. Up to two adjacent units wi...
Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned.
def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. Units used are years, months, weeks, days, hours, and minutes. Seconds and mic...
[ "def", "timesince", "(", "d", ",", "now", "=", "None", ",", "reversed", "=", "False", ")", ":", "chunks", "=", "(", "(", "60", "*", "60", "*", "24", "*", "365", ",", "ungettext_lazy", "(", "'%d year'", ",", "'%d years'", ")", ")", ",", "(", "60",...
[ 9, 0 ]
[ 57, 17 ]
python
en
['en', 'error', 'th']
False
timeuntil
(d, now=None)
Like timesince, but returns a string measuring the time until the given time.
Like timesince, but returns a string measuring the time until the given time.
def timeuntil(d, now=None): """ Like timesince, but returns a string measuring the time until the given time. """ return timesince(d, now, reversed=True)
[ "def", "timeuntil", "(", "d", ",", "now", "=", "None", ")", ":", "return", "timesince", "(", "d", ",", "now", ",", "reversed", "=", "True", ")" ]
[ 60, 0 ]
[ 65, 43 ]
python
en
['en', 'error', 'th']
False
_date_from_string
(year, year_format, month='', month_format='', day='', day_format='', delim='__')
Helper: get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date.
Helper: get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date.
def _date_from_string(year, year_format, month='', month_format='', day='', day_format='', delim='__'): """ Helper: get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date. """ format = delim.join((year_format, month_forma...
[ "def", "_date_from_string", "(", "year", ",", "year_format", ",", "month", "=", "''", ",", "month_format", "=", "''", ",", "day", "=", "''", ",", "day_format", "=", "''", ",", "delim", "=", "'__'", ")", ":", "format", "=", "delim", ".", "join", "(", ...
[ 678, 0 ]
[ 691, 10 ]
python
en
['en', 'error', 'th']
False
_get_next_prev
(generic_view, date, is_previous, period)
Helper: Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles different intervals of time, hence the coupling to generic_view. However ...
Helper: Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view.
def _get_next_prev(generic_view, date, is_previous, period): """ Helper: Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles different inte...
[ "def", "_get_next_prev", "(", "generic_view", ",", "date", ",", "is_previous", ",", "period", ")", ":", "date_field", "=", "generic_view", ".", "get_date_field", "(", ")", "allow_empty", "=", "generic_view", ".", "get_allow_empty", "(", ")", "allow_future", "=",...
[ 694, 0 ]
[ 782, 34 ]
python
en
['en', 'error', 'th']
False
timezone_today
()
Return the current date in the current time zone.
Return the current date in the current time zone.
def timezone_today(): """ Return the current date in the current time zone. """ if settings.USE_TZ: return timezone.localtime(timezone.now()).date() else: return datetime.date.today()
[ "def", "timezone_today", "(", ")", ":", "if", "settings", ".", "USE_TZ", ":", "return", "timezone", ".", "localtime", "(", "timezone", ".", "now", "(", ")", ")", ".", "date", "(", ")", "else", ":", "return", "datetime", ".", "date", ".", "today", "("...
[ 785, 0 ]
[ 792, 36 ]
python
en
['en', 'error', 'th']
False
YearMixin.get_year_format
(self)
Get a year format string in strptime syntax to be used to parse the year from url variables.
Get a year format string in strptime syntax to be used to parse the year from url variables.
def get_year_format(self): """ Get a year format string in strptime syntax to be used to parse the year from url variables. """ return self.year_format
[ "def", "get_year_format", "(", "self", ")", ":", "return", "self", ".", "year_format" ]
[ 23, 4 ]
[ 28, 31 ]
python
en
['en', 'error', 'th']
False
YearMixin.get_year
(self)
Return the year for which this view should display data.
Return the year for which this view should display data.
def get_year(self): """ Return the year for which this view should display data. """ year = self.year if year is None: try: year = self.kwargs['year'] except KeyError: try: year = self.request.GET['year']...
[ "def", "get_year", "(", "self", ")", ":", "year", "=", "self", ".", "year", "if", "year", "is", "None", ":", "try", ":", "year", "=", "self", ".", "kwargs", "[", "'year'", "]", "except", "KeyError", ":", "try", ":", "year", "=", "self", ".", "req...
[ 30, 4 ]
[ 43, 19 ]
python
en
['en', 'error', 'th']
False
YearMixin.get_next_year
(self, date)
Get the next valid year.
Get the next valid year.
def get_next_year(self, date): """ Get the next valid year. """ return _get_next_prev(self, date, is_previous=False, period='year')
[ "def", "get_next_year", "(", "self", ",", "date", ")", ":", "return", "_get_next_prev", "(", "self", ",", "date", ",", "is_previous", "=", "False", ",", "period", "=", "'year'", ")" ]
[ 45, 4 ]
[ 49, 75 ]
python
en
['en', 'error', 'th']
False
YearMixin.get_previous_year
(self, date)
Get the previous valid year.
Get the previous valid year.
def get_previous_year(self, date): """ Get the previous valid year. """ return _get_next_prev(self, date, is_previous=True, period='year')
[ "def", "get_previous_year", "(", "self", ",", "date", ")", ":", "return", "_get_next_prev", "(", "self", ",", "date", ",", "is_previous", "=", "True", ",", "period", "=", "'year'", ")" ]
[ 51, 4 ]
[ 55, 74 ]
python
en
['en', 'error', 'th']
False
YearMixin._get_next_year
(self, date)
Return the start date of the next interval. The interval is defined by start date <= item date < next start date.
Return the start date of the next interval.
def _get_next_year(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ return date.replace(year=date.year + 1, month=1, day=1)
[ "def", "_get_next_year", "(", "self", ",", "date", ")", ":", "return", "date", ".", "replace", "(", "year", "=", "date", ".", "year", "+", "1", ",", "month", "=", "1", ",", "day", "=", "1", ")" ]
[ 57, 4 ]
[ 63, 63 ]
python
en
['en', 'error', 'th']
False