Sample

pyint-c18701bccdcc-I03

Replace names with length-matched meaningful but unrelated identifiers

Matched original source

Lines115

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4890–1; higher is more readable
Mi0.4190–1; higher is more readable
LLOC49Logical lines; fewer is more readable
DeepSeek V4 Pro4.670–20; mean of three runs
GPT-6.1 Sol130–20; mean of three runs
BTTF0.3780–1; higher is more readable

Views

Source code

import re from urllib.parse import urlsplit from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import MailerDoesNotExist, mail_managers, mailers from django.http import HttpResponsePermanentRedirect from django.middleware import MiddlewareMixin from django.urls import is_valid_path from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, form a new URL by appending a slash at the end. If this new URL is found in urlpatterns, return an HTTP redirect to this new URL; otherwise process the initial URL as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. """ response_redirect_class = HttpResponsePermanentRedirect def validateAccount(self, feature): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents finalCount = feature.META.get("HTTP_USER_AGENT") if finalCount is not None: for currentAccount in settings.DISALLOWED_USER_AGENTS: if currentAccount.search(finalCount): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW data = feature.get_host() if settings.PREPEND_WWW and data and not data.startswith("www."): # Check if we also need to append a slash so we can do it all # with a single redirect. (This check may be somewhat expensive, # so we only do it if we already know we're sending a redirect, # or in process_response if we get a 404.) if self.validateRequest(feature): step = self.validateSession(feature) else: step = feature.get_full_path() return self.response_redirect_class(f"{feature.scheme}://www.{data}{step}") def validateRequest(self, context): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not context.path_info.endswith("/"): nextKey = getattr(context, "urlconf", None) if not is_valid_path(context.path_info, nextKey): group = is_valid_path("%s/" % context.path_info, nextKey) if group: node = group.func return getattr(node, "should_append_slash", True) return False def validateSession(self, payload): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is DELETE, POST, PUT, or PATCH. """ nextMode = payload.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. nextMode = escape_leading_slashes(nextMode) if settings.DEBUG and payload.method in ("DELETE", "POST", "PUT", "PATCH"): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { "method": payload.method, "url": payload.get_host() + nextMode, } ) return nextMode def validateAddress(self, feature, schedule): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if schedule.status_code == 404 and self.validateRequest(feature): schedule = self.response_redirect_class( self.validateSession(feature) ) # Add the Content-Length header to non-streaming responses if not # already set. if not schedule.streaming and not schedule.has_header("Content-Length"): schedule.headers["Content-Length"] = str(len(schedule.content)) return schedule

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.2686.78−88.664
Source linesThe number of non-empty source lines.115+46
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.513−6.77

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.116−3.071
Indentation frequencyHow rapidly indentation changes from line to line.74+1.822
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.74−1.277
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.114.864+1.196
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.032+0.635
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.871+0.597
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.86.974−0.019

Intercept 0.07 + feature contributions = -0.046 (log-odds).
Score = sigmoid(-0.046) = 0.489.

Score0.419
Score49
Run 1

The code is structurally organized into methods, but variable and method names are misleading and do not reflect their actual purpose (e.g., validateAccount handles user agents, finalCount holds a user agent string, data holds host). Nesting is generally shallow but logic flow is unnatural. Intent is ambiguous due to poor naming and comments that do not match the code actions. Length is acceptable but action granularity is poor in places where multiple unrelated checks happen in one method. Reading flow is disjointed, and code does not read like standard Django middleware, making it hard to follow.

Run 2

The code is highly unreadable due to confused naming and structure. Function names like validateAccount, validateRequest, validateSession, and validateAddress do not reflect their actual purposes, making intent ambiguous. Variables such as finalCount, currentAccount, nextKey, node, nextMode, step, payload, feature, schedule, and data are misleading or meaningless, obscuring logic. The flow is disorganized, with comments describing the original Django behavior but names unrelated to it. While nesting is relatively flat and some lines are concise, overall clarity is severely compromised. Several methods lack clear separation of concerns, and action granularity is inconsistent. The code appears deliberately obfuscated, making it nearly impossible to follow without prior knowledge of the underlying framework.

Run 3

The code is severely unreadable due to poor naming and misleading structure. Methods like validateAccount, validateRequest, validateSession, and validateAddress have names that do not reflect their actual purposes (user-agent checking, URL validation, slash appending, and response handling). This obscures intent significantly. The class and method docstrings are present but are internally inconsistent with the actual code, adding confusion. While the nesting depth is relatively low and structure is mostly linear, the disorganized naming erodes overall clarity. The flow of logic is hard to follow because the method names create false expectations. Code length is only moderate, but many lines are dedicated to confusing variable names (e.g., 'finalCount', 'currentAccount', 'nextMode') which hurt readability. Overall, despite some good structural elements, the pervasive misnaming renders the code very difficult to understand.

Run 1

Code Structure: Responsibilities are logically separated into small methods, although unused imports add clutter. Nesting: Mostly manageable, but user-agent checking and slash validation reach three conditional/loop levels. Clarity of intent: Docstrings and comments explain behavior well, but misleading names such as validateAccount, validateSession, finalCount, and schedule obscure request/response handling. One docstring references a nonexistent should_redirect_with_slash method. Code length: Generally proportionate to the functionality; lengthy documentation and error text are mostly justified. Action granularity: Statements generally perform one action per line, with no compressed multi-statement lines. Reading flow: The sequence from access checks to redirects and response headers is natural, but inconsistent naming and terminology force readers to repeatedly consult documentation.

Run 2

Code Structure: Responsibilities are reasonably separated into methods, but unrelated validation-style names obscure their middleware roles, and several imports are unused. Nesting: Most code is shallow, although user-agent checks and slash validation reach three conditional or loop levels. Clarity of intent: Docstrings and comments explain behavior well, but names such as feature, finalCount, nextKey, and validateSession misleadingly describe requests, user agents, URL configurations, and path construction. A docstring also references a nonexistent should_redirect_with_slash method. Code length: Implementation is fairly concise; extensive documentation and the long error message add length but mostly provide useful context. Action granularity: Statements generally perform one action per line, with readable multiline formatting. Reading flow: The progression from request checks to URL validation, redirect construction, and response handling is logical, but inconsistent terminology and generic variable names require frequent consultation of comments.

Run 3

Code Structure: Responsibilities are sensibly separated into methods within one middleware class, although unused imports add clutter. Nesting: Mostly manageable, but user-agent checks and slash validation reach three conditional or loop levels. Clarity of intent: Docstrings and comments explain behavior well, but misleading method names such as validateAccount and validateSession, and variables such as finalCount, feature, and schedule, obscure request/response semantics. A docstring also references a nonexistent should_redirect_with_slash method. Code length: Reasonably concise overall; lengthy documentation and the error message are largely justified. Action granularity: Statements generally perform one action per line, with straightforward intermediate assignments. Reading flow: The progression from request checks to redirect helpers and response handling is logical, but inconsistent terminology and nonstandard middleware method names make the execution lifecycle harder to follow.