Sample

pyint-d916faee63f1-I05

Rewrite eligible decimal integer literals in hexadecimal notation

Matched original source

Lines127

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4790–1; higher is more readable
Mi0.6550–1; higher is more readable
LLOC58Logical lines; fewer is more readable
DeepSeek V4 Pro16.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.2580–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()[ ::0x2 ] # 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=0x0, 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(0x7d1, 0x1, 0x1)).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.127+50.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.424−6.636

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.128−3.496
Indentation frequencyHow rapidly indentation changes from line to line.97+2.618
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.97−1.805
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.126.821+1.363
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.82.852+0.532
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.047+0.482
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.82.992+0.15

Intercept 0.07 + feature contributions = -0.086 (log-odds).
Score = sigmoid(-0.086) = 0.479.

Score0.655
Score58
Run 1

The code is well-structured with clear separation of concerns, good use of properties, and a logical organization of methods. The class follows a consistent pattern with private methods, and the token generation/checking flow is easy to follow. Nesting is minimal with early returns and simple loops. The main readability issue is the use of hex literals (0x7d1, 0x1, 0x2) instead of decimal numbers, which adds unnecessary cognitive load. The `_make_hash_value` method has a moderate length but remains understandable. Some comments help clarify intent, though a few areas like the token parsing could benefit from small explanatory comments. Overall, this code demonstrates strong readability with minor issues around numeric literal choices and occasional verbosity.

Run 2

The code is well-structured and readable overall. It has clear separation of concerns, good use of helper methods, and descriptive naming. The class docstring explains the purpose, and methods have useful comments. However, some readability issues exist: hexadecimal notation like 0x7d1, 0x1, and 0x0 obscures values (2001, 1, 0); the `[::0x2]` slice is cryptic and needs explanation; the token parsing logic in check_token has moderate nesting and multiple early returns that require careful reading. The property accessors add boilerplate complexity, and some lines are dense. The score reflects solid readability with minor clarity issues in numeric literals and token parsing flow.

Run 3

The code is generally readable and well-structured. It follows Django's style conventions with clear method separation and docstrings explaining purpose. Class responsibilities are logical—token generation and verification are cleanly split. The use of properties for secret handling is concise and idiomatic. However, there are a few minor readability issues: the `check_token` method contains multiple early returns and a for-else construct, which slightly disrupts natural flow. The slicing trick `[::0x2]` and hexadecimal constants like `0x7d1` and `0x1` obscure intent without comments. Some inline comments are helpful, but a few expressions (e.g., the timestamp conversion) could be more self-documenting. Overall, the code is maintainable and clear, but could be slightly improved with more explicit constants and less dense logic in a few places.

Run 1

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Shallow overall; early returns simplify validation, although the for-else construct requires extra attention. Clarity of intent: Descriptive names, docstrings, and comments explain the purpose and security rationale. Hexadecimal literals for ordinary dates, zero, and slice steps unnecessarily obscure meaning. Code length: Mostly concise; extensive documentation is useful rather than redundant, though property boilerplate adds some length. Action granularity: Most lines perform one clear action; the chained HMAC, hexadecimal slicing, and compact conditional expression are slightly harder to scan. Reading flow: Validation follows a natural sequence from parsing through verification to expiration checking. The awkwardly wrapped hexdigest slice interrupts otherwise consistent formatting.

Run 2

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Mostly flat, with early returns keeping validation straightforward; the loop and conditional add only modest nesting. Clarity of intent: Descriptive names, docstrings, and comments explain the purpose and security rationale. However, hexadecimal literals for ordinary dates, zero, and slice steps obscure otherwise simple operations. Code length: Reasonably concise; configuration accessors and detailed documentation add length but serve clear purposes. Action granularity: Most statements perform one action, although chained HMAC generation and slicing combine several operations. Reading flow: Validation follows a natural parse, verify, and expiration-check sequence. The loop-else construct requires familiarity, and the awkward multiline hexdigest slice interrupts the flow slightly.

Run 3

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Mostly flat, with early returns keeping validation easy to follow; the loop adds little depth. Clarity of intent: Descriptive names, docstrings, and security-related comments clearly explain the purpose, although hexadecimal literals for ordinary dates, zero, and slice steps unnecessarily obscure meaning. Code length: Appropriately concise for the functionality; documentation adds useful context rather than excessive verbosity. Action granularity: Most statements perform one clear action, though the chained HMAC, hexadecimal conversion, and slicing expression is visually awkward. Reading flow: Validation follows a natural parse, verify, and expiration-check sequence. Minor friction comes from the less familiar for-else construct, property accessor boilerplate, and unusual multiline slice formatting.