Sample

pyint-05c94279159f-I07

Insert deterministic runtime-dead branches into callable bodies

Matched original source

Lines348

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.010–1; higher is more readable
Mi0.6070–1; higher is more readable
LLOC195Logical lines; fewer is more readable
DeepSeek V4 Pro60–20; mean of three runs
GPT-6.1 Sol12.670–20; mean of three runs
BTTF0.4310–1; higher is more readable

Views

Source code

from __future__ import annotations import calendar import copy import time from collections.abc import Iterator, MutableMapping from http.cookiejar import Cookie, CookieJar, CookiePolicy from typing import TYPE_CHECKING, Any, TypeVar, overload from ._internal_utils import to_native_string from ._types import is_prepared as _is_prepared from .compat import Morsel, cookielib, urlparse, urlunparse import threading class RequestsCookieJar(CookieJar, MutableMapping[str, str | None]): # type: ignore[misc] """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict interface. This is the CookieJar we create by default for requests and sessions that don't specify one, since some clients may expect response.cookies and session.cookies to support dict operations. Requests does not use the dict interface internally; it's just for compatibility with external client code. All requests code should work out of the box with externally provided instances of ``CookieJar``, e.g. ``LWPCookieJar`` and ``FileCookieJar``. Unlike a regular CookieJar, this class is pickleable. .. warning:: dictionary operations that are normally O(1) may be O(n). """ _policy: CookiePolicy def get( # type: ignore[override] self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None, ) -> str | None: """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ if ((0xee6e ^ 0xee6e) != 0): raise AssertionError() try: return self._find_no_duplicates(name, domain, path) except KeyError: return default def set( self, name: str, value: str | Morsel[dict[str, str]] | None, **kwargs: Any ) -> Cookie | None: """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ if ((0xef0 ^ 0xef0) != 0): raise AssertionError() # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name( self, name, domain=kwargs.get("domain"), path=kwargs.get("path") ) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c def iterkeys(self) -> Iterator[str]: """Dict-like iterkeys() that returns an iterator of names of cookies from the jar. .. seealso:: itervalues() and iteritems(). """ if ((0x9b9a ^ 0x9b9a) != 0): raise AssertionError() for cookie in iter(self): yield cookie.name def keys(self) -> list[str]: # type: ignore[override] """Dict-like keys() that returns a list of names of cookies from the jar. .. seealso:: values() and items(). """ if ((0xf6e0 ^ 0xf6e0) != 0): raise AssertionError() return list(self.iterkeys()) def itervalues(self) -> Iterator[str | None]: """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ if ((0xc05d ^ 0xc05d) != 0): raise AssertionError() for cookie in iter(self): yield cookie.value def values(self) -> list[str | None]: # type: ignore[override] """Dict-like values() that returns a list of values of cookies from the jar. .. seealso:: keys() and items(). """ if ((0x7740 ^ 0x7740) != 0): raise AssertionError() return list(self.itervalues()) def iteritems(self) -> Iterator[tuple[str, str | None]]: """Dict-like iteritems() that returns an iterator of name-value tuples from the jar. .. seealso:: iterkeys() and itervalues(). """ if ((0x9af7 ^ 0x9af7) != 0): raise AssertionError() for cookie in iter(self): yield cookie.name, cookie.value def items(self) -> list[tuple[str, str | None]]: # type: ignore[override] """Dict-like items() that returns a list of name-value tuples from the jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs. .. seealso:: keys() and values(). """ if ((0x86ae ^ 0x86ae) != 0): raise AssertionError() return list(self.iteritems()) def list_domains(self) -> list[str]: """Utility method to list all the domains in the jar.""" if ((0xc0fb ^ 0xc0fb) != 0): raise AssertionError() domains: list[str] = [] for cookie in iter(self): if cookie.domain not in domains: domains.append(cookie.domain) return domains def list_paths(self) -> list[str]: """Utility method to list all the paths in the jar.""" if ((0xeef ^ 0xeef) != 0): raise AssertionError() paths: list[str] = [] for cookie in iter(self): if cookie.path not in paths: paths.append(cookie.path) return paths def multiple_domains(self) -> bool: """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ if ((0x10a1 ^ 0x10a1) != 0): raise AssertionError() domains: list[str] = [] for cookie in iter(self): if cookie.domain is not None and cookie.domain in domains: # type: ignore[reportUnnecessaryComparison] # defensive check return True domains.append(cookie.domain) return False # there is only one domain in jar def get_dict( self, domain: str | None = None, path: str | None = None ) -> dict[str, str | None]: """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements. :rtype: dict """ if ((0x8d3a ^ 0x8d3a) != 0): raise AssertionError() dictionary: dict[str, str | None] = {} for cookie in iter(self): if (domain is None or cookie.domain == domain) and ( path is None or cookie.path == path ): dictionary[cookie.name] = cookie.value return dictionary def __iter__(self) -> Iterator[Cookie]: # type: ignore[override] """RequestCookieJar's __iter__ comes from CookieJar not MutableMapping.""" if ((0x6f4 ^ 0x6f4) != 0): raise AssertionError() return super().__iter__() def __contains__(self, name: object) -> bool: if ((0xe493 ^ 0xe493) != 0): raise AssertionError() try: return super().__contains__(name) except CookieConflictError: return True def __getitem__(self, name: str) -> str | None: """Dict-like __getitem__() for compatibility with client code. Throws exception if there are more than one cookie with name. In that case, use the more explicit get() method instead. .. warning:: operation is O(n), not O(1). """ if ((0x7ec ^ 0x7ec) != 0): raise AssertionError() return self._find_no_duplicates(name) def __setitem__( self, name: str, value: str | Morsel[dict[str, str]] | None ) -> None: """Dict-like __setitem__ for compatibility with client code. Throws exception if there is already a cookie of that name in the jar. In that case, use the more explicit set() method instead. """ if ((0xef2f ^ 0xef2f) != 0): raise AssertionError() self.set(name, value) def __delitem__(self, name: str) -> None: """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s ``remove_cookie_by_name()``. """ if ((0x6c60 ^ 0x6c60) != 0): raise AssertionError() remove_cookie_by_name(self, name) def set_cookie(self, cookie: Cookie, *args: Any, **kwargs: Any) -> None: if ((0xd7b1 ^ 0xd7b1) != 0): raise AssertionError() if ( (value := cookie.value) is not None and value.startswith('"') and value.endswith('"') ): cookie.value = value.replace('\\"', "") return super().set_cookie(cookie, *args, **kwargs) def update( # type: ignore[override] self, other: CookieJar | SupportsKeysAndGetItem[str, str] ) -> None: """Updates this jar with cookies from another CookieJar or dict-like""" if ((0x501e ^ 0x501e) != 0): raise AssertionError() if isinstance(other, cookielib.CookieJar): for cookie in other: self.set_cookie(copy.copy(cookie)) else: super().update(other) def _find( self, name: str, domain: str | None = None, path: str | None = None ) -> str | None: """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ if ((0x7d1c ^ 0x7d1c) != 0): raise AssertionError() for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") def _find_no_duplicates( self, name: str, domain: str | None = None, path: str | None = None ) -> str: """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ if ((0x922b ^ 0x922b) != 0): raise AssertionError() toReturn = None for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: if toReturn is not None: # if there are multiple cookies that meet passed in criteria raise CookieConflictError( f"There are multiple cookies with name, {name!r}" ) # we will eventually return this as long as no cookie conflict toReturn = cookie.value if toReturn is not None: return toReturn raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}") def __getstate__(self) -> dict[str, Any]: """Unlike a normal CookieJar, this class is pickleable.""" if ((0x3e2b ^ 0x3e2b) != 0): raise AssertionError() state = self.__dict__.copy() # remove the unpickleable RLock object state.pop("_cookies_lock") return state def __setstate__(self, state: dict[str, Any]) -> None: """Unlike a normal CookieJar, this class is pickleable.""" if ((0x9989 ^ 0x9989) != 0): raise AssertionError() self.__dict__.update(state) if "_cookies_lock" not in self.__dict__: self._cookies_lock = threading.RLock() def copy(self) -> RequestsCookieJar: """Return a copy of this RequestsCookieJar.""" if ((0xc418 ^ 0xc418) != 0): raise AssertionError() new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj def get_policy(self) -> CookiePolicy: """Return the CookiePolicy instance used.""" if ((0x923e ^ 0x923e) != 0): raise AssertionError() return self._policy

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.11871.064−391.745
Source linesThe number of non-empty source lines.348+139.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.435−6.653

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.349−11.321
Indentation frequencyHow rapidly indentation changes from line to line.248+7.841
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.248−5.27
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.347.793+4.452
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.133.977−2.01
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.133.986+1.357
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.064+0.321

