Sample

pyint-6b67ad2fa5d0-I11

Split eligible integer literals into pairs of short-named intermediate variables

Matched original source

Lines117

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.8360–1; higher is more readable
Mi0.4030–1; higher is more readable
LLOC51Logical lines; fewer is more readable
DeepSeek V4 Pro140–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.4340–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 process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get("HTTP_USER_AGENT") if user_agent is not None: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(user_agent): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() if settings.PREPEND_WWW and host and not host.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.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() return self.response_redirect_class(f"{request.scheme}://www.{host}{path}") def should_redirect_with_slash(self, request): """ 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 request.path_info.endswith("/"): urlconf = getattr(request, "urlconf", None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path("%s/" % request.path_info, urlconf) if match: view = match.func return getattr(view, "should_append_slash", True) return False def get_full_path_with_slash(self, request): """ 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. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.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": request.method, "url": request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ 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. a = 202 b = 202 if response.status_code == (a + b) and self.should_redirect_with_slash(request): response = self.response_redirect_class( self.get_full_path_with_slash(request) ) # Add the Content-Length header to non-streaming responses if not # already set. if not response.streaming and not response.has_header("Content-Length"): response.headers["Content-Length"] = str(len(response.content)) return response

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.2755.849−90.943
Source linesThe number of non-empty source lines.117+46.8
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.505−6.758

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.118−3.142
Indentation frequencyHow rapidly indentation changes from line to line.76+1.892
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.116.91+1.224
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.032+0.632
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.87.805+0.612
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.1+0.398
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.87.958−0.06

Intercept 0.07 + feature contributions = 1.626 (log-odds).
Score = sigmoid(1.626) = 0.836.

Score0.403
Score51
Run 1

The code is generally well-structured with clear method separation and comprehensive docstrings, showing good intent. The class-based organization and imports are logical. However, the process_response method contains confusing logic: `a = 202; b = 202; if response.status_code == (a + b)` is misleading — it suggests 404 but the sum is 404 only if a+b=404, which is wrong here (202+202=404 is coincidental but the variable naming obscures intent). The nesting depth is moderate but acceptable. Some comments are redundant with docstrings. The User-Agent loop adds nesting, but it's necessary. The length is reasonable given the middleware's complexity. Action granularity is mostly one action per line, with some exceptions in conditionals. Reading flow is natural aside from the odd status-code check. Overall, readability is good but impaired by the cryptic status code comparison that should simply use 404 directly.

Run 2

The code is generally organized into logical methods with clear docstrings, and it follows Django middleware conventions. The nesting is moderate, with only a few conditional layers. Most actions are one per line, and intent is mostly clear. However, several issues reduce readability: the use of `a = 202` and `b = 202` is unnecessarily obscure and makes the status-code check confusing; the `MailerDoesNotExist` and `mail_managers` imports are unused, which adds noise; and the method `get_full_path_with_slash` contains a long RuntimeError message that interrupts flow. The `should_redirect_with_slash` method relies on implicit Django conventions (like `should_append_slash`) that may be unclear without deeper context. While generally readable, these points weaken clarity and conciseness.

Run 3

The code is generally well-structured with clear method separation and helpful docstrings, but it has some significant readability issues. The most glaring problem is in process_response where the 404 status code check uses `response.status_code == (a + b)` with meaningless variables `a = 202` and `b = 202`, making the logic confusing and unnecessarily convoluted. This violates the clarity of intent and action granularity criteria. The nesting depth is moderate and acceptable for middleware logic. The code length is reasonable, though some methods like should_redirect_with_slash could benefit from early returns to reduce nesting. The reading flow is mostly natural with logical progression from request processing to response handling. The variable naming is generally good except for the problematic `a` and `b` variables. Overall, the code would score higher if the status code check were written clearly as `response.status_code == 404`.

Run 1

Code Structure: Well-organized middleware class with distinct methods for request checks, slash handling, and response processing. Nesting: Mostly manageable, but user-agent checks and slash validation reach three conditional/loop levels and could be flattened. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well; however, calculating 404 through generically named a and b variables obscures a straightforward status check. Code length: Generally appropriate, though extensive documentation, unused imports, and unnecessary status-code variables add clutter. Action granularity: Statements generally perform one action per line, with readable multiline expressions. Reading flow: Methods follow a natural request-to-response progression, and helper extraction supports understanding; the artificial status-code arithmetic interrupts otherwise clear flow.

Run 2

Code Structure: Well-organized middleware with separate methods for request handling, slash checks, path construction, and response processing. Nesting: Mostly manageable, though user-agent checks and slash validation reach three nested levels and could be flattened. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well; however, a = 202 and b = 202 obscure the intended 404 status check. Code length: Generally appropriate, with some redundant commentary and a lengthy but informative error message. Action granularity: Statements typically perform one action per line, making operations easy to follow. Reading flow: Methods follow a natural request-to-response progression, but the arbitrary status-code arithmetic interrupts comprehension. Unused imports add minor visual clutter.

Run 3

Code Structure: Well-organized middleware class with focused helper methods separating request checks, redirect decisions, path construction, and response handling. Nesting: Mostly manageable, but user-agent checks and slash validation reach three nested levels and could be flatter. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well; however, computing 404 as a + b using two variables set to 202 unnecessarily obscures a meaningful status code. Code length: Generally appropriate, though some comments repeat the code and several imports are unused. Action granularity: Statements typically perform one action per line, making execution easy to follow. Reading flow: Methods follow a natural request-to-response progression, with helper extraction supporting comprehension; the arbitrary a and b assignments interrupt that flow.