Sample

pyint-b01167fa013f-I10

Deterministically remove some optional blank lines and bracketed line breaks

Matched original source

Lines194

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0060–1; higher is more readable
Mi0.0960–1; higher is more readable
LLOC100Logical lines; fewer is more readable
DeepSeek V4 Pro50–20; mean of three runs
GPT-6.1 Sol13.330–20; mean of three runs
BTTF0.270–1; higher is more readable

Views

Source code

from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, AdminUserCreationForm, UserChangeForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = "admin/auth/user/add_form.html" change_user_password_template = None fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("first_name", "last_name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "usable_password", "password1", "password2"), }, ), ) form = UserChangeForm add_form = AdminUserCreationForm change_password_form = AdminPasswordChangeForm list_display = ("username", "email", "first_name", "last_name", "is_staff") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("username", "first_name", "last_name", "email") ordering = ("username",) filter_horizontal = ( "groups", "user_permissions", ) def get_fieldsets(self, request, obj=None): if not obj: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if obj is None: defaults["form"] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( "<id>/password/", self.admin_site.admin_view(self.user_change_password), name="auth_user_password_change", ), *super().get_urls(), ] def lookup_allowed(self, lookup, value, request): # Don't allow lookups involving passwords. return not lookup.startswith("password") and super().lookup_allowed( lookup, value, request ) @method_decorator([sensitive_post_parameters(), csrf_protect]) def add_view(self, request, form_url="", extra_context=None): if request.method in ("GET", "HEAD", "OPTIONS", "TRACE"): return self._add_view(request, form_url, extra_context) with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url="", extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not self.has_change_permission(request): if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' "order to add users, Django requires that your user " 'account have both the "Add user" and "Change user" ' "permissions set." ) raise PermissionDenied if extra_context is None: extra_context = {} username_field = self.opts.get_field(self.model.USERNAME_FIELD) defaults = { "auto_populated_fields": (), "username_help_text": username_field.help_text, } extra_context.update(defaults) return super().add_view(request, form_url, extra_context) @method_decorator(sensitive_post_parameters()) def user_change_password(self, request, id, form_url=""): user = self.get_object(request, unquote(id)) if not self.has_change_permission(request, user): raise PermissionDenied if user is None: raise Http404( _("%(name)s object with primary key %(key)r does not exist.") % { "name": self.opts.verbose_name, "key": escape(id), } ) if request.method == "POST": form = self.change_password_form(user, request.POST) if form.is_valid(): # If disabling password-based authentication was requested # (via the form field `usable_password`), the submit action # must be "unset-password". This check is most relevant when # the admin user has two submit buttons available (for example # when Javascript is disabled). valid_submission = ( form.cleaned_data["set_usable_password"] or "unset-password" in request.POST ) if not valid_submission: msg = gettext("Conflicting form data submitted. Please try again.") messages.error(request, msg) return HttpResponseRedirect(request.get_full_path()) user = form.save() change_message = self.construct_change_message(request, form, None) self.log_change(request, user, change_message) if user.has_usable_password(): msg = gettext("Password changed successfully.") else: msg = gettext("Password-based authentication was disabled.") messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( "%s:%s_%s_change" % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) else: form = self.change_password_form(user) fieldsets = [(None, {"fields": list(form.base_fields)})] admin_form = admin.helpers.AdminForm(form, fieldsets, {}) if user.has_usable_password(): title = _("Change password: %s") else: title = _("Set password: %s") context = { "title": title % escape(user.get_username()), "adminForm": admin_form, "form_url": form_url, "form": form, "is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), "is_popup_var": IS_POPUP_VAR, "add": True, "change": False, "has_delete_permission": False, "has_change_permission": True, "has_absolute_url": False, "opts": self.opts, "original": user, "save_as": False, "show_save": True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or "admin/auth/user/change_password.html", context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if "_addanother" not in request.POST and IS_POPUP_VAR not in request.POST: request.POST = request.POST.copy() request.POST["_continue"] = 1 return super().response_add(request, obj, post_url_continue)

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.9397.215−310.108
Source linesThe number of non-empty source lines.194+77.6
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.343−6.514

Intercept 8.87 + feature contributions = -230.153 (log-odds).
Score = sigmoid(-230.153) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.248.99−6.881
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.195−5.868
Indentation frequencyHow rapidly indentation changes from line to line.169+5.108
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.169−3.457
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.248.985+3.213
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.193.908+2.301
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.061+0.344

