Sample

pyint-a65d95876168-I10

Deterministically remove some optional blank lines and bracketed line breaks

Matched original source

Lines112

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.3060–1; higher is more readable
Mi0.5510–1; higher is more readable
LLOC58Logical lines; fewer is more readable
DeepSeek V4 Pro8.330–20; mean of three runs
GPT-6.1 Sol160–20; mean of three runs
BTTF0.3440–1; higher is more readable

Views

Source code

from datetime import datetime from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm = None _secret = None _secret_fallbacks = None def __init__(self): self.algorithm = self.algorithm or "sha256" def _get_secret(self): return self._secret or settings.SECRET_KEY def _set_secret(self, secret): self._secret = secret secret = property(_get_secret, _set_secret) def _get_fallbacks(self): if self._secret_fallbacks is None: return settings.SECRET_KEY_FALLBACKS return self._secret_fallbacks def _set_fallbacks(self, fallbacks): self._secret_fallbacks = fallbacks secret_fallbacks = property(_get_fallbacks, _set_fallbacks) def make_token(self, user): """ Return a token that can be used once to do a password reset for the given user. """ return self._make_token_with_timestamp( user, self._num_seconds(self._now()), self.secret, ) def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with for secret in [self.secret, *self.secret_fallbacks]: if constant_time_compare( self._make_token_with_timestamp(user, ts, secret), token, ): break else: return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True def _make_token_with_timestamp(self, user, timestamp, secret): # timestamp is number of seconds since 2001-1-1. Converted to base 36, # this gives us a 6 digit string until about 2069. ts_b36 = int_to_base36(timestamp) hash_string = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), secret=secret, algorithm=self.algorithm, ).hexdigest()[ ::2 ] # Limit to shorten the URL. return "%s-%s" % (ts_b36, hash_string) def _make_hash_value(self, user, timestamp): """ Hash the user's primary key, email (if available), and some user state that's sure to change after a password reset to produce a token that is invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after a password reset. Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually invalidates the token. Running this data through salted_hmac() prevents password cracking attempts using the reset token, provided the secret isn't compromised. """ # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = ( "" if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) ) email_field = user.get_email_field_name() email = getattr(user, email_field, "") or "" return f"{user.pk}{user.password}{login_timestamp}{timestamp}{email}" def _num_seconds(self, dt): return int((dt - datetime(2001, 1, 1)).total_seconds()) def _now(self): # Used for mocking in tests return datetime.now()

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.2962.12−97.75
Source linesThe number of non-empty source lines.112+44.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.408−6.612

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.113−2.965
Indentation frequencyHow rapidly indentation changes from line to line.83+2.134
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.83−1.484
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.117−1.29
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.111.822+1.153
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.117+1.083
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.047+0.481

Intercept 0.07 + feature contributions = -0.817 (log-odds).
Score = sigmoid(-0.817) = 0.306.

Score0.551
Score58
Run 1

The code has clear intent and documentation, but its readability is severely hampered by poor formatting and structure. Long lines with excessive whitespace in `_make_token_with_timestamp` and `_make_hash_value` break visual flow and make them hard to parse. Multiple statements per line (e.g., `str(self._get_secret())` and nested property definitions) violate action granularity. Inconsistent spacing around methods, missing blank lines, and inline comments (`# Parse the token`) further reduce clarity. While the token generation logic is logically separated into methods, the physical structure is disorganized, increasing cognitive load. Fixing line breaks, aligning whitespace, and adding consistent spacing would significantly improve readability.

Run 2

The code has a clear overall purpose and reasonable class-level organization, but readability suffers from inconsistent formatting, missing blank lines between methods, and unusual line breaks/indentation in several places (e.g., salted_hmac call, login_timestamp assignment). The check_token method includes multiple nested try/except blocks and a loop with an else clause, which adds some complexity. Action granularity is mixed: some lines bundle multiple operations or have awkward spacing, while others are appropriately separated. The reading flow is disrupted by long conditional expressions and inconsistent spacing around operators and parentheses. Docstrings help with intent, but the inconsistent style and occasional dense expressions make the code harder to follow than necessary.

Run 3

The code suffers from poor readability due to missing blank lines between class methods, which makes the structure difficult to scan. Some lines contain multiple operations or are excessively long, violating the 'one action per line' principle. The `_make_token_with_timestamp` method has significant alignment and spacing issues that obscure the logic. While the algorithm logic is generally sound and comments exist, the formatting undermines the natural reading flow. The overall structure requires substantial formatting fixes to be considered readable.

Run 1

1. Code Structure: Well-organized class with focused methods separating token generation, validation, configuration, and hashing; missing blank lines weaken visual separation. 2. Nesting: Mostly shallow, with early returns keeping validation straightforward. The for/else construct requires some familiarity. 3. Clarity of intent: Descriptive method names, docstrings, and comments explain the purpose and security-related decisions, though abbreviations such as ts_b36 require interpretation. 4. Code length: Implementation is reasonably concise; the longer hashing docstring provides useful context rather than unnecessary verbosity. 5. Action granularity: Most statements perform one clear action, but the compressed salted_hmac arguments and awkward conditional-expression formatting impede scanning. 6. Reading flow: Methods follow a logical progression, but inconsistent spacing, crowded method boundaries, and the unusually split hexdigest slice disrupt otherwise natural reading.

Run 2

Code Structure: Responsibilities are logically separated into token generation, validation, configuration properties, and hashing helpers. Nesting: Early returns keep validation mostly flat; the loop and conditional introduce only shallow nesting. Clarity of intent: Descriptive method names, docstrings, and comments explain the security-related behavior, although abbreviated timestamp variables and the loop-else construct require some familiarity. Code length: Implementation is reasonably concise; the lengthy hashing docstring provides useful context rather than unnecessary repetition. Action granularity: Statements generally perform one action per line, though the compressed HMAC arguments and conditional expression reduce scanability. Reading flow: Methods follow a sensible progression, but inconsistent blank lines between methods, excessive inline spacing, and awkward wrapping of the hash slice and login timestamp interrupt otherwise natural reading.

Run 3

Code Structure: The class is logically organized into token generation, validation, configuration properties, and supporting helpers, though inconsistent blank lines weaken separation. Nesting: Early returns keep validation relatively flat; the loop with an else clause adds modest complexity. Clarity of intent: Descriptive method names, docstrings, and comments explain the security logic well, although abbreviated timestamp variables require interpretation. Code length: Methods are concise and focused; the longer explanatory docstring is useful rather than unnecessary. Action granularity: Most statements perform one clear action, but the compressed HMAC call and awkward conditional-expression formatting obscure individual operations. Reading flow: Validation follows a natural parse, verify, and expiration-check sequence, but excessive inline spacing, irregular line breaks, and crowded method boundaries interrupt scanning.