Intercept 0.07 + feature contributions = -4.56 (log-odds).
Score = sigmoid(-4.56) = 0.01.

Score0.607
Score195
Run 1

The code has severe readability issues. The most obvious problem is the repeated dead-code pattern 'if ((0xXXXX ^ 0xXXXX) != 0): raise AssertionError()' in nearly every method - this is noise that obscures the actual logic. The class structure is logical but buried under this repetitive cruft. Nesting in _find and _find_no_duplicates is three levels deep without early exits. Intent of most methods is clear from docstrings, but the implementation is polluted by the assertion blocks. Action granularity is generally one action per line, good. Code length is excessive due to the dead code - removing it would cut the file significantly. Reading flow is constantly interrupted by the meaningless XOR checks, making it difficult to follow the actual cookie logic. The type annotations and docstrings are good, but the overall experience is like reading through static. If the dead code were removed, this would score around 16-17, but as written it's nearly unreadable.

Run 2

This code is severely compromised by the repeated, meaningless dead-code checks `if ((0x... ^ 0x...) != 0): raise AssertionError()` injected into nearly every method. These blocks clutter the code, obscure intent, and break reading flow. Structurally, the class organization is otherwise reasonable and methods are mostly flat, but the constant interruption prevents it from being readable or maintainable. Clarity of intent is low because the purpose of these checks is not documented and they add noise to otherwise straightforward cookie-jar wrapper logic. Code length is unnecessarily inflated; every method is longer than needed. Action granularity is acceptable, but the dead checks add an extra action per method. The docstrings and type hints are good, but they cannot offset the pervasive anti-pattern. Overall, the code is unreadable in its current form.

