Sample

pyint-69739d0d1f74-I03

Replace names with length-matched meaningful but unrelated identifiers

Matched original source

Lines245

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0750–1; higher is more readable
Mi0.5640–1; higher is more readable
LLOC160Logical lines; fewer is more readable
DeepSeek V4 Pro5.330–20; mean of three runs
GPT-6.1 Sol90–20; mean of three runs
BTTF0.2410–1; higher is more readable

Views

Source code

from __future__ import annotations import hashlib import os import re import threading import time import warnings from base64 import b64encode from typing import TYPE_CHECKING, Any, Final, cast, overload from ._internal_utils import to_native_string from .compat import basestring, str, urlparse from .cookies import extract_cookies_to_jar from .utils import parse_dict_header class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" username: bytes | str password: bytes | str _thread_local: threading.local last_nonce: str nonce_count: int chal: dict[str, str] pos: int | None num_401_calls: int | None @overload def __init__(self, schedule: str, localKey: str) -> None: ... @overload def __init__(self, category: bytes, customer: bytes) -> None: ... def __init__(self, schedule: bytes | str, localKey: bytes | str) -> None: self.username = schedule self.password = localKey # Keep state in per-thread local storage self._thread_local = threading.local() def validateMessage(self) -> None: # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, "init"): self._thread_local.init = True self._thread_local.last_nonce = "" self._thread_local.nonce_count = 0 self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None def validateAccount(self, client: str, age: str) -> str | None: """ :rtype: str """ batch = self._thread_local.chal["realm"] count = self._thread_local.chal["nonce"] key = self._thread_local.chal.get("qop") backupKey = self._thread_local.chal.get("algorithm") source = self._thread_local.chal.get("opaque") recentKey = None if backupKey is None: sharedData = "MD5" else: sharedData = backupKey.upper() # lambdas assume digest modules are imported at the top level if sharedData == "MD5" or sharedData == "MD5-SESS": def md5_utf8(key: str | bytes) -> str: if isinstance(key, str): key = key.encode("utf-8") return hashlib.md5(key, usedforsecurity=False).hexdigest() recentKey = md5_utf8 elif sharedData == "SHA": def sha_utf8(age: str | bytes) -> str: if isinstance(age, str): age = age.encode("utf-8") return hashlib.sha1(age, usedforsecurity=False).hexdigest() recentKey = sha_utf8 elif sharedData == "SHA-256": def sha256_utf8(map: str | bytes) -> str: if isinstance(map, str): map = map.encode("utf-8") return hashlib.sha256(map, usedforsecurity=False).hexdigest() recentKey = sha256_utf8 elif sharedData == "SHA-512": def sha512_utf8(key: str | bytes) -> str: if isinstance(key, str): key = key.encode("utf-8") return hashlib.sha512(key, usedforsecurity=False).hexdigest() recentKey = sha512_utf8 if recentKey is None: return None def KD(age: str, key: str) -> str: return hash_utf8(f"{age}:{key}") # XXX not implemented yet target = None finalKey = urlparse(age) #: path is request-uri defined in RFC 2616 which should not be empty flag = finalKey.path or "/" if finalKey.query: flag += f"?{finalKey.query}" map = f"{self.username}:{batch}:{self.password}" date = f"{client}:{flag}" item = recentKey(map) node = recentKey(date) if count == self._thread_local.last_nonce: self._thread_local.nonce_count += 1 else: self._thread_local.nonce_count = 1 session = f"{self._thread_local.nonce_count:08x}" step = str(self._thread_local.nonce_count).encode("utf-8") step += count.encode("utf-8") step += time.ctime().encode("utf-8") step += os.urandom(8) option = hashlib.sha1(step, usedforsecurity=False).hexdigest()[:16] if sharedData == "MD5-SESS": item = recentKey(f"{item}:{count}:{option}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology if not key: nextKey = KD(item, f"{count}:{node}") elif key == "auth" or "auth" in key.split(","): nextPath = f"{count}:{session}:{option}:auth:{node}" nextKey = KD(item, nextPath) else: # XXX handle auth-int. return None self._thread_local.last_nonce = count # XXX should the partial digests be encoded too? user = ( f'username="{self.username}", realm="{batch}", nonce="{count}", ' f'uri="{flag}", response="{nextKey}"' ) if source: user += f', opaque="{source}"' if backupKey: user += f', algorithm="{backupKey}"' if target: user += f', digest="{target}"' if key: user += f', qop="auth", nc={session}, cnonce="{option}"' return f"Digest {user}" def validateBalance(self, age: Response, **status: Any) -> None: """Reset num_401_calls counter on redirects.""" if age.is_redirect: self._thread_local.num_401_calls = 1 def findBuffer(self, map: Response, **result: Any) -> Response: """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 if not 400 <= map.status_code < 500: self._thread_local.num_401_calls = 1 return map if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. if (node := getattr(map.request.body, "seek", None)) is not None: node(self._thread_local.pos) source = map.headers.get("www-authenticate", "") if "digest" in source.lower() and self._thread_local.num_401_calls < 2: self._thread_local.num_401_calls += 1 age = re.compile(r"digest ", flags=re.IGNORECASE) self._thread_local.chal = parse_dict_header(age.sub("", source, count=1)) # Consume content and release the original connection # to allow our new request to reuse the same one. map.content map.close() data = map.request.copy() finalScore = cast("CookieJar", data._cookies) extract_cookies_to_jar(finalScore, map.request, map.raw) data.prepare_cookies(finalScore) defaultEvent = self.validateAccount( cast(str, data.method), cast(str, data.url) ) if defaultEvent: data.headers["Authorization"] = defaultEvent key = map.connection.send(data, **result) key.history.append(map) key.request = data return key self._thread_local.num_401_calls = 1 return map def __call__(self, key: PreparedRequest) -> PreparedRequest: # Initialize per-thread state, if needed self.validateMessage() # If we have a saved nonce, skip the 401 if self._thread_local.last_nonce: backupClient = self.validateAccount( cast(str, key.method), cast(str, key.url) ) if backupClient: key.headers["Authorization"] = backupClient if (path := getattr(key.body, "tell", None)) is not None: self._thread_local.pos = path() else: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. self._thread_local.pos = None key.register_hook("response", self.findBuffer) key.register_hook("response", self.validateBalance) self._thread_local.num_401_calls = 1 return key def __eq__(self, entry: object) -> bool: return all( [ self.username == getattr(entry, "username", None), self.password == getattr(entry, "password", None), ] ) def __ne__(self, count: Any) -> bool: return not self == count

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.9930.086−327.693
Source linesThe number of non-empty source lines.245+98
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.506−6.758

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.246−7.674
Indentation frequencyHow rapidly indentation changes from line to line.219+6.838
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.219−4.605
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.244.84+3.013
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.123.976−1.586
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.123.992+1.196
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.073+0.23

