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
never_cache
(view_func)
Decorator that adds headers to a response so that it will never be cached.
Decorator that adds headers to a response so that it will never be cached.
def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view_func(request, *args, **kwargs): response = view_func(request, *args, **kwargs) add_never_cache_h...
[ "def", "never_cache", "(", "view_func", ")", ":", "@", "wraps", "(", "view_func", ",", "assigned", "=", "available_attrs", "(", "view_func", ")", ")", "def", "_wrapped_view_func", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "resp...
[ 46, 0 ]
[ 56, 29 ]
python
en
['en', 'error', 'th']
False
staff_member_required
(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login')
Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary.
Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary.
def staff_member_required(view_func, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'): """ Decorator for views that checks that the user is logged in and is a staff member, displaying the login page if necessary. """ return user_passes_test( lambda u: u.is_active and u.is_st...
[ "def", "staff_member_required", "(", "view_func", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ",", "login_url", "=", "'admin:login'", ")", ":", "return", "user_passes_test", "(", "lambda", "u", ":", "u", ".", "is_active", "and", "u", ".", "is_staff", ...
[ 4, 0 ]
[ 13, 16 ]
python
en
['en', 'error', 'th']
False
FormMixinTests.test_initial_data
(self)
Test instance independence of initial data dict (see #16138)
Test instance independence of initial data dict (see #16138)
def test_initial_data(self): """ Test instance independence of initial data dict (see #16138) """ initial_1 = FormMixin().get_initial() initial_1['foo'] = 'bar' initial_2 = FormMixin().get_initial() self.assertNotEqual(initial_1, initial_2)
[ "def", "test_initial_data", "(", "self", ")", ":", "initial_1", "=", "FormMixin", "(", ")", ".", "get_initial", "(", ")", "initial_1", "[", "'foo'", "]", "=", "'bar'", "initial_2", "=", "FormMixin", "(", ")", ".", "get_initial", "(", ")", "self", ".", ...
[ 17, 4 ]
[ 22, 49 ]
python
en
['en', 'en', 'en']
True
FormMixinTests.test_get_prefix
(self)
Test prefix can be set (see #18872)
Test prefix can be set (see #18872)
def test_get_prefix(self): """ Test prefix can be set (see #18872) """ test_string = 'test' rf = RequestFactory() get_request = rf.get('/') class TestFormMixin(FormMixin): request = get_request default_kwargs = TestFormMixin().get_form_kwargs() self...
[ "def", "test_get_prefix", "(", "self", ")", ":", "test_string", "=", "'test'", "rf", "=", "RequestFactory", "(", ")", "get_request", "=", "rf", ".", "get", "(", "'/'", ")", "class", "TestFormMixin", "(", "FormMixin", ")", ":", "request", "=", "get_request"...
[ 24, 4 ]
[ 40, 63 ]
python
en
['en', 'en', 'en']
True
SelectionPreferences.__init__
( self, allow_yanked, # type: bool allow_all_prereleases=False, # type: bool format_control=None, # type: Optional[FormatControl] prefer_binary=False, # type: bool ignore_requires_python=None, # type: Optional[bool] )
Create a SelectionPreferences object. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param format_control: A FormatControl object or None. Used to control the selection of source packages / binary packag...
Create a SelectionPreferences object.
def __init__( self, allow_yanked, # type: bool allow_all_prereleases=False, # type: bool format_control=None, # type: Optional[FormatControl] prefer_binary=False, # type: bool ignore_requires_python=None, # type: Optional[bool] ): # type: ...
[ "def", "__init__", "(", "self", ",", "allow_yanked", ",", "# type: bool", "allow_all_prereleases", "=", "False", ",", "# type: bool", "format_control", "=", "None", ",", "# type: Optional[FormatControl]", "prefer_binary", "=", "False", ",", "# type: bool", "ignore_requi...
[ 18, 4 ]
[ 46, 60 ]
python
en
['en', 'en', 'en']
True
make_basic_picklable_cnn
( nb_filters=64, nb_classes=10, input_shape=(None, 28, 28, 1) )
The model for the picklable models tutorial.
The model for the picklable models tutorial.
def make_basic_picklable_cnn( nb_filters=64, nb_classes=10, input_shape=(None, 28, 28, 1) ): """The model for the picklable models tutorial.""" layers = [ Conv2D(nb_filters, (8, 8), (2, 2), "SAME"), ReLU(), Conv2D(nb_filters * 2, (6, 6), (2, 2), "VALID"), ReLU(), Conv...
[ "def", "make_basic_picklable_cnn", "(", "nb_filters", "=", "64", ",", "nb_classes", "=", "10", ",", "input_shape", "=", "(", "None", ",", "28", ",", "28", ",", "1", ")", ")", ":", "layers", "=", "[", "Conv2D", "(", "nb_filters", ",", "(", "8", ",", ...
[ 13, 0 ]
[ 29, 16 ]
python
en
['en', 'en', 'en']
True
clip_eta
(eta, norm, eps)
PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param norm: np.inf, 1, or 2 :param eps: float
PyTorch implementation of the clip_eta in utils_tf.
def clip_eta(eta, norm, eps): """ PyTorch implementation of the clip_eta in utils_tf. :param eta: Tensor :param norm: np.inf, 1, or 2 :param eps: float """ if norm not in [np.inf, 1, 2]: raise ValueError("norm must be np.inf, 1, or 2.") avoid_zero_div = torch.tensor(1e-12, dtyp...
[ "def", "clip_eta", "(", "eta", ",", "norm", ",", "eps", ")", ":", "if", "norm", "not", "in", "[", "np", ".", "inf", ",", "1", ",", "2", "]", ":", "raise", "ValueError", "(", "\"norm must be np.inf, 1, or 2.\"", ")", "avoid_zero_div", "=", "torch", ".",...
[ 7, 0 ]
[ 38, 14 ]
python
en
['en', 'error', 'th']
False
get_or_guess_labels
(model, x, **kwargs)
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then assume it's a targeted attack and us...
Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not none, then assume it's a targeted attack and us...
def get_or_guess_labels(model, x, **kwargs): """ Get the label to use in generating an adversarial example for x. The kwargs are fed directly from the kwargs of the attack. If 'y' is in kwargs, then assume it's an untargeted attack and use that as the label. If 'y_target' is in kwargs and is not...
[ "def", "get_or_guess_labels", "(", "model", ",", "x", ",", "*", "*", "kwargs", ")", ":", "if", "\"y\"", "in", "kwargs", "and", "\"y_target\"", "in", "kwargs", ":", "raise", "ValueError", "(", "\"Can not set both 'y' and 'y_target'.\"", ")", "if", "\"y\"", "in"...
[ 41, 0 ]
[ 65, 17 ]
python
en
['en', 'error', 'th']
False
optimize_linear
(grad, eps, norm=np.inf)
Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{norm} < eps} dot(eta, grad) :param grad: Tensor, shape (N, d_1, ...). Batch of gradients :param eps: float. Scalar specifying size of constraint region :param norm: np.inf, 1, o...
Solves for the optimal input to a linear function under a norm constraint.
def optimize_linear(grad, eps, norm=np.inf): """ Solves for the optimal input to a linear function under a norm constraint. Optimal_perturbation = argmax_{eta, ||eta||_{norm} < eps} dot(eta, grad) :param grad: Tensor, shape (N, d_1, ...). Batch of gradients :param eps: float. Scalar specifying siz...
[ "def", "optimize_linear", "(", "grad", ",", "eps", ",", "norm", "=", "np", ".", "inf", ")", ":", "red_ind", "=", "list", "(", "range", "(", "1", ",", "len", "(", "grad", ".", "size", "(", ")", ")", ")", ")", "avoid_zero_div", "=", "torch", ".", ...
[ 68, 0 ]
[ 123, 30 ]
python
en
['en', 'error', 'th']
False
zero_out_clipped_grads
(grad, x, clip_min, clip_max)
Helper function to erase entries in the gradient where the update would be clipped. :param grad: The gradient :param x: The current input :param clip_min: Minimum input component value :param clip_max: Maximum input component value
Helper function to erase entries in the gradient where the update would be clipped. :param grad: The gradient :param x: The current input :param clip_min: Minimum input component value :param clip_max: Maximum input component value
def zero_out_clipped_grads(grad, x, clip_min, clip_max): """ Helper function to erase entries in the gradient where the update would be clipped. :param grad: The gradient :param x: The current input :param clip_min: Minimum input component value :param clip_max: Maximum input component value...
[ "def", "zero_out_clipped_grads", "(", "grad", ",", "x", ",", "clip_min", ",", "clip_max", ")", ":", "signed_grad", "=", "torch", ".", "sign", "(", "grad", ")", "# Find input components that lie at the boundary of the input range, and", "# where the gradient points in the wr...
[ 126, 0 ]
[ 144, 15 ]
python
en
['en', 'error', 'th']
False
HStoreField.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 dict, if the data or initial value we get # is None, replace it w/ {}. initial_value = se...
[ "def", "has_changed", "(", "self", ",", "initial", ",", "data", ")", ":", "# For purposes of seeing whether something has changed, None is", "# the same as an empty dict, if the data or initial value we get", "# is None, replace it w/ {}.", "initial_value", "=", "self", ".", "to_py...
[ 49, 4 ]
[ 57, 55 ]
python
en
['en', 'error', 'th']
False
AppConfig._path_from_module
(self, module)
Attempt to determine app's filesystem path from its module.
Attempt to determine app's filesystem path from its module.
def _path_from_module(self, module): """Attempt to determine app's filesystem path from its module.""" # See #21874 for extended discussion of the behavior of this method in # various cases. # Convert paths to list because Python's _NamespacePath doesn't support # indexing. ...
[ "def", "_path_from_module", "(", "self", ",", "module", ")", ":", "# See #21874 for extended discussion of the behavior of this method in", "# various cases.", "# Convert paths to list because Python's _NamespacePath doesn't support", "# indexing.", "paths", "=", "list", "(", "getatt...
[ 53, 4 ]
[ 78, 23 ]
python
en
['en', 'en', 'en']
True
AppConfig.create
(cls, entry)
Factory that creates an app config from an entry in INSTALLED_APPS.
Factory that creates an app config from an entry in INSTALLED_APPS.
def create(cls, entry): """ Factory that creates an app config from an entry in INSTALLED_APPS. """ try: # If import_module succeeds, entry is a path to an app module, # which may specify an app config class with default_app_config. # Otherwise, entry ...
[ "def", "create", "(", "cls", ",", "entry", ")", ":", "try", ":", "# If import_module succeeds, entry is a path to an app module,", "# which may specify an app config class with default_app_config.", "# Otherwise, entry is a path to an app config class or an error.", "module", "=", "imp...
[ 81, 4 ]
[ 164, 40 ]
python
en
['en', 'error', 'th']
False
AppConfig.get_model
(self, model_name, require_ready=True)
Return the model with the given case-insensitive model_name. Raise LookupError if no model exists with this name.
Return the model with the given case-insensitive model_name.
def get_model(self, model_name, require_ready=True): """ Return the model with the given case-insensitive model_name. Raise LookupError if no model exists with this name. """ if require_ready: self.apps.check_models_ready() else: self.apps.check_a...
[ "def", "get_model", "(", "self", ",", "model_name", ",", "require_ready", "=", "True", ")", ":", "if", "require_ready", ":", "self", ".", "apps", ".", "check_models_ready", "(", ")", "else", ":", "self", ".", "apps", ".", "check_apps_ready", "(", ")", "t...
[ 166, 4 ]
[ 180, 81 ]
python
en
['en', 'error', 'th']
False
AppConfig.get_models
(self, include_auto_created=False, include_swapped=False)
Return an iterable of models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have been swapped out. Set the corresponding keyword argument to True to include su...
Return an iterable of models.
def get_models(self, include_auto_created=False, include_swapped=False): """ Return an iterable of models. By default, the following models aren't included: - auto-created models for many-to-many relations without an explicit intermediate table, - models that have bee...
[ "def", "get_models", "(", "self", ",", "include_auto_created", "=", "False", ",", "include_swapped", "=", "False", ")", ":", "self", ".", "apps", ".", "check_models_ready", "(", ")", "for", "model", "in", "self", ".", "models", ".", "values", "(", ")", "...
[ 182, 4 ]
[ 201, 23 ]
python
en
['en', 'error', 'th']
False
AppConfig.ready
(self)
Override this method in subclasses to run code when Django starts.
Override this method in subclasses to run code when Django starts.
def ready(self): """ Override this method in subclasses to run code when Django starts. """
[ "def", "ready", "(", "self", ")", ":" ]
[ 212, 4 ]
[ 215, 11 ]
python
en
['en', 'error', 'th']
False
process_varaamo_libraries
()
Find varaamo libraries' Units from the db, ask their data from kirjastot.fi and process resulting opening hours if found into their Unit object Asks the span of opening hours from get_time_range TODO: Libraries in Helmet system with resources need more reliable identifier :return: None ...
Find varaamo libraries' Units from the db, ask their data from kirjastot.fi and process resulting opening hours if found into their Unit object
def process_varaamo_libraries(): """ Find varaamo libraries' Units from the db, ask their data from kirjastot.fi and process resulting opening hours if found into their Unit object Asks the span of opening hours from get_time_range TODO: Libraries in Helmet system with resources need more ...
[ "def", "process_varaamo_libraries", "(", ")", ":", "varaamo_units", "=", "Unit", ".", "objects", ".", "filter", "(", "identifiers__namespace", "=", "KIRKANTA_NAMESPACE", ")", "start", ",", "end", "=", "get_time_range", "(", ")", "problems", "=", "[", "]", "for...
[ 29, 0 ]
[ 70, 12 ]
python
en
['en', 'error', 'th']
False
timetable_fetcher
(unit, start='2016-07-01', end='2016-12-31')
Fetch periods using kirjastot.fi's v4 API v4 gives opening for each day with period id it originated from, thus allowing creation of unique periods :param unit: Unit object of the library :param start: start day for required opening hours :param end: end day for required opening hours ...
Fetch periods using kirjastot.fi's v4 API
def timetable_fetcher(unit, start='2016-07-01', end='2016-12-31'): """ Fetch periods using kirjastot.fi's v4 API v4 gives opening for each day with period id it originated from, thus allowing creation of unique periods :param unit: Unit object of the library :param start: start day for req...
[ "def", "timetable_fetcher", "(", "unit", ",", "start", "=", "'2016-07-01'", ",", "end", "=", "'2016-12-31'", ")", ":", "base_url", "=", "\"https://api.kirjastot.fi/v4/library\"", "supported_namespaces", "=", "(", "KIRKANTA_NAMESPACE", ",", ")", "for", "identificator",...
[ 73, 0 ]
[ 114, 16 ]
python
en
['en', 'error', 'th']
False
process_periods
(library, unit)
Generate Period and Day objects into given Unit from kirjastot.fi v4 API data Each day in data has its own Period and Day object resulting in as many Periods with one Day as there is items in data :param data: kirjastot.fi v4 API data form /library endpoint :param unit: Unit :return: ...
Generate Period and Day objects into given Unit from kirjastot.fi v4 API data
def process_periods(library, unit): """ Generate Period and Day objects into given Unit from kirjastot.fi v4 API data Each day in data has its own Period and Day object resulting in as many Periods with one Day as there is items in data :param data: kirjastot.fi v4 API data form /library e...
[ "def", "process_periods", "(", "library", ",", "unit", ")", ":", "schedule_days", "=", "[", "parse_schedule", "(", "schedule_item", ")", "for", "schedule_item", "in", "library", "[", "'schedules'", "]", "]", "for", "day", "in", "schedule_days", ":", "# this is...
[ 117, 0 ]
[ 158, 31 ]
python
en
['en', 'error', 'th']
False
merge_opening_hours
(opening_hours: List)
A workaround helper that combines a list of opening times to a single pair with the earliest opening and the latest closing time.
A workaround helper that combines a list of opening times to a single pair with the earliest opening and the latest closing time.
def merge_opening_hours(opening_hours: List) -> Dict[str, datetime.time]: """ A workaround helper that combines a list of opening times to a single pair with the earliest opening and the latest closing time. """ opening_times = [parse_time(times['from']) for times in opening_hours] closing_times = [pars...
[ "def", "merge_opening_hours", "(", "opening_hours", ":", "List", ")", "->", "Dict", "[", "str", ",", "datetime", ".", "time", "]", ":", "opening_times", "=", "[", "parse_time", "(", "times", "[", "'from'", "]", ")", "for", "times", "in", "opening_hours", ...
[ 177, 0 ]
[ 185, 5 ]
python
en
['en', 'en', 'en']
True
get_time_range
(start=None, back: int = 1, forward: int = 12)
From a starting date from back and forward by given amount and return start of both months as dates :param start: datetime.date :param back: int :param forward: int :return: (datetime.date, datetime.date)
From a starting date from back and forward by given amount and return start of both months as dates
def get_time_range(start=None, back: int = 1, forward: int = 12): """ From a starting date from back and forward by given amount and return start of both months as dates :param start: datetime.date :param back: int :param forward: int :return: (datetime.date, datetime.date) """ ...
[ "def", "get_time_range", "(", "start", "=", "None", ",", "back", ":", "int", "=", "1", ",", "forward", ":", "int", "=", "12", ")", ":", "base", "=", "delorean", ".", "Delorean", "(", "start", ")", "start", "=", "base", ".", "last_month", "(", "back...
[ 193, 0 ]
[ 207, 21 ]
python
en
['en', 'error', 'th']
False
flatatt
(attrs)
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through...
Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string.
def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. T...
[ "def", "flatatt", "(", "attrs", ")", ":", "boolean_attrs", "=", "[", "]", "for", "attr", ",", "value", "in", "list", "(", "attrs", ".", "items", "(", ")", ")", ":", "if", "value", "is", "True", ":", "boolean_attrs", ".", "append", "(", "(", "attr",...
[ 22, 0 ]
[ 42, 5 ]
python
en
['en', 'error', 'th']
False
from_current_timezone
(value)
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes.
def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: ...
[ "def", "from_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_naive", "(", "value", ")", ":", "current_timezone", "=", "timezone", ".", "get_current_timezone", "(", "...
[ 152, 0 ]
[ 173, 16 ]
python
en
['en', 'error', 'th']
False
to_current_timezone
(value)
When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display.
When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display.
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return ...
[ "def", "to_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_aware", "(", "value", ")", ":", "current_timezone", "=", "timezone", ".", "get_current_timezone", "(", ")"...
[ 176, 0 ]
[ 184, 16 ]
python
en
['en', 'error', 'th']
False
SimpleTemplateResponse.__getstate__
(self)
Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response.
Pickling support function.
def __getstate__(self): """Pickling support function. Ensures that the object can't be pickled before it has been rendered, and that the pickled state only includes rendered data, not the data used to construct the response. """ obj_dict = super(SimpleTemplateResponse, s...
[ "def", "__getstate__", "(", "self", ")", ":", "obj_dict", "=", "super", "(", "SimpleTemplateResponse", ",", "self", ")", ".", "__getstate__", "(", ")", "if", "not", "self", ".", "_is_rendered", ":", "raise", "ContentNotRenderedError", "(", "'The response content...
[ 34, 4 ]
[ 49, 23 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.resolve_template
(self, template)
Accepts a template object, path-to-template or list of paths
Accepts a template object, path-to-template or list of paths
def resolve_template(self, template): "Accepts a template object, path-to-template or list of paths" if isinstance(template, (list, tuple)): return loader.select_template(template) elif isinstance(template, six.string_types): return loader.get_template(template) e...
[ "def", "resolve_template", "(", "self", ",", "template", ")", ":", "if", "isinstance", "(", "template", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "loader", ".", "select_template", "(", "template", ")", "elif", "isinstance", "(", "template", ...
[ 51, 4 ]
[ 58, 27 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.resolve_context
(self, context)
Converts context data into a full Context object (assuming it isn't already a Context object).
Converts context data into a full Context object (assuming it isn't already a Context object).
def resolve_context(self, context): """Converts context data into a full Context object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context else: return Context(context)
[ "def", "resolve_context", "(", "self", ",", "context", ")", ":", "if", "isinstance", "(", "context", ",", "Context", ")", ":", "return", "context", "else", ":", "return", "Context", "(", "context", ")" ]
[ 60, 4 ]
[ 67, 35 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.rendered_content
(self)
Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. ...
Returns the freshly rendered content for the template and context described by the TemplateResponse.
def rendered_content(self): """Returns the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly us...
[ "def", "rendered_content", "(", "self", ")", ":", "template", "=", "self", ".", "resolve_template", "(", "self", ".", "template_name", ")", "context", "=", "self", ".", "resolve_context", "(", "self", ".", "context_data", ")", "content", "=", "template", "."...
[ 70, 4 ]
[ 81, 22 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.add_post_render_callback
(self, callback)
Adds a new post-rendering callback. If the response has already been rendered, invoke the callback immediately.
Adds a new post-rendering callback.
def add_post_render_callback(self, callback): """Adds a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(call...
[ "def", "add_post_render_callback", "(", "self", ",", "callback", ")", ":", "if", "self", ".", "_is_rendered", ":", "callback", "(", "self", ")", "else", ":", "self", ".", "_post_render_callbacks", ".", "append", "(", "callback", ")" ]
[ 83, 4 ]
[ 92, 56 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.render
(self)
Renders (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance.
Renders (thereby finalizing) the content of the response.
def render(self): """Renders (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Returns the baked response instance. """ retval = self if not self._is_rendered: self.content = self.rendered_content ...
[ "def", "render", "(", "self", ")", ":", "retval", "=", "self", "if", "not", "self", ".", "_is_rendered", ":", "self", ".", "content", "=", "self", ".", "rendered_content", "for", "post_callback", "in", "self", ".", "_post_render_callbacks", ":", "newretval",...
[ 94, 4 ]
[ 108, 21 ]
python
en
['en', 'en', 'en']
True
SimpleTemplateResponse.content
(self, value)
Sets the content for the response
Sets the content for the response
def content(self, value): """Sets the content for the response """ HttpResponse.content.fset(self, value) self._is_rendered = True
[ "def", "content", "(", "self", ",", "value", ")", ":", "HttpResponse", ".", "content", ".", "fset", "(", "self", ",", "value", ")", "self", ".", "_is_rendered", "=", "True" ]
[ 128, 4 ]
[ 132, 32 ]
python
en
['en', 'en', 'en']
True
TemplateResponse.resolve_context
(self, context)
Convert context data into a full RequestContext object (assuming it isn't already a Context object).
Convert context data into a full RequestContext object (assuming it isn't already a Context object).
def resolve_context(self, context): """Convert context data into a full RequestContext object (assuming it isn't already a Context object). """ if isinstance(context, Context): return context return RequestContext(self._request, context, current_app=self._current_app)
[ "def", "resolve_context", "(", "self", ",", "context", ")", ":", "if", "isinstance", "(", "context", ",", "Context", ")", ":", "return", "context", "return", "RequestContext", "(", "self", ".", "_request", ",", "context", ",", "current_app", "=", "self", "...
[ 150, 4 ]
[ 156, 84 ]
python
en
['en', 'lb', 'en']
True
WhereNode._prepare_data
(self, data)
Prepare data for addition to the tree. If the data is a list or tuple, it is expected to be of the form (obj, lookup_type, value), where obj is a Constraint object, and is then slightly munged before being stored (to avoid storing any reference to field objects). Otherwise, the ...
Prepare data for addition to the tree. If the data is a list or tuple, it is expected to be of the form (obj, lookup_type, value), where obj is a Constraint object, and is then slightly munged before being stored (to avoid storing any reference to field objects). Otherwise, the ...
def _prepare_data(self, data): """ Prepare data for addition to the tree. If the data is a list or tuple, it is expected to be of the form (obj, lookup_type, value), where obj is a Constraint object, and is then slightly munged before being stored (to avoid storing any reference ...
[ "def", "_prepare_data", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "data", "obj", ",", "lookup_type", ",", "value", "=", "data", "if", "isinstance", "(", "value...
[ 51, 4 ]
[ 82, 58 ]
python
en
['en', 'error', 'th']
False
WhereNode.as_sql
(self, qn, connection)
Returns the SQL version of the where clause and the value to be substituted in. Returns '', [] if this node matches everything, None, [] if this node is empty, and raises EmptyResultSet if this node can't match anything.
Returns the SQL version of the where clause and the value to be substituted in. Returns '', [] if this node matches everything, None, [] if this node is empty, and raises EmptyResultSet if this node can't match anything.
def as_sql(self, qn, connection): """ Returns the SQL version of the where clause and the value to be substituted in. Returns '', [] if this node matches everything, None, [] if this node is empty, and raises EmptyResultSet if this node can't match anything. """ #...
[ "def", "as_sql", "(", "self", ",", "qn", ",", "connection", ")", ":", "# Note that the logic here is made slightly more complex than", "# necessary because there are two kind of empty nodes: Nodes", "# containing 0 children, and nodes that are known to match everything.", "# A match-everyt...
[ 84, 4 ]
[ 154, 40 ]
python
en
['en', 'error', 'th']
False
WhereNode.make_atom
(self, child, qn, connection)
Turn a tuple (Constraint(table_alias, column_name, db_type), lookup_type, value_annotation, params) into valid SQL. The first item of the tuple may also be an Aggregate. Returns the string for the SQL fragment and the parameters to use for it.
Turn a tuple (Constraint(table_alias, column_name, db_type), lookup_type, value_annotation, params) into valid SQL.
def make_atom(self, child, qn, connection): """ Turn a tuple (Constraint(table_alias, column_name, db_type), lookup_type, value_annotation, params) into valid SQL. The first item of the tuple may also be an Aggregate. Returns the string for the SQL fragment and the parameters t...
[ "def", "make_atom", "(", "self", ",", "child", ",", "qn", ",", "connection", ")", ":", "warnings", ".", "warn", "(", "\"The make_atom() method will be removed in Django 1.9. Use Lookup class instead.\"", ",", "RemovedInDjango19Warning", ")", "lvalue", ",", "lookup_type", ...
[ 168, 4 ]
[ 265, 64 ]
python
en
['en', 'error', 'th']
False
WhereNode.sql_for_columns
(self, data, qn, connection, internal_type=None)
Returns the SQL fragment used for the left-hand side of a column constraint (for example, the "T1.foo" portion in the clause "WHERE ... T1.foo = 6") and a list of parameters.
Returns the SQL fragment used for the left-hand side of a column constraint (for example, the "T1.foo" portion in the clause "WHERE ... T1.foo = 6") and a list of parameters.
def sql_for_columns(self, data, qn, connection, internal_type=None): """ Returns the SQL fragment used for the left-hand side of a column constraint (for example, the "T1.foo" portion in the clause "WHERE ... T1.foo = 6") and a list of parameters. """ table_alias, name, d...
[ "def", "sql_for_columns", "(", "self", ",", "data", ",", "qn", ",", "connection", ",", "internal_type", "=", "None", ")", ":", "table_alias", ",", "name", ",", "db_type", "=", "data", "if", "table_alias", ":", "lhs", "=", "'%s.%s'", "%", "(", "qn", "("...
[ 267, 4 ]
[ 278, 74 ]
python
en
['en', 'error', 'th']
False
WhereNode.relabel_aliases
(self, change_map)
Relabels the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values.
Relabels the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values.
def relabel_aliases(self, change_map): """ Relabels the alias values of any children. 'change_map' is a dictionary mapping old (current) alias values to the new values. """ for pos, child in enumerate(self.children): if hasattr(child, 'relabel_aliases'): ...
[ "def", "relabel_aliases", "(", "self", ",", "change_map", ")", ":", "for", "pos", ",", "child", "in", "enumerate", "(", "self", ".", "children", ")", ":", "if", "hasattr", "(", "child", ",", "'relabel_aliases'", ")", ":", "# For example another WhereNode", "...
[ 280, 4 ]
[ 297, 42 ]
python
en
['en', 'error', 'th']
False
WhereNode.clone
(self)
Creates a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Contraint, lookup, value) tuples, or objects supporting .clone().
Creates a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Contraint, lookup, value) tuples, or objects supporting .clone().
def clone(self): """ Creates a clone of the tree. Must only be called on root nodes (nodes with empty subtree_parents). Childs must be either (Contraint, lookup, value) tuples, or objects supporting .clone(). """ clone = self.__class__._new_instance( children=...
[ "def", "clone", "(", "self", ")", ":", "clone", "=", "self", ".", "__class__", ".", "_new_instance", "(", "children", "=", "[", "]", ",", "connector", "=", "self", ".", "connector", ",", "negated", "=", "self", ".", "negated", ")", "for", "child", "i...
[ 299, 4 ]
[ 312, 20 ]
python
en
['en', 'error', 'th']
False
Constraint.process
(self, lookup_type, value, connection)
Returns a tuple of data suitable for inclusion in a WhereNode instance.
Returns a tuple of data suitable for inclusion in a WhereNode instance.
def process(self, lookup_type, value, connection): """ Returns a tuple of data suitable for inclusion in a WhereNode instance. """ # Because of circular imports, we need to import this here. from django.db.models.base import ObjectDoesNotExist try: if ...
[ "def", "process", "(", "self", ",", "lookup_type", ",", "value", ",", "connection", ")", ":", "# Because of circular imports, we need to import this here.", "from", "django", ".", "db", ".", "models", ".", "base", "import", "ObjectDoesNotExist", "try", ":", "if", ...
[ 366, 4 ]
[ 388, 54 ]
python
en
['en', 'error', 'th']
False
ParserTest.test_validate_vanilla_html
(self)
Verify that validate() does not raise errors for well-formed HTML.
Verify that validate() does not raise errors for well-formed HTML.
def test_validate_vanilla_html(self) -> None: """ Verify that validate() does not raise errors for well-formed HTML. """ my_html = """ <table> <tr> <td>foo</td> </tr> </table>""" validate(text=my_html...
[ "def", "test_validate_vanilla_html", "(", "self", ")", "->", "None", ":", "my_html", "=", "\"\"\"\n <table>\n <tr>\n <td>foo</td>\n </tr>\n </table>\"\"\"", "validate", "(", "text", "=", "my_html", ")" ]
[ 31, 4 ]
[ 42, 30 ]
python
en
['en', 'error', 'th']
False
AnalyzeQueueStatsTests.test_queue_stuck
(self)
Last update > 5 minutes ago and there's events in the queue.
Last update > 5 minutes ago and there's events in the queue.
def test_queue_stuck(self) -> None: """Last update > 5 minutes ago and there's events in the queue.""" result = analyze_queue_stats("name", {"update_time": time.time() - 301}, 100) self.assertEqual(result["status"], CRITICAL) self.assertIn("queue appears to be stuck", result["message"])
[ "def", "test_queue_stuck", "(", "self", ")", "->", "None", ":", "result", "=", "analyze_queue_stats", "(", "\"name\"", ",", "{", "\"update_time\"", ":", "time", ".", "time", "(", ")", "-", "301", "}", ",", "100", ")", "self", ".", "assertEqual", "(", "...
[ 11, 4 ]
[ 16, 69 ]
python
en
['en', 'en', 'en']
True
AnalyzeQueueStatsTests.test_queue_just_started
(self)
We just started processing a burst of events, and haven't processed enough to log productivity statistics yet.
We just started processing a burst of events, and haven't processed enough to log productivity statistics yet.
def test_queue_just_started(self) -> None: """ We just started processing a burst of events, and haven't processed enough to log productivity statistics yet. """ result = analyze_queue_stats( "name", { "update_time": time.time(), ...
[ "def", "test_queue_just_started", "(", "self", ")", "->", "None", ":", "result", "=", "analyze_queue_stats", "(", "\"name\"", ",", "{", "\"update_time\"", ":", "time", ".", "time", "(", ")", ",", "\"current_queue_size\"", ":", "10000", ",", "\"recent_average_con...
[ 18, 4 ]
[ 32, 46 ]
python
en
['en', 'error', 'th']
False
AnalyzeQueueStatsTests.test_queue_normal
(self)
10000 events and each takes a second => it'll take a long time to empty.
10000 events and each takes a second => it'll take a long time to empty.
def test_queue_normal(self) -> None: """10000 events and each takes a second => it'll take a long time to empty.""" result = analyze_queue_stats( "name", { "update_time": time.time(), "current_queue_size": 10000, "queue_last_emptied...
[ "def", "test_queue_normal", "(", "self", ")", "->", "None", ":", "result", "=", "analyze_queue_stats", "(", "\"name\"", ",", "{", "\"update_time\"", ":", "time", ".", "time", "(", ")", ",", "\"current_queue_size\"", ":", "10000", ",", "\"queue_last_emptied_times...
[ 34, 4 ]
[ 87, 50 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_serialize
(self)
Tests that basic serialization works.
Tests that basic serialization works.
def test_serialize(self): """Tests that basic serialization works.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) self.assertTrue(self._validate_output(serial_str))
[ "def", "test_serialize", "(", "self", ")", ":", "serial_str", "=", "serializers", ".", "serialize", "(", "self", ".", "serializer_name", ",", "Article", ".", "objects", ".", "all", "(", ")", ")", "self", ".", "assertTrue", "(", "self", ".", "_validate_outp...
[ 103, 4 ]
[ 107, 58 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_serializer_roundtrip
(self)
Tests that serialized content can be deserialized.
Tests that serialized content can be deserialized.
def test_serializer_roundtrip(self): """Tests that serialized content can be deserialized.""" serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) models = list(serializers.deserialize(self.serializer_name, serial_str)) ...
[ "def", "test_serializer_roundtrip", "(", "self", ")", ":", "serial_str", "=", "serializers", ".", "serialize", "(", "self", ".", "serializer_name", ",", "Article", ".", "objects", ".", "all", "(", ")", ")", "models", "=", "list", "(", "serializers", ".", "...
[ 109, 4 ]
[ 114, 40 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_altering_serialized_output
(self)
Tests the ability to create new objects by modifying serialized content.
Tests the ability to create new objects by modifying serialized content.
def test_altering_serialized_output(self): """ Tests the ability to create new objects by modifying serialized content. """ old_headline = "Poker has no place on ESPN" new_headline = "Poker has no place on television" serial_str = serializers.serialize(self.serial...
[ "def", "test_altering_serialized_output", "(", "self", ")", ":", "old_headline", "=", "\"Poker has no place on ESPN\"", "new_headline", "=", "\"Poker has no place on television\"", "serial_str", "=", "serializers", ".", "serialize", "(", "self", ".", "serializer_name", ",",...
[ 116, 4 ]
[ 137, 71 ]
python
en
['en', 'error', 'th']
False
SerializersTestBase.test_one_to_one_as_pk
(self)
Tests that if you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier.
Tests that if you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier.
def test_one_to_one_as_pk(self): """ Tests that if you use your own primary key field (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier. """ profile = AuthorProfile(author=self.joe, da...
[ "def", "test_one_to_one_as_pk", "(", "self", ")", ":", "profile", "=", "AuthorProfile", "(", "author", "=", "self", ".", "joe", ",", "date_of_birth", "=", "datetime", "(", "1970", ",", "1", ",", "1", ")", ")", "profile", ".", "save", "(", ")", "serial_...
[ 139, 4 ]
[ 153, 80 ]
python
en
['en', 'error', 'th']
False
SerializersTestBase.test_serialize_field_subset
(self)
Tests that output can be restricted to a subset of fields
Tests that output can be restricted to a subset of fields
def test_serialize_field_subset(self): """Tests that output can be restricted to a subset of fields""" valid_fields = ('headline', 'pub_date') invalid_fields = ("author", "categories") serial_str = serializers.serialize(self.serializer_name, Article.ob...
[ "def", "test_serialize_field_subset", "(", "self", ")", ":", "valid_fields", "=", "(", "'headline'", ",", "'pub_date'", ")", "invalid_fields", "=", "(", "\"author\"", ",", "\"categories\"", ")", "serial_str", "=", "serializers", ".", "serialize", "(", "self", "....
[ 155, 4 ]
[ 166, 75 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_serialize_unicode
(self)
Tests that unicode makes the roundtrip intact
Tests that unicode makes the roundtrip intact
def test_serialize_unicode(self): """Tests that unicode makes the roundtrip intact""" actor_name = "Za\u017c\u00f3\u0142\u0107" movie_title = 'G\u0119\u015bl\u0105 ja\u017a\u0144' ac = Actor(name=actor_name) mv = Movie(title=movie_title, actor=ac) ac.save() mv.sav...
[ "def", "test_serialize_unicode", "(", "self", ")", ":", "actor_name", "=", "\"Za\\u017c\\u00f3\\u0142\\u0107\"", "movie_title", "=", "'G\\u0119\\u015bl\\u0105 ja\\u017a\\u0144'", "ac", "=", "Actor", "(", "name", "=", "actor_name", ")", "mv", "=", "Movie", "(", "title"...
[ 168, 4 ]
[ 183, 51 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_serialize_superfluous_queries
(self)
Ensure no superfluous queries are made when serializing ForeignKeys #17602
Ensure no superfluous queries are made when serializing ForeignKeys
def test_serialize_superfluous_queries(self): """Ensure no superfluous queries are made when serializing ForeignKeys #17602 """ ac = Actor(name='Actor name') ac.save() mv = Movie(title='Movie title', actor_id=ac.pk) mv.save() with self.assertNumQueries(0...
[ "def", "test_serialize_superfluous_queries", "(", "self", ")", ":", "ac", "=", "Actor", "(", "name", "=", "'Actor name'", ")", "ac", ".", "save", "(", ")", "mv", "=", "Movie", "(", "title", "=", "'Movie title'", ",", "actor_id", "=", "ac", ".", "pk", "...
[ 185, 4 ]
[ 196, 61 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_serialize_with_null_pk
(self)
Tests that serialized data with no primary key results in a model instance with no id
Tests that serialized data with no primary key results in a model instance with no id
def test_serialize_with_null_pk(self): """ Tests that serialized data with no primary key results in a model instance with no id """ category = Category(name="Reference") serial_str = serializers.serialize(self.serializer_name, [category]) pk_value = self._get_pk_...
[ "def", "test_serialize_with_null_pk", "(", "self", ")", ":", "category", "=", "Category", "(", "name", "=", "\"Reference\"", ")", "serial_str", "=", "serializers", ".", "serialize", "(", "self", ".", "serializer_name", ",", "[", "category", "]", ")", "pk_value...
[ 198, 4 ]
[ 210, 42 ]
python
en
['en', 'error', 'th']
False
SerializersTestBase.test_float_serialization
(self)
Tests that float values serialize and deserialize intact
Tests that float values serialize and deserialize intact
def test_float_serialization(self): """Tests that float values serialize and deserialize intact""" sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) deserial_objs = list(serializers.deserialize(self.serializer_name, ...
[ "def", "test_float_serialization", "(", "self", ")", ":", "sc", "=", "Score", "(", "score", "=", "3.4", ")", "sc", ".", "save", "(", ")", "serial_str", "=", "serializers", ".", "serialize", "(", "self", ".", "serializer_name", ",", "[", "sc", "]", ")",...
[ 212, 4 ]
[ 219, 83 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_custom_field_serialization
(self)
Tests that custom fields serialize and deserialize intact
Tests that custom fields serialize and deserialize intact
def test_custom_field_serialization(self): """Tests that custom fields serialize and deserialize intact""" team_str = "Spartak Moskva" player = Player() player.name = "Soslan Djanaev" player.rank = 1 player.team = Team(team_str) player.save() serial_str = ...
[ "def", "test_custom_field_serialization", "(", "self", ")", ":", "team_str", "=", "\"Spartak Moskva\"", "player", "=", "Player", "(", ")", "player", ".", "name", "=", "\"Soslan Djanaev\"", "player", ".", "rank", "=", "1", "player", ".", "team", "=", "Team", ...
[ 221, 4 ]
[ 237, 49 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_pre_1000ad_date
(self)
Tests that year values before 1000AD are properly formatted
Tests that year values before 1000AD are properly formatted
def test_pre_1000ad_date(self): """Tests that year values before 1000AD are properly formatted""" # Regression for #12524 -- dates before 1000AD get prefixed # 0's on the year a = Article.objects.create( author=self.jane, headline="Nobody remembers the early years...
[ "def", "test_pre_1000ad_date", "(", "self", ")", ":", "# Regression for #12524 -- dates before 1000AD get prefixed", "# 0's on the year", "a", "=", "Article", ".", "objects", ".", "create", "(", "author", "=", "self", ".", "jane", ",", "headline", "=", "\"Nobody remem...
[ 239, 4 ]
[ 250, 81 ]
python
en
['en', 'en', 'en']
True
SerializersTestBase.test_pkless_serialized_strings
(self)
Tests that serialized strings without PKs can be turned into models
Tests that serialized strings without PKs can be turned into models
def test_pkless_serialized_strings(self): """ Tests that serialized strings without PKs can be turned into models """ deserial_objs = list(serializers.deserialize(self.serializer_name, self.pkless_str)) for obj in deser...
[ "def", "test_pkless_serialized_strings", "(", "self", ")", ":", "deserial_objs", "=", "list", "(", "serializers", ".", "deserialize", "(", "self", ".", "serializer_name", ",", "self", ".", "pkless_str", ")", ")", "for", "obj", "in", "deserial_objs", ":", "self...
[ 252, 4 ]
[ 262, 59 ]
python
en
['en', 'error', 'th']
False
SerializersTransactionTestBase.test_forward_refs
(self)
Tests that objects ids can be referenced before they are defined in the serialization data.
Tests that objects ids can be referenced before they are defined in the serialization data.
def test_forward_refs(self): """ Tests that objects ids can be referenced before they are defined in the serialization data. """ # The deserialization process needs to run in a transaction in order # to test forward reference handling. with transaction.atomic(): ...
[ "def", "test_forward_refs", "(", "self", ")", ":", "# The deserialization process needs to run in a transaction in order", "# to test forward reference handling.", "with", "transaction", ".", "atomic", "(", ")", ":", "objs", "=", "serializers", ".", "deserialize", "(", "sel...
[ 270, 4 ]
[ 287, 54 ]
python
en
['en', 'error', 'th']
False
NoYamlSerializerTestCase.setUpClass
(cls)
Removes imported yaml and stubs importlib.import_module
Removes imported yaml and stubs importlib.import_module
def setUpClass(cls): """Removes imported yaml and stubs importlib.import_module""" super(NoYamlSerializerTestCase, cls).setUpClass() cls._import_module_mock = YamlImportModuleMock() importlib.import_module = cls._import_module_mock.import_module # clear out cached serializers t...
[ "def", "setUpClass", "(", "cls", ")", ":", "super", "(", "NoYamlSerializerTestCase", ",", "cls", ")", ".", "setUpClass", "(", ")", "cls", ".", "_import_module_mock", "=", "YamlImportModuleMock", "(", ")", "importlib", ".", "import_module", "=", "cls", ".", "...
[ 469, 4 ]
[ 477, 37 ]
python
en
['en', 'en', 'en']
True
NoYamlSerializerTestCase.tearDownClass
(cls)
Puts yaml back if necessary
Puts yaml back if necessary
def tearDownClass(cls): """Puts yaml back if necessary""" super(NoYamlSerializerTestCase, cls).tearDownClass() importlib.import_module = cls._import_module_mock._import_module # clear out cached serializers to clean out BadSerializer instances serializers._serializers = {}
[ "def", "tearDownClass", "(", "cls", ")", ":", "super", "(", "NoYamlSerializerTestCase", ",", "cls", ")", ".", "tearDownClass", "(", ")", "importlib", ".", "import_module", "=", "cls", ".", "_import_module_mock", ".", "_import_module", "# clear out cached serializers...
[ 480, 4 ]
[ 487, 37 ]
python
en
['en', 'sn', 'en']
True
NoYamlSerializerTestCase.test_serializer_pyyaml_error_message
(self)
Using yaml serializer without pyyaml raises ImportError
Using yaml serializer without pyyaml raises ImportError
def test_serializer_pyyaml_error_message(self): """Using yaml serializer without pyyaml raises ImportError""" jane = Author(name="Jane") self.assertRaises(ImportError, serializers.serialize, "yaml", [jane])
[ "def", "test_serializer_pyyaml_error_message", "(", "self", ")", ":", "jane", "=", "Author", "(", "name", "=", "\"Jane\"", ")", "self", ".", "assertRaises", "(", "ImportError", ",", "serializers", ".", "serialize", ",", "\"yaml\"", ",", "[", "jane", "]", ")"...
[ 489, 4 ]
[ 492, 77 ]
python
en
['en', 'zu', 'sw']
False
NoYamlSerializerTestCase.test_deserializer_pyyaml_error_message
(self)
Using yaml deserializer without pyyaml raises ImportError
Using yaml deserializer without pyyaml raises ImportError
def test_deserializer_pyyaml_error_message(self): """Using yaml deserializer without pyyaml raises ImportError""" self.assertRaises(ImportError, serializers.deserialize, "yaml", "")
[ "def", "test_deserializer_pyyaml_error_message", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "ImportError", ",", "serializers", ".", "deserialize", ",", "\"yaml\"", ",", "\"\"", ")" ]
[ 494, 4 ]
[ 496, 75 ]
python
en
['en', 'zu', 'sw']
False
NoYamlSerializerTestCase.test_dumpdata_pyyaml_error_message
(self)
Calling dumpdata produces an error when yaml package missing
Calling dumpdata produces an error when yaml package missing
def test_dumpdata_pyyaml_error_message(self): """Calling dumpdata produces an error when yaml package missing""" with six.assertRaisesRegex(self, management.CommandError, YAML_IMPORT_ERROR_MESSAGE): management.call_command('dumpdata', format='yaml')
[ "def", "test_dumpdata_pyyaml_error_message", "(", "self", ")", ":", "with", "six", ".", "assertRaisesRegex", "(", "self", ",", "management", ".", "CommandError", ",", "YAML_IMPORT_ERROR_MESSAGE", ")", ":", "management", ".", "call_command", "(", "'dumpdata'", ",", ...
[ 498, 4 ]
[ 501, 62 ]
python
en
['en', 'en', 'en']
True
resolve_relation
(scope_model, relation)
Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model argument will be returned. * A bare model name wi...
Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model.
def resolve_relation(scope_model, relation): """ Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model arg...
[ "def", "resolve_relation", "(", "scope_model", ",", "relation", ")", ":", "# Check for recursive relations", "if", "relation", "==", "RECURSIVE_RELATIONSHIP_CONSTANT", ":", "relation", "=", "scope_model", "# Look for an \"app.Model\" relation", "if", "isinstance", "(", "rel...
[ 36, 0 ]
[ 58, 19 ]
python
en
['en', 'error', 'th']
False
lazy_related_operation
(function, model, *related_models, **kwargs)
Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus any optional keyword arguments. The `model` argument must be a model class...
Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus any optional keyword arguments.
def lazy_related_operation(function, model, *related_models, **kwargs): """ Schedule `function` to be called once `model` and all `related_models` have been imported and registered with the app registry. `function` will be called with the newly-loaded model classes as its positional arguments, plus ...
[ "def", "lazy_related_operation", "(", "function", ",", "model", ",", "*", "related_models", ",", "*", "*", "kwargs", ")", ":", "models", "=", "[", "model", "]", "+", "[", "resolve_relation", "(", "model", ",", "rel", ")", "for", "rel", "in", "related_mod...
[ 61, 0 ]
[ 79, 78 ]
python
en
['en', 'error', 'th']
False
RelatedField._check_clashes
(self)
Check accessor and reverse query name clashes.
Check accessor and reverse query name clashes.
def _check_clashes(self): """Check accessor and reverse query name clashes.""" from django.db.models.base import ModelBase errors = [] opts = self.model._meta # `f.remote_field.model` may be a string instead of a model. Skip if model name is # not resolved. if n...
[ "def", "_check_clashes", "(", "self", ")", ":", "from", "django", ".", "db", ".", "models", ".", "base", "import", "ModelBase", "errors", "=", "[", "]", "opts", "=", "self", ".", "model", ".", "_meta", "# `f.remote_field.model` may be a string instead of a model...
[ 189, 4 ]
[ 281, 21 ]
python
en
['en', 'en', 'en']
True
RelatedField.get_forward_related_filter
(self, obj)
Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an instance of self.related_field.model.
Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an instance of self.related_field.model.
def get_forward_related_filter(self, obj): """ Return the keyword arguments that when supplied to self.model.object.filter(), would select all instances related through this field to the remote obj. This is used to build the querysets returned by related descriptors. obj is an in...
[ "def", "get_forward_related_filter", "(", "self", ",", "obj", ")", ":", "return", "{", "'%s__%s'", "%", "(", "self", ".", "name", ",", "rh_field", ".", "name", ")", ":", "getattr", "(", "obj", ",", "rh_field", ".", "attname", ")", "for", "_", ",", "r...
[ 329, 4 ]
[ 340, 9 ]
python
en
['en', 'error', 'th']
False
RelatedField.get_reverse_related_filter
(self, obj)
Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an instance of self.model.
Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an instance of self.model.
def get_reverse_related_filter(self, obj): """ Complement to get_forward_related_filter(). Return the keyword arguments that when passed to self.related_field.model.object.filter() select all instances of self.related_field.model related through this field to obj. obj is an insta...
[ "def", "get_reverse_related_filter", "(", "self", ",", "obj", ")", ":", "base_filter", "=", "{", "rh_field", ".", "attname", ":", "getattr", "(", "obj", ",", "lh_field", ".", "attname", ")", "for", "lh_field", ",", "rh_field", "in", "self", ".", "related_f...
[ 342, 4 ]
[ 359, 21 ]
python
en
['en', 'error', 'th']
False
RelatedField.swappable_setting
(self)
Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False.
Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False.
def swappable_setting(self): """ Get the setting that this is powered from for swapping, or None if it's not swapped in / marked with swappable=False. """ if self.swappable: # Work out string form of "to" if isinstance(self.remote_field.model, str): ...
[ "def", "swappable_setting", "(", "self", ")", ":", "if", "self", ".", "swappable", ":", "# Work out string form of \"to\"", "if", "isinstance", "(", "self", ".", "remote_field", ".", "model", ",", "str", ")", ":", "to_string", "=", "self", ".", "remote_field",...
[ 362, 4 ]
[ 374, 19 ]
python
en
['en', 'error', 'th']
False
RelatedField.get_limit_choices_to
(self)
Return ``limit_choices_to`` for this model field. If it is a callable, it will be invoked and the result will be returned.
Return ``limit_choices_to`` for this model field.
def get_limit_choices_to(self): """ Return ``limit_choices_to`` for this model field. If it is a callable, it will be invoked and the result will be returned. """ if callable(self.remote_field.limit_choices_to): return self.remote_field.limit_choices_to() ...
[ "def", "get_limit_choices_to", "(", "self", ")", ":", "if", "callable", "(", "self", ".", "remote_field", ".", "limit_choices_to", ")", ":", "return", "self", ".", "remote_field", ".", "limit_choices_to", "(", ")", "return", "self", ".", "remote_field", ".", ...
[ 389, 4 ]
[ 398, 49 ]
python
en
['en', 'error', 'th']
False
RelatedField.formfield
(self, **kwargs)
Pass ``limit_choices_to`` to the field being constructed. Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the ``queryset`` to the field being constructed.
Pass ``limit_choices_to`` to the field being constructed.
def formfield(self, **kwargs): """ Pass ``limit_choices_to`` to the field being constructed. Only passes it if there is a type that supports related fields. This is a similar strategy used to pass the ``queryset`` to the field being constructed. """ defaults = {}...
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "}", "if", "hasattr", "(", "self", ".", "remote_field", ",", "'get_related_field'", ")", ":", "# If this is a callable, do not invoke it here. Just pass", "# it in the defaults...
[ 400, 4 ]
[ 418, 44 ]
python
en
['en', 'error', 'th']
False
RelatedField.related_query_name
(self)
Define the name that can be used to identify this related object in a table-spanning query.
Define the name that can be used to identify this related object in a table-spanning query.
def related_query_name(self): """ Define the name that can be used to identify this related object in a table-spanning query. """ return self.remote_field.related_query_name or self.remote_field.related_name or self.opts.model_name
[ "def", "related_query_name", "(", "self", ")", ":", "return", "self", ".", "remote_field", ".", "related_query_name", "or", "self", ".", "remote_field", ".", "related_name", "or", "self", ".", "opts", ".", "model_name" ]
[ 420, 4 ]
[ 425, 109 ]
python
en
['en', 'error', 'th']
False
RelatedField.target_field
(self)
When filtering against this relation, return the field on the remote model against which the filtering should happen.
When filtering against this relation, return the field on the remote model against which the filtering should happen.
def target_field(self): """ When filtering against this relation, return the field on the remote model against which the filtering should happen. """ target_fields = self.get_path_info()[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError(...
[ "def", "target_field", "(", "self", ")", ":", "target_fields", "=", "self", ".", "get_path_info", "(", ")", "[", "-", "1", "]", ".", "target_fields", "if", "len", "(", "target_fields", ")", ">", "1", ":", "raise", "exceptions", ".", "FieldError", "(", ...
[ 428, 4 ]
[ 437, 31 ]
python
en
['en', 'error', 'th']
False
ForeignObject.get_extra_descriptor_filter
(self, instance)
Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) call or a Q-object. The condition will be ANDed toge...
Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field.
def get_extra_descriptor_filter(self, instance): """ Return an extra filter condition for related object fetching when user does 'instance.fieldname', that is the extra filter is used in the descriptor of the field. The filter should be either a dict usable in .filter(**kwargs) ...
[ "def", "get_extra_descriptor_filter", "(", "self", ",", "instance", ")", ":", "return", "{", "}" ]
[ 668, 4 ]
[ 681, 17 ]
python
en
['en', 'error', 'th']
False
ForeignObject.get_extra_restriction
(self, where_class, alias, related_alias)
Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_alias' will not work in some conditions, like subquery pushdown. ...
Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method.
def get_extra_restriction(self, where_class, alias, related_alias): """ Return a pair condition used for joining and subquery pushdown. The condition is something that responds to as_sql(compiler, connection) method. Note that currently referring both the 'alias' and 'related_al...
[ "def", "get_extra_restriction", "(", "self", ",", "where_class", ",", "alias", ",", "related_alias", ")", ":", "return", "None" ]
[ 683, 4 ]
[ 695, 19 ]
python
en
['en', 'error', 'th']
False
ForeignObject.get_path_info
(self, filtered_relation=None)
Get path from this field to the related model.
Get path from this field to the related model.
def get_path_info(self, filtered_relation=None): """Get path from this field to the related model.""" opts = self.remote_field.model._meta from_opts = self.model._meta return [PathInfo( from_opts=from_opts, to_opts=opts, target_fields=self.foreign_rela...
[ "def", "get_path_info", "(", "self", ",", "filtered_relation", "=", "None", ")", ":", "opts", "=", "self", ".", "remote_field", ".", "model", ".", "_meta", "from_opts", "=", "self", ".", "model", ".", "_meta", "return", "[", "PathInfo", "(", "from_opts", ...
[ 697, 4 ]
[ 709, 10 ]
python
en
['en', 'en', 'en']
True
ForeignObject.get_reverse_path_info
(self, filtered_relation=None)
Get path from the related model to this field's model.
Get path from the related model to this field's model.
def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" opts = self.model._meta from_opts = self.remote_field.model._meta return [PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(...
[ "def", "get_reverse_path_info", "(", "self", ",", "filtered_relation", "=", "None", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "from_opts", "=", "self", ".", "remote_field", ".", "model", ".", "_meta", "return", "[", "PathInfo", "(", "from_...
[ 711, 4 ]
[ 723, 10 ]
python
en
['en', 'en', 'en']
True
ForeignKey.get_reverse_path_info
(self, filtered_relation=None)
Get path from the related model to this field's model.
Get path from the related model to this field's model.
def get_reverse_path_info(self, filtered_relation=None): """Get path from the related model to this field's model.""" opts = self.model._meta from_opts = self.remote_field.model._meta return [PathInfo( from_opts=from_opts, to_opts=opts, target_fields=(...
[ "def", "get_reverse_path_info", "(", "self", ",", "filtered_relation", "=", "None", ")", ":", "opts", "=", "self", ".", "model", ".", "_meta", "from_opts", "=", "self", ".", "remote_field", ".", "model", ".", "_meta", "return", "[", "PathInfo", "(", "from_...
[ 881, 4 ]
[ 893, 10 ]
python
en
['en', 'en', 'en']
True
ForeignKey.get_default
(self)
Return the to_field if the default value is an object.
Return the to_field if the default value is an object.
def get_default(self): """Return the to_field if the default value is an object.""" field_default = super().get_default() if isinstance(field_default, self.remote_field.model): return getattr(field_default, self.target_field.attname) return field_default
[ "def", "get_default", "(", "self", ")", ":", "field_default", "=", "super", "(", ")", ".", "get_default", "(", ")", "if", "isinstance", "(", "field_default", ",", "self", ".", "remote_field", ".", "model", ")", ":", "return", "getattr", "(", "field_default...
[ 925, 4 ]
[ 930, 28 ]
python
en
['en', 'en', 'en']
True
ManyToManyField._get_path_info
(self, direct=False, filtered_relation=None)
Called by both direct and indirect m2m traversal.
Called by both direct and indirect m2m traversal.
def _get_path_info(self, direct=False, filtered_relation=None): """Called by both direct and indirect m2m traversal.""" int_model = self.remote_field.through linkfield1 = int_model._meta.get_field(self.m2m_field_name()) linkfield2 = int_model._meta.get_field(self.m2m_reverse_field_name()...
[ "def", "_get_path_info", "(", "self", ",", "direct", "=", "False", ",", "filtered_relation", "=", "None", ")", ":", "int_model", "=", "self", ".", "remote_field", ".", "through", "linkfield1", "=", "int_model", ".", "_meta", ".", "get_field", "(", "self", ...
[ 1462, 4 ]
[ 1486, 62 ]
python
en
['en', 'en', 'en']
True
ManyToManyField._get_m2m_db_table
(self, opts)
Function that can be curried to provide the m2m table name for this relation.
Function that can be curried to provide the m2m table name for this relation.
def _get_m2m_db_table(self, opts): """ Function that can be curried to provide the m2m table name for this relation. """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table elif self.db_table: return self.db_ta...
[ "def", "_get_m2m_db_table", "(", "self", ",", "opts", ")", ":", "if", "self", ".", "remote_field", ".", "through", "is", "not", "None", ":", "return", "self", ".", "remote_field", ".", "through", ".", "_meta", ".", "db_table", "elif", "self", ".", "db_ta...
[ 1494, 4 ]
[ 1505, 88 ]
python
en
['en', 'error', 'th']
False
ManyToManyField._get_m2m_attr
(self, related, attr)
Function that can be curried to provide the source accessor or DB column name for the m2m table.
Function that can be curried to provide the source accessor or DB column name for the m2m table.
def _get_m2m_attr(self, related, attr): """ Function that can be curried to provide the source accessor or DB column name for the m2m table. """ cache_attr = '_m2m_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr) if self....
[ "def", "_get_m2m_attr", "(", "self", ",", "related", ",", "attr", ")", ":", "cache_attr", "=", "'_m2m_%s_cache'", "%", "attr", "if", "hasattr", "(", "self", ",", "cache_attr", ")", ":", "return", "getattr", "(", "self", ",", "cache_attr", ")", "if", "sel...
[ 1507, 4 ]
[ 1523, 48 ]
python
en
['en', 'error', 'th']
False
ManyToManyField._get_m2m_reverse_attr
(self, related, attr)
Function that can be curried to provide the related accessor or DB column name for the m2m table.
Function that can be curried to provide the related accessor or DB column name for the m2m table.
def _get_m2m_reverse_attr(self, related, attr): """ Function that can be curried to provide the related accessor or DB column name for the m2m table. """ cache_attr = '_m2m_reverse_%s_cache' % attr if hasattr(self, cache_attr): return getattr(self, cache_attr)...
[ "def", "_get_m2m_reverse_attr", "(", "self", ",", "related", ",", "attr", ")", ":", "cache_attr", "=", "'_m2m_reverse_%s_cache'", "%", "attr", "if", "hasattr", "(", "self", ",", "cache_attr", ")", ":", "return", "getattr", "(", "self", ",", "cache_attr", ")"...
[ 1525, 4 ]
[ 1553, 40 ]
python
en
['en', 'error', 'th']
False
update_contenttypes
(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs)
Creates content types for models in the given app, removing any model entries that no longer have a matching model class.
Creates content types for models in the given app, removing any model entries that no longer have a matching model class.
def update_contenttypes(app_config, verbosity=2, interactive=True, using=DEFAULT_DB_ALIAS, **kwargs): """ Creates content types for models in the given app, removing any model entries that no longer have a matching model class. """ if not app_config.models_module: return try: Co...
[ "def", "update_contenttypes", "(", "app_config", ",", "verbosity", "=", "2", ",", "interactive", "=", "True", ",", "using", "=", "DEFAULT_DB_ALIAS", ",", "*", "*", "kwargs", ")", ":", "if", "not", "app_config", ".", "models_module", ":", "return", "try", "...
[ 8, 0 ]
[ 86, 52 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.add_dependency
(self, migration, child, parent, skip_validation=False)
This may create dummy nodes if they don't yet exist. If `skip_validation=True`, validate_consistency() should be called afterwards.
This may create dummy nodes if they don't yet exist. If `skip_validation=True`, validate_consistency() should be called afterwards.
def add_dependency(self, migration, child, parent, skip_validation=False): """ This may create dummy nodes if they don't yet exist. If `skip_validation=True`, validate_consistency() should be called afterwards. """ if child not in self.nodes: error_message = (...
[ "def", "add_dependency", "(", "self", ",", "migration", ",", "child", ",", "parent", ",", "skip_validation", "=", "False", ")", ":", "if", "child", "not", "in", "self", ".", "nodes", ":", "error_message", "=", "(", "\"Migration %s dependencies reference nonexist...
[ 98, 4 ]
[ 119, 39 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.remove_replaced_nodes
(self, replacement, replaced)
Remove each of the `replaced` nodes (when they exist). Any dependencies that were referencing them are changed to reference the `replacement` node instead.
Remove each of the `replaced` nodes (when they exist). Any dependencies that were referencing them are changed to reference the `replacement` node instead.
def remove_replaced_nodes(self, replacement, replaced): """ Remove each of the `replaced` nodes (when they exist). Any dependencies that were referencing them are changed to reference the `replacement` node instead. """ # Cast list of replaced keys to set to speed up look...
[ "def", "remove_replaced_nodes", "(", "self", ",", "replacement", ",", "replaced", ")", ":", "# Cast list of replaced keys to set to speed up lookup later.", "replaced", "=", "set", "(", "replaced", ")", "try", ":", "replacement_node", "=", "self", ".", "node_map", "["...
[ 121, 4 ]
[ 154, 58 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.remove_replacement_node
(self, replacement, replaced)
The inverse operation to `remove_replaced_nodes`. Almost. Remove the replacement node `replacement` and remap its child nodes to `replaced` - the list of nodes it would have replaced. Don't remap its parent nodes as they are expected to be correct already.
The inverse operation to `remove_replaced_nodes`. Almost. Remove the replacement node `replacement` and remap its child nodes to `replaced` - the list of nodes it would have replaced. Don't remap its parent nodes as they are expected to be correct already.
def remove_replacement_node(self, replacement, replaced): """ The inverse operation to `remove_replaced_nodes`. Almost. Remove the replacement node `replacement` and remap its child nodes to `replaced` - the list of nodes it would have replaced. Don't remap its parent nodes as th...
[ "def", "remove_replacement_node", "(", "self", ",", "replacement", ",", "replaced", ")", ":", "self", ".", "nodes", ".", "pop", "(", "replacement", ",", "None", ")", "try", ":", "replacement_node", "=", "self", ".", "node_map", ".", "pop", "(", "replacemen...
[ 156, 4 ]
[ 188, 52 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.validate_consistency
(self)
Ensure there are no dummy nodes remaining in the graph.
Ensure there are no dummy nodes remaining in the graph.
def validate_consistency(self): """Ensure there are no dummy nodes remaining in the graph.""" [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)]
[ "def", "validate_consistency", "(", "self", ")", ":", "[", "n", ".", "raise_error", "(", ")", "for", "n", "in", "self", ".", "node_map", ".", "values", "(", ")", "if", "isinstance", "(", "n", ",", "DummyNode", ")", "]" ]
[ 192, 4 ]
[ 194, 85 ]
python
en
['en', 'en', 'en']
True
MigrationGraph.forwards_plan
(self, target)
Given a node, return a list of which previous nodes (dependencies) must be applied, ending with the node itself. This is the list you would follow if applying the migrations to a database.
Given a node, return a list of which previous nodes (dependencies) must be applied, ending with the node itself. This is the list you would follow if applying the migrations to a database.
def forwards_plan(self, target): """ Given a node, return a list of which previous nodes (dependencies) must be applied, ending with the node itself. This is the list you would follow if applying the migrations to a database. """ if target not in self.nodes: r...
[ "def", "forwards_plan", "(", "self", ",", "target", ")", ":", "if", "target", "not", "in", "self", ".", "nodes", ":", "raise", "NodeNotFoundError", "(", "\"Node %r not a valid node\"", "%", "(", "target", ",", ")", ",", "target", ")", "return", "self", "."...
[ 196, 4 ]
[ 204, 56 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.backwards_plan
(self, target)
Given a node, return a list of which dependent nodes (dependencies) must be unapplied, ending with the node itself. This is the list you would follow if removing the migrations from a database.
Given a node, return a list of which dependent nodes (dependencies) must be unapplied, ending with the node itself. This is the list you would follow if removing the migrations from a database.
def backwards_plan(self, target): """ Given a node, return a list of which dependent nodes (dependencies) must be unapplied, ending with the node itself. This is the list you would follow if removing the migrations from a database. """ if target not in self.nodes: ...
[ "def", "backwards_plan", "(", "self", ",", "target", ")", ":", "if", "target", "not", "in", "self", ".", "nodes", ":", "raise", "NodeNotFoundError", "(", "\"Node %r not a valid node\"", "%", "(", "target", ",", ")", ",", "target", ")", "return", "self", "....
[ 206, 4 ]
[ 214, 72 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.iterative_dfs
(self, start, forwards=True)
Iterative depth-first search for finding dependencies.
Iterative depth-first search for finding dependencies.
def iterative_dfs(self, start, forwards=True): """Iterative depth-first search for finding dependencies.""" visited = [] visited_set = set() stack = [(start, False)] while stack: node, processed = stack.pop() if node in visited_set: pass ...
[ "def", "iterative_dfs", "(", "self", ",", "start", ",", "forwards", "=", "True", ")", ":", "visited", "=", "[", "]", "visited_set", "=", "set", "(", ")", "stack", "=", "[", "(", "start", ",", "False", ")", "]", "while", "stack", ":", "node", ",", ...
[ 216, 4 ]
[ 231, 22 ]
python
en
['en', 'en', 'en']
True
MigrationGraph.root_nodes
(self, app=None)
Return all root nodes - that is, nodes with no dependencies inside their app. These are the starting point for an app.
Return all root nodes - that is, nodes with no dependencies inside their app. These are the starting point for an app.
def root_nodes(self, app=None): """ Return all root nodes - that is, nodes with no dependencies inside their app. These are the starting point for an app. """ roots = set() for node in self.nodes: if all(key[0] != node[0] for key in self.node_map[node].parents...
[ "def", "root_nodes", "(", "self", ",", "app", "=", "None", ")", ":", "roots", "=", "set", "(", ")", "for", "node", "in", "self", ".", "nodes", ":", "if", "all", "(", "key", "[", "0", "]", "!=", "node", "[", "0", "]", "for", "key", "in", "self...
[ 233, 4 ]
[ 242, 28 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.leaf_nodes
(self, app=None)
Return all leaf nodes - that is, nodes with no dependents in their app. These are the "most current" version of an app's schema. Having more than one per app is technically an error, but one that gets handled further up, in the interactive command - it's usually the result of a ...
Return all leaf nodes - that is, nodes with no dependents in their app. These are the "most current" version of an app's schema. Having more than one per app is technically an error, but one that gets handled further up, in the interactive command - it's usually the result of a ...
def leaf_nodes(self, app=None): """ Return all leaf nodes - that is, nodes with no dependents in their app. These are the "most current" version of an app's schema. Having more than one per app is technically an error, but one that gets handled further up, in the interactive comm...
[ "def", "leaf_nodes", "(", "self", ",", "app", "=", "None", ")", ":", "leaves", "=", "set", "(", ")", "for", "node", "in", "self", ".", "nodes", ":", "if", "all", "(", "key", "[", "0", "]", "!=", "node", "[", "0", "]", "for", "key", "in", "sel...
[ 244, 4 ]
[ 256, 29 ]
python
en
['en', 'error', 'th']
False
MigrationGraph.make_state
(self, nodes=None, at_end=True, real_apps=None)
Given a migration node or nodes, return a complete ProjectState for it. If at_end is False, return the state before the migration has run. If nodes is not provided, return the overall most current project state.
Given a migration node or nodes, return a complete ProjectState for it. If at_end is False, return the state before the migration has run. If nodes is not provided, return the overall most current project state.
def make_state(self, nodes=None, at_end=True, real_apps=None): """ Given a migration node or nodes, return a complete ProjectState for it. If at_end is False, return the state before the migration has run. If nodes is not provided, return the overall most current project state. "...
[ "def", "make_state", "(", "self", ",", "nodes", "=", "None", ",", "at_end", "=", "True", ",", "real_apps", "=", "None", ")", ":", "if", "nodes", "is", "None", ":", "nodes", "=", "list", "(", "self", ".", "leaf_nodes", "(", ")", ")", "if", "not", ...
[ 299, 4 ]
[ 315, 28 ]
python
en
['en', 'error', 'th']
False
_check_keys_and_values
(result)
Check that given dict represents equipment data in correct form.
Check that given dict represents equipment data in correct form.
def _check_keys_and_values(result): """ Check that given dict represents equipment data in correct form. """ assert len(result) == 3 # id, name, equipments assert result['id'] != '' assert result['name'] == {'fi': 'test equipment category'} equipments = result['equipment'] assert len(eq...
[ "def", "_check_keys_and_values", "(", "result", ")", ":", "assert", "len", "(", "result", ")", "==", "3", "# id, name, equipments", "assert", "result", "[", "'id'", "]", "!=", "''", "assert", "result", "[", "'name'", "]", "==", "{", "'fi'", ":", "'test equ...
[ 19, 0 ]
[ 31, 32 ]
python
en
['en', 'error', 'th']
False
test_disallowed_methods
(all_user_types_api_client, list_url, detail_url)
Tests that only safe methods are allowed to equipment list and detail endpoints.
Tests that only safe methods are allowed to equipment list and detail endpoints.
def test_disallowed_methods(all_user_types_api_client, list_url, detail_url): """ Tests that only safe methods are allowed to equipment list and detail endpoints. """ check_disallowed_methods(all_user_types_api_client, (list_url, detail_url), UNSAFE_METHODS)
[ "def", "test_disallowed_methods", "(", "all_user_types_api_client", ",", "list_url", ",", "detail_url", ")", ":", "check_disallowed_methods", "(", "all_user_types_api_client", ",", "(", "list_url", ",", "detail_url", ")", ",", "UNSAFE_METHODS", ")" ]
[ 35, 0 ]
[ 39, 95 ]
python
en
['en', 'error', 'th']
False
test_get_equipment_category_list
(api_client, list_url, equipment)
Tests that equipment category list endpoint returns equipment category data in correct form.
Tests that equipment category list endpoint returns equipment category data in correct form.
def test_get_equipment_category_list(api_client, list_url, equipment): """ Tests that equipment category list endpoint returns equipment category data in correct form. """ response = api_client.get(list_url) results = response.data['results'] assert len(results) == 1 _check_keys_and_values(r...
[ "def", "test_get_equipment_category_list", "(", "api_client", ",", "list_url", ",", "equipment", ")", ":", "response", "=", "api_client", ".", "get", "(", "list_url", ")", "results", "=", "response", ".", "data", "[", "'results'", "]", "assert", "len", "(", ...
[ 43, 0 ]
[ 50, 38 ]
python
en
['en', 'error', 'th']
False
test_get_equipment_category_list
(api_client, detail_url, equipment)
Tests that equipment category detail endpoint returns equipment category data in correct form.
Tests that equipment category detail endpoint returns equipment category data in correct form.
def test_get_equipment_category_list(api_client, detail_url, equipment): """ Tests that equipment category detail endpoint returns equipment category data in correct form. """ response = api_client.get(detail_url) _check_keys_and_values(response.data)
[ "def", "test_get_equipment_category_list", "(", "api_client", ",", "detail_url", ",", "equipment", ")", ":", "response", "=", "api_client", ".", "get", "(", "detail_url", ")", "_check_keys_and_values", "(", "response", ".", "data", ")" ]
[ 54, 0 ]
[ 59, 41 ]
python
en
['en', 'error', 'th']
False
BotTest.test_bot_add_subscription
(self)
Calling POST /json/users/me/subscriptions should successfully add streams, and a stream to the list of subscriptions and confirm the right number of events are generated. When 'principals' has a bot, no notification message event or invitation email is sent when add_subs...
Calling POST /json/users/me/subscriptions should successfully add streams, and a stream to the list of subscriptions and confirm the right number of events are generated. When 'principals' has a bot, no notification message event or invitation email is sent when add_subs...
def test_bot_add_subscription(self) -> None: """ Calling POST /json/users/me/subscriptions should successfully add streams, and a stream to the list of subscriptions and confirm the right number of events are generated. When 'principals' has a bot, no notification message...
[ "def", "test_bot_add_subscription", "(", "self", ")", "->", "None", ":", "hamlet", "=", "self", ".", "example_user", "(", "\"hamlet\"", ")", "iago", "=", "self", ".", "example_user", "(", "\"iago\"", ")", "self", ".", "login_user", "(", "hamlet", ")", "# N...
[ 375, 4 ]
[ 420, 45 ]
python
en
['en', 'error', 'th']
False
BotTest.test_deactivate_bogus_bot
(self)
Deleting a bogus bot will succeed silently.
Deleting a bogus bot will succeed silently.
def test_deactivate_bogus_bot(self) -> None: """Deleting a bogus bot will succeed silently.""" self.login("hamlet") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) invalid_user_id = 1000 result = self.client_delete(f"/json/bots/{inval...
[ "def", "test_deactivate_bogus_bot", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "assert_num_bots_equal", "(", "0", ")", "self", ".", "create_bot", "(", ")", "self", ".", "assert_num_bots_equal", "(", "1", ...
[ 576, 4 ]
[ 585, 37 ]
python
en
['en', 'en', 'en']
True
BotTest.test_bot_deactivation_attacks
(self)
You cannot deactivate somebody else's bot.
You cannot deactivate somebody else's bot.
def test_bot_deactivation_attacks(self) -> None: """You cannot deactivate somebody else's bot.""" self.login("hamlet") self.assert_num_bots_equal(0) self.create_bot() self.assert_num_bots_equal(1) # Have Othello try to deactivate both Hamlet and # Hamlet's bot. ...
[ "def", "test_bot_deactivation_attacks", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "assert_num_bots_equal", "(", "0", ")", "self", ".", "create_bot", "(", ")", "self", ".", "assert_num_bots_equal", "(", "1...
[ 636, 4 ]
[ 662, 37 ]
python
en
['en', 'en', 'en']
True
BotTest.test_patch_bogus_bot
(self)
Deleting a bogus bot will succeed silently.
Deleting a bogus bot will succeed silently.
def test_patch_bogus_bot(self) -> None: """Deleting a bogus bot will succeed silently.""" self.login("hamlet") self.create_bot() bot_info = { "full_name": "Fred", } invalid_user_id = 1000 result = self.client_patch(f"/json/bots/{invalid_user_id}", bot_...
[ "def", "test_patch_bogus_bot", "(", "self", ")", "->", "None", ":", "self", ".", "login", "(", "\"hamlet\"", ")", "self", ".", "create_bot", "(", ")", "bot_info", "=", "{", "\"full_name\"", ":", "\"Fred\"", ",", "}", "invalid_user_id", "=", "1000", "result...
[ 1388, 4 ]
[ 1398, 37 ]
python
en
['en', 'en', 'en']
True