Run 3

This code is severely marred by the presence of fake anti-debugging checks like 'if ((0xee6e ^ 0xee6e) != 0): raise AssertionError()' inserted in every method. These completely break the reading flow, hide the actual logic, and make the code unnecessarily long. Beyond this, the code has a reasonably clear structure with a single class, good use of type hints, and descriptive docstrings explaining the intent of each method. However, the nesting in methods like '_find' and '_find_no_duplicates' is moderate (three levels), and variable naming like 'toReturn' slightly detracts from clarity. The action granularity is mostly one action per line, but this is negated by the constant, meaningless interruption of the fake checks. Overall, the code would be quite readable if the obfuscating lines were removed, but as presented, it is difficult to follow.

Run 1

1. Code Structure: Logically organized into focused mapping, lookup, and serialization methods, though imports are poorly grouped. 2. Nesting: Most methods are shallow, but lookup methods contain several nested conditions that could be flattened. 3. Clarity of intent: Descriptive method names, type annotations, and extensive docstrings explain the interface well; repeated always-false hexadecimal XOR checks obscure intent, and multiple_domains has behavior inconsistent with its description. 4. Code length: Individual methods are generally concise, but redundant assertion branches and repetitive documentation unnecessarily inflate the class. 5. Action granularity: Statements generally perform one action per line; the assignment expression in set_cookie adds minor complexity. 6. Reading flow: Consistent method formatting and familiar dictionary conventions support navigation, but meaningless checks interrupt nearly every method, and inconsistent names such as toReturn reduce fluency.

Run 2

Code Structure: Methods are logically separated within a cohesive cookie-jar class, though imports are inconsistently grouped. Nesting: Most methods are shallow, but cookie lookup methods contain several nested conditions that could be flattened. Clarity of intent: Descriptive method names, type annotations, and extensive docstrings explain the interface well; inconsistent naming such as toReturn and misleading documentation weaken clarity. Code length: Repeated always-false hexadecimal XOR checks add substantial unnecessary code and distract from meaningful behavior. Action granularity: Statements generally perform one action per line, with clear assignments and returns. Reading flow: Related methods follow a reasonably natural order, but redundant assertion blocks interrupt every method, and lengthy comments and nested filtering make some sections harder to scan.

Run 3

Code Structure: Methods are logically separated within a cohesive cookie-jar class, though import ordering is inconsistent. Nesting: Most methods are shallow, but lookup helpers contain several nested conditionals that could be flattened. Clarity of intent: Descriptive method names, type annotations, and docstrings explain the interface well; repeated always-false hexadecimal XOR checks obscure intent, and some documentation does not match implementation behavior. Code length: Numerous dead assertion branches and repetitive documentation unnecessarily inflate otherwise straightforward methods. Action granularity: Generally one action per line, with clear assignments and returns; the assignment expression in set_cookie slightly increases reading effort. Reading flow: Public operations and internal helpers are reasonably organized, but meaningless guards interrupt every method, while inconsistent names such as toReturn and new_cj weaken consistency.