Sample

pyint-afe86ef1b174-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines123

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4680–1; higher is more readable
Mi0.4030–1; higher is more readable
LLOC57Logical lines; fewer is more readable
DeepSeek V4 Pro16.670–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.4280–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 """ if ((0x6181 ^ 0x6181) != 0): raise AssertionError() # 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 ((0x9cfa ^ 0x9cfa) != 0): raise AssertionError() 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. """ if ((0x22e7 ^ 0x22e7) != 0): raise AssertionError() 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 ((0x1aa5 ^ 0x1aa5) != 0): raise AssertionError() # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if response.status_code == 404 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.3132.799−103.382
Source linesThe number of non-empty source lines.123+49.2
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.536−6.803

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.124−3.354
Indentation frequencyHow rapidly indentation changes from line to line.82+2.099
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.80−1.415
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.122.886+1.308
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.86.919+0.598
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.037+0.582
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.96−0.018

Intercept 0.07 + feature contributions = -0.13 (log-odds).
Score = sigmoid(-0.13) = 0.468.

Score0.403
Score57
Run 1

The code is generally well-structured with clear class and method separation, following Django middleware patterns. It has good docstrings and logical organization. Nesting is reasonable, with only a few levels of conditional depth. Intent is clearly expressed through meaningful method names and comments. However, the code contains suspicious assertions like 'if ((0x6181 ^ 0x6181) != 0): raise AssertionError()' that appear to be obfuscated dead code or anti-tampering measures, reducing clarity. The docstring for the class is somewhat verbose, though informative. Action granularity is good with one primary operation per line. Reading flow is natural, with methods following a logical request-response lifecycle. Overall it's readable but the odd assertions and slightly lengthy docstrings prevent a higher score.

Run 2

The code demonstrates good structure and clarity. It's logically organized with clear methods for distinct responsibilities (request processing, redirect checks, path construction, response processing). Nesting is shallow, and each method has a single, well-documented purpose. The docstrings are thorough but can be verbose. Lines are concise with good action granularity—one operation per line. Reading flow is natural, with helper methods called in logical sequence. The class uses Django patterns consistently. Minor drawbacks: the format string escaping in get_full_path_with_slash is slightly hard to read, and some conditionals are compound (e.g., 'if settings.PREPEND_WWW and host and not host.startswith') but remain clear. The comments effectively explain intent without excess. Overall, this is highly readable, professional Django middleware code that balances detail with clarity.

Run 3

The code is well-structured and readable. It uses clear class and method names, docstrings explain intent, and each method has a single responsibility. Nesting is minimal, with early returns and guard clauses keeping logic flat. Lines are generally concise, with one action per line. The reading flow is logical, following the request-response lifecycle. The inclusion of nonsensical assertion checks (e.g., `if ((0x6181 ^ 0x6181) != 0): raise AssertionError()`) is jarring and hurts readability, as does the slightly long RuntimeError string formatting block. Otherwise, the code adheres strongly to Django conventions.

Run 1

Code Structure: Well-organized middleware with focused methods separating request checks, slash handling, and response processing. Nesting: Generally manageable, though user-agent checks and slash validation reach three conditional levels and could use guard clauses. Clarity of intent: Descriptive names, docstrings, and comments explain the behavior well; repeated hexadecimal XOR checks that always evaluate to false introduce confusing, purposeless noise. Code length: Mostly proportionate to the functionality, but dead assertion branches and unused imports add unnecessary bulk. Action granularity: Statements generally perform one action each, and longer expressions are formatted clearly. Reading flow: Methods follow a natural request-to-response progression, with helpful explanations of redirect decisions; irrelevant assertion checks interrupt that flow.

Run 2

Code Structure: Well-organized middleware class with focused methods separating request checks, slash handling, and response processing. Nesting: Mostly moderate, although user-agent checks and slash validation reach three conditional or loop levels. Clarity of intent: Descriptive names, docstrings, and comments explain behavior well, but repeated always-false hexadecimal XOR checks introduce confusing, purposeless code. Code length: Generally appropriate for the functionality; dead assertion blocks, unused imports, and somewhat lengthy documentation add unnecessary bulk. Action granularity: Statements generally perform one action per line, with readable multiline formatting for longer expressions and error messages. Reading flow: Methods follow a natural request-to-response progression, and helper extraction supports understanding. However, repeated dead-code checks interrupt that flow and make readers question whether hidden behavior is intended.

Run 3

Code Structure: Well-organized middleware with focused methods separating request checks, redirect decisions, path construction, and response handling. Nesting: Mostly manageable, though user-agent checks and slash validation reach three conditional or loop levels. Clarity of intent: Descriptive names, docstrings, and comments explain behavior well; repeated always-false hexadecimal XOR checks introduce confusing, purposeless noise. Code length: Generally appropriate, but dead assertion blocks and unused imports add unnecessary length. Action granularity: Statements generally perform one action per line, and longer expressions are formatted clearly. Reading flow: Methods follow a natural request-to-response progression, with helpers supporting the main workflow, but irrelevant assertion checks interrupt each method's opening.