Intercept 0.07 + feature contributions = -5.17 (log-odds).
Score = sigmoid(-5.17) = 0.006.

Score0.096
Score100
Run 1

The code is severely unreadable due to inconsistent and bizarre indentation throughout. Tuple/list definitions for fieldsets, add_fieldsets, get_urls, reverse, and context dictionaries have random spacing and line breaks that break visual flow. Many lines combine multiple actions or are split arbitrarily, undermining action granularity. While the underlying logic (Django UserAdmin) is familiar and docstrings are clear, the formatting obscures intent and structure. Deeply nested permission checks and long method bodies add complexity, but the primary failure is the chaotic whitespace, which makes even simple assignments hard to parse. Refactoring with standard formatting, extracting helper methods, and flattening conditionals would dramatically improve readability.

Run 2

The code exhibits severe readability issues across all criteria. Structure is tangled due to inconsistent and excessive indentation in fieldsets, add_fieldsets, and method calls. Nesting is deep in methods like user_change_password, with multiple nested conditionals and error-handling paths. Intent is obscured by dense blocks and scattered inline comments. Length is excessive for what could be more concise logic, and action granularity is poor—many lines contain multiple logical actions or broken continuations. Reading flow is severely disrupted by the erratic alignment and lack of visual separation between class methods. While the code follows Django conventions functionally, its formatting undermines clarity, making it difficult to parse and maintain.

Run 3

This code is challenging to read due to inconsistent formatting, excessive indentation, and poor visual separation. The imports are logical but have awkward multi-line alignment. The fieldsets and add_fieldsets definitions suffer from severe indentation issues, with closing brackets misaligned and inconsistent spacing. Method bodies contain unnecessary line breaks and deeply indented multi-line arguments, especially in `user_change_password` and `lookup_allowed`. The `_add_view` method has good comments explaining business logic, but the surrounding code's poor structural formatting negates clarity. Reading flow is disrupted by erratic line lengths and vertical misalignment. Methods are logically organized and have clear names, but the physical layout requires significant effort to follow. Several lines concatenate multiple conceptually distinct operations (e.g., combining form validation with conditional logic). While the code's intent is understandable, its presentation is markedly inconsistent with Django's typical formatting standards.

Run 1

1. Code Structure: Configuration and behavior are logically organized within a Django admin class, with distinct methods for individual workflows. Missing blank lines weaken visual separation. 2. Nesting: Most methods are shallow, but password handling has several nested conditionals and complex expressions. 3. Clarity of intent: Descriptive names, familiar Django conventions, and explanatory comments make permissions and password workflows understandable. 4. Code length: Generally justified by functionality, although the password-change method is long and some comments are verbose. 5. Action granularity: Most statements perform one action, but multiple configuration entries crowded onto single lines reduce scanability. 6. Reading flow: Execution order is coherent, yet irregular spacing, awkward line breaks, and densely packed dictionaries and tuples repeatedly interrupt reading.

Run 2

Code Structure: Imports, configuration, and specialized admin methods are logically organized, but inconsistent spacing and missing method separators obscure boundaries. Nesting: Mostly shallow, with moderate nesting in password-change handling; early returns help limit complexity. Clarity of intent: Descriptive names, familiar Django patterns, and explanatory comments make permissions and password workflows understandable. Code length: Generally justified by functionality, though verbose comments and a long password-change method increase reading effort. Action granularity: Most statements perform one action, but several configuration entries share lines, weakening visual separation. Reading flow: The sequence from validation through saving, messaging, and rendering is natural, but irregular indentation, excessive inline whitespace, and awkwardly wrapped expressions repeatedly interrupt scanning.

Run 3

Code Structure: The class logically groups admin configuration and workflow methods, though the password-change method combines several responsibilities. Nesting: Most methods are shallow, but POST handling introduces multiple nested conditions. Clarity of intent: Descriptive names, recognizable Django conventions, and explanatory security comments make the purpose clear. Code length: Generally justified by the functionality, although lengthy comments and the large password-change method increase reading effort. Action granularity: Most executable statements perform one action per line, but multiple configuration entries share lines, reducing scanability. Reading flow: Method order and control flow are coherent, but inconsistent whitespace, awkward line breaks, crowded dictionary entries, and missing blank lines between some methods substantially disrupt visual readability.