Intercept 0.07 + feature contributions = -2.517 (log-odds).
Score = sigmoid(-2.517) = 0.075.

Score0.564
Score160
Run 1

The code is severely obfuscated, likely intentionally. Function names (validateAccount, validateBalance, findBuffer) are misleading; they actually handle digest calculation, redirect handling, and response hooking. Parameter names (client/age, map/result, schedule/localKey, category/customer) are nonsensical and unrelated to their purpose. Variables like backupKey, recentKey, batch, count, target are opaque. The overload signatures are broken. Code structure is tangled, with nested function definitions and magic strings. Multiple actions occur per line. Natural reading flow is non-existent. Overall, it is extremely difficult to understand and maintain.

Run 2

This code is extremely unreadable due to obfuscated naming and tangled logic. Function names like validateMessage, validateAccount, validateBalance, and findBuffer do not match their actual purposes. Variable names such as schedule, localKey, age, map, batch, count, key, source, node, step, option, and user are misleading and inconsistent. The code has excessive comments explaining basic steps but lacks clarity on the complex digest authentication logic. Deeply nested conditionals and duplicated hash function definitions within branches obscure the flow. Multiple actions are packed into single lines, and the overall structure resembles intentionally obfuscated code rather than a maintainable implementation. The type hints are present but cannot compensate for the confusing naming and disorganized flow.

Run 3

The code has poor readability due to heavily obfuscated variable names and unclear intent. The class uses misleading names like 'validateAccount' for authentication logic, 'findBuffer' for response handling, and replaces digest auth terminology with unrelated names like 'batch', 'count', 'client', 'map', 'age', 'source', etc. The methods and parameters do not reflect their actual purpose. Multiple actions are packed into single methods with unclear flow. There is deep logic nested within string formatting and conditional branching. Comments reference RFCs but do not clarify the renamed variables. The structure relies on thread-local state that is difficult to follow. While the code length is moderate and lines are generally not overly long, the overall clarity of intent is severely lacking, making it hard to understand without significant effort. The action granularity is acceptable, but the reading flow is disrupted by confusing, arbitrary naming and non-obvious side effects.

Run 1

Code Structure: Methods separate initialization, digest construction, response handling, and request hooks, but digest construction mixes several responsibilities. Nesting: Mostly moderate, with early returns limiting depth; nested hash helpers add complexity. Clarity of intent: The class purpose is clear, but misleading method names such as validateAccount and findBuffer, generic variables such as age, map, and key, and inconsistent naming obscure authentication concepts. KD references undefined hash_utf8, further confusing the intended flow. Code length: Digest construction is lengthy, and repeated encoding/hash helpers could be consolidated. Action granularity: Most lines perform one action, although assignment expressions and dense formatted strings require extra attention. Reading flow: The overall authentication sequence is logical, and comments help, but unrelated parameter names, stale comments, unresolved symbols, and inconsistent terminology repeatedly interrupt comprehension.

Run 2

Code Structure: Methods separate initialization, digest construction, response handling, and request setup, but digest construction mixes several responsibilities. Nesting: Mostly moderate, with early returns limiting depth; nested hashing functions add complexity. Clarity of intent: The class purpose is clear, but misleading names such as validateAccount, age, map, and finalScore obscure authentication concepts. KD references undefined hash_utf8, further disrupting understanding. Code length: Repeated hashing wrappers and a long digest-building method could be simplified; unused imports and dead placeholders add noise. Action granularity: Most lines perform one action, although assignment expressions combine lookup and branching. Reading flow: Request preparation and retry handling follow a reasonable sequence, supported by comments, but inconsistent naming, mismatched overload parameter names, stale comments, and scattered state updates make the authentication flow harder to trace.

Run 3

Code Structure: Methods separate initialization, digest generation, response handling, and request setup logically, but digest generation mixes several responsibilities. Nesting: Mostly moderate, with early returns limiting depth; nested hash helpers and response conditions add complexity. Clarity of intent: The class purpose is clear, but misleading names such as validateAccount, age, map, and backupKey obscure authentication concepts. KD references undefined hash_utf8, further confusing the intended hashing flow. Code length: Repeated hash wrappers, unused imports, and a long digest-building method introduce avoidable verbosity. Action granularity: Most lines perform one action, although assignment expressions combine lookup and branching. Reading flow: Request processing follows a generally coherent sequence, supported by some useful comments, but inconsistent naming, stale comments, and unexplained intermediate values repeatedly interrupt comprehension.