instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings including usage examples
from __future__ import annotations from dataclasses import dataclass, field from typing import List, Optional _BRACES = {"(", ")", "[", "]", "{", "}"} def _validate_no_invalid_chars(value: str, field_name: str) -> None: for ch in value: # printable ASCII without space: '!' (0x21) to '~' (0x7E) ...
--- +++ @@ -7,6 +7,11 @@ def _validate_no_invalid_chars(value: str, field_name: str) -> None: + """Ensure value contains only printable ASCII without spaces or braces. + + This mirrors the constraints enforced by other Redis clients for values that + will appear in CLIENT LIST / CLIENT INFO output. + ""...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/driver_info.py
Generate docstrings for script automation
from enum import Enum from typing import TYPE_CHECKING, Any, Awaitable, Dict, Optional, Tuple, Union from redis.exceptions import IncorrectPolicyType, RedisError, ResponseError from redis.utils import str_if_bytes if TYPE_CHECKING: from redis.asyncio.cluster import ClusterNode class RequestPolicy(Enum): ALL...
--- +++ @@ -47,6 +47,12 @@ class AbstractCommandsParser: def _get_pubsub_keys(self, *args): + """ + Get the keys from pubsub command. + Although PubSub commands have predetermined key locations, they are not + supported in the 'COMMAND's output, so the key positions are hardcoded + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/commands.py
Generate NumPy-style docstrings
import asyncio import collections import random import socket import threading import time import warnings from abc import ABC, abstractmethod from copy import copy from itertools import chain from typing import ( Any, Callable, Coroutine, Deque, Dict, Generator, List, Literal, Mappi...
--- +++ @@ -105,9 +105,135 @@ class RedisCluster(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands): + """ + Create a new RedisCluster client. + + Pass one of parameters: + + - `host` & `port` + - `startup_nodes` + + | Use ``await`` :meth:`initialize` to find cluster nodes & creat...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/cluster.py
Create simple docstrings for beginners
import asyncio from typing import ( TYPE_CHECKING, Any, AsyncIterator, Awaitable, Dict, Iterable, Iterator, List, Literal, Mapping, NoReturn, Optional, Sequence, Union, ) from redis.crc import key_slot from redis.exceptions import RedisClusterException, RedisErro...
--- +++ @@ -165,8 +165,12 @@ class ClusterMultiKeyCommands(ClusterCommandsProtocol): + """ + A class containing commands that handle more than one key + """ def _partition_keys_by_slot(self, keys: Iterable[KeyT]) -> Dict[int, List[KeyT]]: + """Split keys into a dictionary that maps a slot to ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/cluster.py
Add inline docstrings for readability
from typing import List from redis import DataError class Field: NUMERIC = "NUMERIC" TEXT = "TEXT" WEIGHT = "WEIGHT" GEO = "GEO" TAG = "TAG" VECTOR = "VECTOR" SORTABLE = "SORTABLE" NOINDEX = "NOINDEX" AS = "AS" GEOSHAPE = "GEOSHAPE" INDEX_MISSING = "INDEXMISSING" INDE...
--- +++ @@ -4,6 +4,9 @@ class Field: + """ + A class representing a field in a document. + """ NUMERIC = "NUMERIC" TEXT = "TEXT" @@ -28,6 +31,20 @@ index_empty: bool = False, as_name: str = None, ): + """ + Create a new field object. + + Args: + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/field.py
Add docstrings with type hints explained
from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Type, Union import pybreaker from redis.asyncio import ConnectionPool, Redis, RedisCluster from redis.asyncio.multidb.database import Database, Databases from redis.asyncio.multidb.failover import ( DEFAULT_FAILOVER_...
--- +++ @@ -56,6 +56,29 @@ @dataclass class DatabaseConfig: + """ + Dataclass representing the configuration for a database connection. + + This class is used to store configuration settings for a database connection, + including client options, connection sourcing details, circuit breaker settings, + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/multidb/config.py
Add detailed docstrings explaining each function
import json from typing import Literal from redis._parsers.helpers import pairs_to_dict from redis.commands.vectorset.utils import ( parse_vemb_result, parse_vlinks_result, parse_vsim_result, ) from ..helpers import get_protocol_version from .commands import ( VEMB_CMD, VGETATTR_CMD, VINFO_CMD...
--- +++ @@ -20,8 +20,10 @@ class _VectorSetBase(VectorSetCommands): + """Base class with shared initialization logic for VectorSet clients.""" def __init__(self, client, **kwargs): + """Initialize VectorSet client with callbacks.""" # Set the module commands' callbacks self._MODUL...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/vectorset/__init__.py
Fully document this Python code with docstrings
from __future__ import annotations import base64 import gzip import json import ssl import zlib from dataclasses import dataclass from typing import Any, Dict, Mapping, Optional, Tuple, Union from urllib.error import HTTPError, URLError from urllib.parse import urlencode, urljoin from urllib.request import Request, ur...
--- +++ @@ -56,6 +56,9 @@ class HttpClient: + """ + A lightweight HTTP client for REST API calls. + """ def __init__( self, @@ -77,6 +80,29 @@ auth_basic: Optional[Tuple[str, str]] = None, # (username, password) user_agent: str = DEFAULT_USER_AGENT, ) -> None: + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/http/http_client.py
Add docstrings to clarify complex logic
from typing import List, Optional, Tuple, Union from redis.commands.search.dialect import DEFAULT_DIALECT FIELDNAME = object() class Limit: def __init__(self, offset: int = 0, count: int = 0) -> None: self.offset = offset self.count = count def build_args(self): if self.count: ...
--- +++ @@ -18,6 +18,11 @@ class Reducer: + """ + Base reducer object for all reducers. + + See the `redisearch.reducers` module for the actual reducers. + """ NAME = None @@ -27,6 +32,20 @@ self._alias: Optional[str] = None def alias(self, alias: str) -> "Reducer": + """ ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/aggregation.py
Add docstrings with type hints explained
import warnings class SentinelCommands: def sentinel(self, *args): warnings.warn(DeprecationWarning("Use the individual sentinel_* methods")) def sentinel_get_master_addr_by_name(self, service_name, return_responses=False): return self.execute_command( "SENTINEL GET-MASTER-ADDR-B...
--- +++ @@ -2,11 +2,20 @@ class SentinelCommands: + """ + A class containing the commands specific to redis sentinel. This class is + to be used as a mixin. + """ def sentinel(self, *args): + """Redis Sentinel's SENTINEL command.""" warnings.warn(DeprecationWarning("Use the indivi...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/sentinel.py
Auto-generate documentation strings for this file
import logging import sys from abc import ABC from asyncio import IncompleteReadError, StreamReader, TimeoutError from typing import Awaitable, Callable, List, Optional, Protocol, Union from redis.maint_notifications import ( MaintenanceNotification, NodeFailedOverNotification, NodeFailingOverNotification,...
--- +++ @@ -108,6 +108,7 @@ @classmethod def parse_error(cls, response): + "Parse an error response" error_code = response.split(" ")[0] if error_code in cls.EXCEPTION_CLASSES: response = response[len(error_code) + 1 :] @@ -125,6 +126,7 @@ class _RESPBase(BaseParser)...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/_parsers/base.py
Generate NumPy-style docstrings
import random import weakref from typing import Optional, Union from redis._parsers.socket import SENTINEL from redis.client import Redis from redis.commands import SentinelCommands from redis.connection import Connection, ConnectionPool, SSLConnection from redis.exceptions import ( ConnectionError, ReadOnlyEr...
--- +++ @@ -142,6 +142,12 @@ class SentinelConnectionPool(ConnectionPool): + """ + Sentinel backed connection pool. + + If ``check_connection`` flag is set to True, SentinelManagedConnection + sends a PING command right after establishing the connection. + """ def __init__(self, service_name, ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/sentinel.py
Expand my code with proper documentation strings
def tags(*t): if not t: raise ValueError("At least one tag must be specified") return TagValue(*t) def between(a, b, inclusive_min=True, inclusive_max=True): return RangeValue(a, b, inclusive_min=inclusive_min, inclusive_max=inclusive_max) def equal(n): return between(n, n) def lt(n): ...
--- +++ @@ -1,44 +1,79 @@ def tags(*t): + """ + Indicate that the values should be matched to a tag field + + ### Parameters + + - **t**: Tags to search for + """ if not t: raise ValueError("At least one tag must be specified") return TagValue(*t) def between(a, b, inclusive_min=T...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/querystring.py
Add docstrings that explain inputs and outputs
import asyncio import threading from abc import ABC, abstractmethod from enum import Enum from typing import Dict, List, Optional, Type, Union from redis.auth.token import TokenInterface from redis.credentials import CredentialProvider, StreamingCredentialProvider from redis.observability.recorder import ( init_co...
--- +++ @@ -14,6 +14,9 @@ class EventListenerInterface(ABC): + """ + Represents a listener for given event object. + """ @abstractmethod def listen(self, event: object): @@ -21,6 +24,9 @@ class AsyncEventListenerInterface(ABC): + """ + Represents an async listener for given event obje...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/event.py
Generate consistent docstrings
import logging import random import socket import sys import threading import time from abc import ABC, abstractmethod from collections import OrderedDict from copy import copy from enum import Enum from itertools import chain from typing import ( Any, Callable, Dict, List, Literal, Optional, ...
--- +++ @@ -149,6 +149,9 @@ def parse_cluster_shards(resp, **options): + """ + Parse CLUSTER SHARDS response. + """ if isinstance(resp[0], dict): return resp shards = [] @@ -168,6 +171,9 @@ def parse_cluster_myshardid(resp, **options): + """ + Parse CLUSTER MYSHARDID response. ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/cluster.py
Add docstrings to improve code quality
from dataclasses import dataclass from typing import Any, Dict, List, Union @dataclass class HybridResult: total_results: int results: List[Dict[str, Any]] warnings: List[Union[str, bytes]] execution_time: float class HybridCursorResult: def __init__(self, search_cursor_id: int, vsim_cursor_id:...
--- +++ @@ -4,6 +4,10 @@ @dataclass class HybridResult: + """ + Represents the result of a hybrid search query execution + Returned by the `hybrid_search` command, when using RESP version 2. + """ total_results: int results: List[Dict[str, Any]] @@ -13,5 +17,11 @@ class HybridCursorResult: ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/search/hybrid_result.py
Add docstrings with type hints explained
import asyncio import random import weakref from typing import AsyncIterator, Iterable, Mapping, Optional, Sequence, Tuple, Type from redis.asyncio.client import Redis from redis.asyncio.connection import ( Connection, ConnectionPool, EncodableT, SSLConnection, ) from redis.commands import AsyncSentine...
--- +++ @@ -97,6 +97,12 @@ class SentinelConnectionPool(ConnectionPool): + """ + Sentinel backed connection pool. + + If ``check_connection`` flag is set to True, SentinelManagedConnection + sends a PING command right after establishing the connection. + """ def __init__(self, service_name, se...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/asyncio/sentinel.py
Improve documentation using docstrings
from json import JSONDecodeError, JSONDecoder, JSONEncoder import redis from ..helpers import get_protocol_version, nativestr from .commands import JSONCommands from .decoders import bulk_of_jsons, decode_list class JSON(JSONCommands): def __init__( self, client, version=None, decoder=JSONDecoder(), en...
--- +++ @@ -8,10 +8,28 @@ class JSON(JSONCommands): + """ + Create a client for talking to json. + + :param decoder: + :type json.JSONDecoder: An instance of json.JSONDecoder + + :param encoder: + :type json.JSONEncoder: An instance of json.JSONEncoder + """ def __init__( self, ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/json/__init__.py
Create docstrings for each class method
import copy import os import socket import sys import threading import time import weakref from abc import ABC, abstractmethod from itertools import chain from queue import Empty, Full, LifoQueue from typing import ( Any, Callable, Dict, Iterable, List, Literal, Optional, Type, TypeV...
--- +++ @@ -118,6 +118,7 @@ class HiredisRespSerializer: def pack(self, *args: List): + """Pack a series of arguments into the Redis protocol""" output = [] if isinstance(args[0], str): @@ -139,6 +140,7 @@ self.encode = encode def pack(self, *args): + """Pack a se...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/connection.py
Write Python docstrings for this snippet
class Path: strPath = "" @staticmethod def root_path(): return "." def __init__(self, path): self.strPath = path def __repr__(self): return self.strPath
--- +++ @@ -1,13 +1,16 @@ class Path: + """This class represents a path in a JSON value.""" strPath = "" @staticmethod def root_path(): + """Return the root path's string representation.""" return "." def __init__(self, path): + """Make a new path based on the string ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/commands/json/path.py
Add docstrings following best practices
import datetime import inspect import logging import textwrap import warnings from collections.abc import Callable from contextlib import contextmanager from functools import wraps from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Optional, TypeVar, Union from redis.exceptions import DataError from redis.typ...
--- +++ @@ -45,6 +45,12 @@ def from_url(url: str, **kwargs: Any) -> "Redis": + """ + Returns an active Redis client generated from the given database URL. + + Will attempt to extract the database id from the path url fragment, if + none is provided. + """ from redis.client import Redis re...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/utils.py
Add concise docstrings to each method
# from __future__ import annotations from datetime import datetime, timedelta from typing import ( TYPE_CHECKING, Any, Awaitable, Iterable, Literal, Mapping, Protocol, Type, TypeVar, Union, ) if TYPE_CHECKING: from redis._parsers import Encoder from redis.event import E...
--- +++ @@ -23,11 +23,21 @@ class AsyncClientProtocol(Protocol): + """Protocol for asynchronous Redis clients (redis.asyncio.client.Redis). + + This protocol uses a Literal marker to identify async clients. + Used in @overload to provide correct return types for async clients. + """ _is_async_cli...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/typing.py
Generate docstrings with examples
# https://github.com/pyinvoke/invoke/issues/833 import inspect import os import shutil from invoke import run, task if not hasattr(inspect, "getargspec"): inspect.getargspec = inspect.getfullargspec @task def devenv(c, endpoints="all"): clean(c) cmd = f"docker compose --profile {endpoints} up -d --build...
--- +++ @@ -11,6 +11,7 @@ @task def devenv(c, endpoints="all"): + """Brings up the test environment, by wrapping docker compose.""" clean(c) cmd = f"docker compose --profile {endpoints} up -d --build" run(cmd) @@ -18,29 +19,34 @@ @task def build_docs(c): + """Generates the sphinx documentatio...
https://raw.githubusercontent.com/redis/redis-py/HEAD/tasks.py
Create docstrings for all classes and functions
from abc import ABC, abstractmethod from enum import Enum from typing import Callable import pybreaker DEFAULT_GRACE_PERIOD = 60 class State(Enum): CLOSED = "closed" OPEN = "open" HALF_OPEN = "half-open" class CircuitBreaker(ABC): @property @abstractmethod def grace_period(self) -> float: ...
--- +++ @@ -17,38 +17,48 @@ @property @abstractmethod def grace_period(self) -> float: + """The grace period in seconds when the circle should be kept open.""" pass @grace_period.setter @abstractmethod def grace_period(self, grace_period: float): + """Set the grace ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/circuit.py
Improve documentation using docstrings
import logging import threading from concurrent.futures import as_completed from concurrent.futures.thread import ThreadPoolExecutor from typing import Any, Callable, List, Literal, Optional from redis.background import BackgroundScheduler from redis.backoff import NoBackoff from redis.client import PubSubWorkerThread...
--- +++ @@ -35,6 +35,10 @@ @experimental class MultiDBClient(RedisModuleCommands, CoreCommands): + """ + Client that operates on multiple logical Redis databases. + Should be used in Client-side geographic failover database setups. + """ def __init__(self, config: MultiDbConfig): self._da...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/client.py
Create Google-style docstrings for my code
from typing import List from redis.client import Redis from redis.event import EventListenerInterface, OnCommandsFailEvent from redis.multidb.database import SyncDatabase from redis.multidb.failure_detector import FailureDetector class ActiveDatabaseChanged: def __init__( self, old_database: Syn...
--- +++ @@ -7,6 +7,9 @@ class ActiveDatabaseChanged: + """ + Event fired when an active database has been changed. + """ def __init__( self, @@ -38,6 +41,9 @@ class ResubscribeOnActiveDatabaseChanged(EventListenerInterface): + """ + Re-subscribe the currently active pub / sub to a...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/event.py
Replace inline comments with docstrings
import abc import socket from time import sleep from typing import ( TYPE_CHECKING, Any, Callable, Generic, Iterable, Optional, Tuple, Type, TypeVar, Union, ) from redis.exceptions import ConnectionError, TimeoutError T = TypeVar("T") E = TypeVar("E", bound=Exception, covariant...
--- +++ @@ -24,6 +24,7 @@ class AbstractRetry(Generic[E], abc.ABC): + """Retry a specific number of times after a failure""" _supported_errors: Tuple[Type[E], ...] @@ -33,6 +34,13 @@ retries: int, supported_errors: Tuple[Type[E], ...], ): + """ + Initialize a `Retry` ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/retry.py
Write docstrings for backend logic
from dataclasses import dataclass, field from enum import Enum from typing import List, Optional, Type, Union import pybreaker from redis import ConnectionPool, Redis, RedisCluster from redis.backoff import ExponentialWithJitterBackoff, NoBackoff from redis.data_structure import WeightedList from redis.event import E...
--- +++ @@ -54,6 +54,29 @@ @dataclass class DatabaseConfig: + """ + Dataclass representing the configuration for a database connection. + + This class is used to store configuration settings for a database connection, + including client options, connection sourcing details, circuit breaker settings, + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/config.py
Add well-formatted docstrings
from enum import Enum from typing import TYPE_CHECKING, Any, Dict, Optional, Union import redis if TYPE_CHECKING: from redis.asyncio.connection import ConnectionPool from redis.asyncio.multidb.database import AsyncDatabase from redis.connection import ConnectionPoolInterface from redis.multidb.databa...
--- +++ @@ -1,3 +1,11 @@+""" +OpenTelemetry semantic convention attributes for Redis. + +This module provides constants and helper functions for building OTel attributes +according to the semantic conventions for database clients. + +Reference: https://opentelemetry.io/docs/specs/semconv/database/redis/ +""" from en...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/attributes.py
Add docstrings to incomplete code
import base64 import datetime import ssl from urllib.parse import urljoin, urlparse import cryptography.hazmat.primitives.hashes import requests from cryptography import hazmat, x509 from cryptography.exceptions import InvalidSignature from cryptography.hazmat import backends from cryptography.hazmat.primitives.asymme...
--- +++ @@ -48,6 +48,7 @@ def _check_certificate(issuer_cert, ocsp_bytes, validate=True): + """A wrapper the return the validity of a known ocsp certificate""" ocsp_response = ocsp.load_der_ocsp_response(ocsp_bytes) @@ -139,6 +140,11 @@ def ocsp_staple_verifier(con, ocsp_bytes, expected=None): + ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/ocsp.py
Add docstrings for better understanding
import time from abc import ABC, abstractmethod from redis.data_structure import WeightedList from redis.multidb.circuit import State as CBState from redis.multidb.database import Databases, SyncDatabase from redis.multidb.exception import ( NoValidDatabaseException, TemporaryUnavailableException, ) DEFAULT_F...
--- +++ @@ -16,10 +16,12 @@ class FailoverStrategy(ABC): @abstractmethod def database(self) -> SyncDatabase: + """Select the database according to the strategy.""" pass @abstractmethod def set_databases(self, databases: Databases) -> None: + """Set the database strategy oper...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/failover.py
Add structured docstrings to improve clarity
from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import Any, Callable, List, Optional, Tuple from redis.client import Pipeline, PubSub, PubSubWorkerThread from redis.event import EventDispatcherInterface, OnCommandsFailEvent from redis.multidb.circuit import State as CBState fro...
--- +++ @@ -30,11 +30,13 @@ @property @abstractmethod def auto_fallback_interval(self) -> float: + """Returns auto-fallback interval.""" pass @auto_fallback_interval.setter @abstractmethod def auto_fallback_interval(self, auto_fallback_interval: float) -> None: + ""...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/command_executor.py
Create documentation for each function signature
import logging from typing import Optional from redis.observability.config import OTelConfig logger = logging.getLogger(__name__) # Optional imports - OTel SDK may not be installed try: from opentelemetry.sdk.metrics import MeterProvider OTEL_AVAILABLE = True except ImportError: OTEL_AVAILABLE = False ...
--- +++ @@ -1,3 +1,24 @@+""" +OpenTelemetry provider management for redis-py. + +This module handles initialization and lifecycle management of OTel SDK components +including MeterProvider, TracerProvider (future), and LoggerProvider (future). + +Uses a singleton pattern - initialize once globally, all Redis clients us...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/providers.py
Write clean docstrings for readability
import logging import time from enum import Enum from typing import TYPE_CHECKING, Callable, Optional, Union if TYPE_CHECKING: from redis.asyncio.connection import ConnectionPool from redis.asyncio.multidb.database import AsyncDatabase from redis.connection import ConnectionPoolInterface from redis.mu...
--- +++ @@ -1,3 +1,9 @@+""" +OpenTelemetry metrics collector for redis-py. + +This module defines and manages all metric instruments according to +OTel semantic conventions for database clients. +""" import logging import time @@ -40,6 +46,17 @@ class CloseReason(Enum): + """ + Enum representing the reaso...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/metrics.py
Document this script properly
class NoValidDatabaseException(Exception): pass class UnhealthyDatabaseException(Exception): def __init__(self, message, database, original_exception): super().__init__(message) self.database = database self.original_exception = original_exception class TemporaryUnavailableException...
--- +++ @@ -3,6 +3,7 @@ class UnhealthyDatabaseException(Exception): + """Exception raised when a database is unhealthy due to an underlying exception.""" def __init__(self, message, database, original_exception): super().__init__(message) @@ -11,10 +12,12 @@ class TemporaryUnavailableExcepti...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/exception.py
Auto-generate documentation strings for this file
import threading from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional # Optional import - OTel SDK may not be installed # Use Any as fallback type when OTel is not available if TYPE_CHECKING: try: from opentelemetry.metrics import Observation except ImportError: Observation = A...
--- +++ @@ -13,24 +13,39 @@ class ObservablesRegistry: + """ + Global registry for storing callbacks for observable metrics. + """ def __init__(self, registry: Dict[str, List[Callable[[], List[Any]]]] = None): self._registry = registry or {} self._lock = threading.Lock() def...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/registry.py
Add docstrings for internal functions
import math import threading from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import List, Optional, Type from redis.multidb.circuit import State as CBState DEFAULT_MIN_NUM_FAILURES = 1000 DEFAULT_FAILURE_RATE_THRESHOLD = 0.1 DEFAULT_FAILURES_DETECTION_WINDOW = 2 class Failur...
--- +++ @@ -14,18 +14,24 @@ class FailureDetector(ABC): @abstractmethod def register_failure(self, exception: Exception, cmd: tuple) -> None: + """Register a failure that occurred during command execution.""" pass @abstractmethod def register_command_execution(self, cmd: tuple) -> ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/failure_detector.py
Add well-formatted docstrings
from enum import IntFlag, auto from typing import List, Optional, Sequence """ OpenTelemetry configuration for redis-py. This module handles configuration for OTel observability features, including parsing environment variables and validating settings. """ class MetricGroup(IntFlag): RESILIENCY = auto() CO...
--- +++ @@ -10,6 +10,7 @@ class MetricGroup(IntFlag): + """Metric groups that can be enabled/disabled.""" RESILIENCY = auto() CONNECTION_BASIC = auto() @@ -21,6 +22,7 @@ class TelemetryOption(IntFlag): + """Telemetry options to export.""" METRICS = auto() @@ -49,6 +51,53 @@ class ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/config.py
Document functions with clear intent
import logging from abc import ABC, abstractmethod from enum import Enum from time import sleep from typing import List, Optional, Tuple, Union from redis import Redis from redis.backoff import NoBackoff from redis.http.http_client import DEFAULT_TIMEOUT, HttpClient from redis.multidb.exception import UnhealthyDatabas...
--- +++ @@ -21,23 +21,30 @@ class HealthCheck(ABC): @abstractmethod def check_health(self, database) -> bool: + """Function to determine the health status.""" pass class HealthCheckPolicy(ABC): + """ + Health checks execution policy. + """ @property @abstractmethod ...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/healthcheck.py
Generate docstrings with parameter types
from abc import ABC, abstractmethod from typing import Optional, Union import redis from redis import RedisCluster from redis.data_structure import WeightedList from redis.multidb.circuit import CircuitBreaker from redis.typing import Number class AbstractDatabase(ABC): @property @abstractmethod def weig...
--- +++ @@ -12,21 +12,25 @@ @property @abstractmethod def weight(self) -> float: + """The weight of this database in compare to others. Used to determine the database failover to.""" pass @weight.setter @abstractmethod def weight(self, weight: float): + """Set the w...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/multidb/database.py
Help me document legacy Python code
from datetime import datetime from typing import TYPE_CHECKING, Callable, List, Optional from redis.observability.attributes import ( AttributeBuilder, ConnectionState, CSCReason, CSCResult, GeoFailoverReason, PubSubDirection, ) from redis.observability.metrics import CloseReason, RedisMetrics...
--- +++ @@ -1,3 +1,23 @@+""" +Simple, clean API for recording observability metrics. + +This module provides a straightforward interface for Redis core code to record +metrics without needing to know about OpenTelemetry internals. + +Usage in Redis core code: + from redis.observability.recorder import record_operati...
https://raw.githubusercontent.com/redis/redis-py/HEAD/redis/observability/recorder.py
Write docstrings describing functionality
# SPDX-License-Identifier: AGPL-3.0-or-later from urllib.parse import urlencode, unquote from lxml import html from searx import logger from searx.utils import ( eval_xpath, eval_xpath_list, eval_xpath_getindex, extract_text, ) from searx.engines.google import ( get_lang_info, time_range_dict...
--- +++ @@ -1,4 +1,21 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Google (Images) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. + +.. _admonition:: Content-Security-Policy (CSP) + + This engine needs to allow images from the `data URLs`_ (prefixed with the + ``data...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/google_images.py
Help me document legacy Python code
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-function-docstring import binascii import re from urllib.parse import urlencode from base64 import b64decode from random import random from lxml import html from searx import logger from searx.utils import ( eval_xpath, eval...
--- +++ @@ -1,4 +1,19 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Google (News) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. Not all parameters can be applied: + +- num_ : the number of search results is ignored +- save_ : is ignored / Google-News results are always ...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/google_news.py
Generate docstrings for exported functions
# SPDX-License-Identifier: AGPL-3.0-or-later import json from urllib.parse import urlencode, urlparse, urljoin from lxml import html from searx import logger from searx.data import WIKIDATA_UNITS from searx.engines.duckduckgo import language_aliases from searx.engines.duckduckgo import _fetch_supported_languages, sup...
--- +++ @@ -1,4 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +""" + DuckDuckGo (Instant Answer API) +""" import json from urllib.parse import urlencode, urlparse, urljoin @@ -35,6 +38,12 @@ def is_broken_text(text): + """ duckduckgo may return something like "<a href="xxxx">http://somewhere Related w...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/duckduckgo_definitions.py
Add docstrings that explain purpose and usage
# SPDX-License-Identifier: AGPL-3.0-or-later from json import loads, dumps from requests.auth import HTTPBasicAuth from searx.exceptions import SearxEngineAPIException base_url = 'http://localhost:9200' username = '' password = '' index = '' search_url = base_url + '/' + index + '/_search' query_type = 'match' custo...
--- +++ @@ -1,4 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +""" + Elasticsearch +""" from json import loads, dumps from requests.auth import HTTPBasicAuth @@ -40,6 +43,11 @@ def _match_query(query): + """ + The standard for full text queries. + searx format: "key:value" e.g. city:berlin + ...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/elasticsearch.py
Add verbose docstrings with examples
# SPDX-License-Identifier: AGPL-3.0-or-later import re from os.path import expanduser, isabs, realpath, commonprefix from shlex import split as shlex_split from subprocess import Popen, PIPE from threading import Thread from searx import logger engine_type = 'offline' paging = True command = [] delimiter = {} parse...
--- +++ @@ -1,4 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +""" + Command (offline) +""" import re from os.path import expanduser, isabs, realpath, commonprefix @@ -135,6 +138,7 @@ def check_parsing_options(engine_settings): + """ Checks if delimiter based parsing or regex parsing is configured cor...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/command.py
Generate docstrings for script automation
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-function-docstring from urllib.parse import urlencode from datetime import datetime from random import random from lxml import html from searx import logger from searx.utils import ( eval_xpath, eval_xpath_list, extract_...
--- +++ @@ -1,4 +1,12 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Google (Scholar) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. + +.. _Query Parameter Definitions: + https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions +...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/google_scholar.py
Create simple docstrings for beginners
# SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint # pylint: disable=missing-function-docstring import re from json import loads from urllib.parse import urlencode from functools import partial from flask_babel import gettext from searx.data import OSM_KEYS_TAGS, CURRENCIES from searx.utils import searx_use...
--- +++ @@ -1,5 +1,8 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint +"""OpenStreetMap (Map) + +""" # pylint: disable=missing-function-docstring import re @@ -135,6 +138,7 @@ def request(query, params): + """do search-request""" params['url'] = base_url + search_string.format(query=urlen...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/openstreetmap.py
Document my Python code with docstrings
# SPDX-License-Identifier: AGPL-3.0-or-later import re from urllib.parse import quote, urljoin from lxml import html from searx.utils import extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex # about about = { "website": 'https://www.duden.de', "wikidata_id": 'Q73624591', "official_api_documen...
--- +++ @@ -1,4 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +""" + Duden +""" import re from urllib.parse import quote, urljoin @@ -24,6 +27,15 @@ def request(query, params): + '''pre-request callback + params<dict>: + method : POST/GET + headers : {} + data : {} # if method ==...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/duden.py
Turn comments into proper docstrings
from urllib.parse import urlencode, urlparse, parse_qs from dateutil.parser import parse as dateparse from lxml import html from searx.utils import extract_text categories = ['music'] paging = True base_url = "https://bandcamp.com/" search_string = search_string = 'search?{query}&page={page}' embedded_url = '''<ifra...
--- +++ @@ -1,3 +1,11 @@+""" +Bandcamp (Music) + +@website https://bandcamp.com/ +@provide-api no +@results HTML +@parse url, title, content, publishedDate, embedded, thumbnail +""" from urllib.parse import urlencode, urlparse, parse_qs from dateutil.parser import parse as dateparse @@ -16,6 +24,15 @@...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/bandcamp.py
Provide docstrings following PEP 257
# SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint from datetime import ( datetime, timedelta, ) from json import loads from urllib.parse import urlencode from flask_babel import gettext from searx.utils import match_language from searx.exceptions import SearxEngineAPIException from searx.raise_for_h...
--- +++ @@ -1,5 +1,27 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint +"""Qwant (Web, News, Images, Videos) + +This engine uses the Qwant API (https://api.qwant.com/v3). The API is +undocumented but can be reverse engineered by reading the network log of +https://www.qwant.com/ queries. + +This implemen...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/qwant.py
Write reusable docstrings
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-function-docstring import re from urllib.parse import urlencode from random import random from lxml import html from searx import logger from searx.utils import ( eval_xpath, eval_xpath_list, eval_xpath_getindex, ext...
--- +++ @@ -1,4 +1,22 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Google (Video) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. Not all parameters can be applied. + +.. _admonition:: Content-Security-Policy (CSP) + + This engine needs to allow images from the `data U...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/google_videos.py
Write reusable docstrings
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=invalid-name, missing-function-docstring, too-many-branches from urllib.parse import urlencode, urlparse from random import random from lxml import html from searx import logger from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_...
--- +++ @@ -1,4 +1,12 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Google (Web) + +For detailed description of the *REST-full* API see: `Query Parameter +Definitions`_. + +.. _Query Parameter Definitions: + https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions +""" ...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/google.py
Add docstrings to improve collaboration
# SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint __all__ = [ 'ENGINES_LANGUAGES', 'CURRENCIES', 'USER_AGENTS', 'EXTERNAL_URLS', 'WIKIDATA_UNITS', 'EXTERNAL_BANGS', 'OSM_KEYS_TAGS', 'ahmia_blacklist_loader', ] import json from pathlib import Path data_dir = Path(__file__).pa...
--- +++ @@ -1,5 +1,10 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # lint: pylint +"""This module holds the *data* created by:: + + make data.all + +""" __all__ = [ 'ENGINES_LANGUAGES', @@ -24,6 +29,14 @@ def ahmia_blacklist_loader(): + """Load data from `ahmia_blacklist.txt` and return a list of MD...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/data/__init__.py
Expand my code with proper documentation strings
class SearxException(Exception): pass class SearxParameterException(SearxException): def __init__(self, name, value): if value == '' or value is None: message = 'Empty ' + name + ' parameter' else: message = 'Invalid value "' + value + '" for parameter ' + name ...
--- +++ @@ -1,3 +1,19 @@+''' +searx is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +searx is distributed in the hope that it wil...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/exceptions.py
Add minimal docstrings for each function
from urllib.parse import urlencode from datetime import datetime from flask_babel import gettext from searx import logger about = { "website": "https://tineye.com", "wikidata_id": "Q2382535", "use_official_api": False, "require_api_key": False, "results": "JSON", } categories = ['images'] pagi...
--- +++ @@ -1,3 +1,6 @@+""" +Tineye - Reverse search images +""" from urllib.parse import urlencode @@ -64,6 +67,31 @@ def parse_tineye_match(match_json): + """Takes parsed JSON from the API server and turns it into a :py:obj:`dict` + object. + + Attributes `(class Match) <https://github.com/TinEye/py...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/engines/tineye.py
Generate docstrings with examples
import math from searx.data import EXTERNAL_URLS IMDB_PREFIX_TO_URL_ID = { 'tt': 'imdb_title', 'mn': 'imdb_name', 'ch': 'imdb_character', 'co': 'imdb_company', 'ev': 'imdb_event' } HTTP_WIKIMEDIA_IMAGE = 'http://commons.wikimedia.org/wiki/Special:FilePath/' def get_imdb_url_id(imdb_item_id): ...
--- +++ @@ -27,6 +27,13 @@ def get_external_url(url_id, item_id, alternative="default"): + """Return an external URL or None if url_id is not found. + + url_id can take value from data/external_urls.json + The "imdb_id" value is automatically converted according to the item_id value. + + If item_id is N...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/external_urls.py
Generate docstrings for each module
import sys from time import time from itertools import cycle from threading import local import requests from searx import settings from searx import logger from searx.raise_for_httperror import raise_for_httperror logger = logger.getChild('poolrequests') try: import ssl if ssl.OPENSSL_VERSION_INFO[0:3] <...
--- +++ @@ -97,6 +97,7 @@ self.mount('http://', http_adapter) def close(self): + """Call super, but clear adapters since there are managed globally""" self.adapters.clear() super().close() @@ -152,6 +153,7 @@ def request(method, url, **kwargs): + """same as requests/...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/poolrequests.py
Document my Python code with docstrings
# SPDX-License-Identifier: AGPL-3.0-or-later # pylint: disable=useless-object-inheritance from base64 import urlsafe_b64encode, urlsafe_b64decode from zlib import compress, decompress from urllib.parse import parse_qs, urlencode from searx import settings, autocomplete from searx.languages import language_codes as l...
--- +++ @@ -1,4 +1,6 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +"""Searx preferences implementation. +""" # pylint: disable=useless-object-inheritance @@ -20,13 +22,18 @@ class MissingArgumentException(Exception): + """Exption from ``cls._post_init`` when a argument is missed. + """ class Vali...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/preferences.py
Document this module using docstrings
# SPDX-License-Identifier: AGPL-3.0-or-later from searx.exceptions import (SearxEngineCaptchaException, SearxEngineTooManyRequestsException, SearxEngineAccessDeniedException) def is_cloudflare_challenge(resp): if resp.status_code in [429, 503]: if ('__cf_chl_jschl_tk__=' in r...
--- +++ @@ -1,4 +1,7 @@ # SPDX-License-Identifier: AGPL-3.0-or-later +""" +Raise exception for an HTTP response is an error. +""" from searx.exceptions import (SearxEngineCaptchaException, SearxEngineTooManyRequestsException, SearxEngineAccessDeniedException) @@ -42,6 +45,17 @@ def...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/raise_for_httperror.py
Generate consistent documentation across files
# SPDX-License-Identifier: AGPL-3.0-or-later from abc import abstractmethod, ABC import re from searx.languages import language_codes from searx.engines import categories, engines, engine_shortcuts from searx.external_bang import get_bang_definition_and_autocomplete from searx.search import EngineRef from searx.webut...
--- +++ @@ -17,6 +17,7 @@ @staticmethod @abstractmethod def check(raw_value): + """Check if raw_value can be parsed""" def __init__(self, raw_text_query, enable_autocomplete): self.raw_text_query = raw_text_query @@ -24,6 +25,13 @@ @abstractmethod def __call__(self, raw_v...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/query.py
Generate descriptive docstrings automatically
#!/usr/bin/env python # pylint: disable=pointless-string-statement ''' searx is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. searx is...
--- +++ @@ -1,4 +1,62 @@ #!/usr/bin/env python +"""Script to run searx from terminal. + +Getting categories without initiate the engine will only return `['general']` + +>>> import searx.engines +... list(searx.engines.categories.keys()) +['general'] +>>> import searx.search +... searx.search.initialize() +... list(sea...
https://raw.githubusercontent.com/searx/searx/HEAD/searx_extra/standalone_searx.py
Add docstrings to incomplete code
#!/usr/bin/env python # pylint: disable=C0116 import json import re from os.path import join import requests from searx import searx_dir # pylint: disable=E0401 C0413 # from https://duckduckgo.com/newbang URL_BV1 = 'https://duckduckgo.com/bv1.js' RE_BANG_VERSION = re.compile(r'\/bang\.v([0-9]+)\.js') HTTPS_COLON ...
--- +++ @@ -1,4 +1,16 @@ #!/usr/bin/env python +""" +Update searx/data/external_bangs.json using the duckduckgo bangs. + +https://duckduckgo.com/newbang loads +* a javascript which provides the bang version ( https://duckduckgo.com/bv1.js ) +* a JSON file which contains the bangs ( https://duckduckgo.com/bang.v260.js f...
https://raw.githubusercontent.com/searx/searx/HEAD/searx_extra/update/update_external_bangs.py
Add docstrings to clarify complex logic
# SPDX-License-Identifier: AGPL-3.0-or-later import typing import types import functools import itertools import threading from time import time from urllib.parse import urlparse import re from langdetect import detect_langs from langdetect.lang_detect_exception import LangDetectException import requests.exceptions ...
--- +++ @@ -258,18 +258,24 @@ self._check_infoboxes(self.result_container.infoboxes) def has_infobox(self): + """Check the ResultContainer has at least one infobox""" if len(self.result_container.infoboxes) == 0: self._record_error('No infobox') def has_answer(self...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/search/checker/impl.py
Add docstrings explaining edge cases
# -*- coding: utf-8 -*- import os import csv import hashlib import hmac import re import inspect from io import StringIO from codecs import getincrementalencoder from searx import logger VALID_LANGUAGE_CODE = re.compile(r'^[a-z]{2,3}(-[a-zA-Z]{2})?$') logger = logger.getChild('webutils') class UnicodeWriter: ...
--- +++ @@ -18,6 +18,10 @@ class UnicodeWriter: + """ + A CSV writer which will write rows to CSV file "f", + which is encoded in the given encoding. + """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue @@ -52,6 +56,7 @@ def get_theme...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/webutils.py
Expand my code with proper documentation strings
# -*- coding: utf-8 -*- import sys import re import importlib from numbers import Number from os.path import splitext, join from random import choice from html.parser import HTMLParser from urllib.parse import urljoin, urlparse, urlunparse from lxml import html from lxml.etree import ElementBase, XPath, XPathError, X...
--- +++ @@ -42,12 +42,17 @@ def searx_useragent(): + """Return the searx User Agent""" return 'searx/{searx_version} {suffix}'.format( searx_version=VERSION_STRING, suffix=settings['outgoing'].get('useragent_suffix', '')) def gen_useragent(os=None): + """Return a random brows...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/utils.py
Can you add docstrings to this Python file?
#!/usr/bin/env python # pylint: disable=C0116 # set path from os.path import join import pygments from pygments.formatters import HtmlFormatter # pylint: disable=E0611 from pygments.style import Style from pygments.token import Comment, Error, Generic, Keyword, Literal, Name, Operator, Text from searx import searx_...
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python +""" +Update pygments style + +Call this script after each upgrade of pygments +""" # pylint: disable=C0116 @@ -13,6 +18,9 @@ class LogicodevStyle(Style): # pylint: disable=R0903 + """Logicodev style + based on https://github.com/searx/searx/blob/2a5c39e33c3...
https://raw.githubusercontent.com/searx/searx/HEAD/searx_extra/update/update_pygments.py
Document my Python code with docstrings
from __future__ import annotations import os import re import sys from pathlib import Path from typing import TYPE_CHECKING from typing import Any from typing import NamedTuple import requests from github import Github if TYPE_CHECKING: from collections.abc import Iterable from github.Issue import Issue C...
--- +++ @@ -1,3 +1,11 @@+""" +Creates an issue that generates a table for dependency checking whether +all packages support the latest Django version. "Latest" does not include +patches, only comparing major and minor version numbers. + +This script handles when there are multiple Django versions that need +to keep up ...
https://raw.githubusercontent.com/cookiecutter/cookiecutter-django/HEAD/scripts/create_django_issue.py
Add inline docstrings for readability
import typing import gc import threading from time import time from uuid import uuid4 from _thread import start_new_thread from searx import settings from searx.answerers import ask from searx.external_bang import get_bang_url from searx.results import ResultContainer from searx import logger from searx.plugins impor...
--- +++ @@ -1,3 +1,19 @@+''' +searx is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +searx is distributed in the hope that it wil...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/search/__init__.py
Create documentation for each function signature
#!/usr/bin/env python import sys if sys.version_info[0] < 3: print('\033[1;31m Python2 is no longer supported\033[0m') exit(1) if __name__ == '__main__': from os.path import realpath, dirname sys.path.append(realpath(dirname(realpath(__file__)) + '/../')) import hashlib import hmac import json impor...
--- +++ @@ -1,5 +1,21 @@ #!/usr/bin/env python +''' +searx is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +searx is distribute...
https://raw.githubusercontent.com/searx/searx/HEAD/searx/webapp.py
Add return value explanations in docstrings
from django.conf import settings from django.db import migrations def _update_or_create_site_with_sequence(site_model, connection, domain, name): site, created = site_model.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": domain, "name": name, }, ...
--- +++ @@ -1,8 +1,14 @@+""" +To understand why this file is here, please read: + +https://cookiecutter-django.readthedocs.io/en/latest/5-help/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django +""" from django.conf import settings from django.db import migrations def _update_or_create...
https://raw.githubusercontent.com/cookiecutter/cookiecutter-django/HEAD/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/contrib/sites/migrations/0003_set_site_domain_and_name.py
Add docstrings to improve collaboration
from typing import TYPE_CHECKING from django.contrib.auth.hashers import make_password from django.contrib.auth.models import UserManager as DjangoUserManager if TYPE_CHECKING: from .models import User # noqa: F401 class UserManager(DjangoUserManager["User"]): def _create_user(self, email: str, password: ...
--- +++ @@ -8,8 +8,12 @@ class UserManager(DjangoUserManager["User"]): + """Custom manager for the User model.""" def _create_user(self, email: str, password: str | None, **extra_fields): + """ + Create and save a user with the given email and password. + """ if not email: ...
https://raw.githubusercontent.com/cookiecutter/cookiecutter-django/HEAD/{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/managers.py
Improve my code by adding docstrings
import json import os from pathlib import Path from github import Github from github.NamedUser import NamedUser from jinja2 import Template CURRENT_FILE = Path(__file__) ROOT = CURRENT_FILE.parents[1] BOT_LOGINS = ["pyup-bot"] GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", None) GITHUB_REPO = os.getenv("GITHUB_REPOSITORY",...
--- +++ @@ -14,6 +14,13 @@ def main() -> None: + """ + Script entry point. + + 1. Fetch recent contributors from the Github API + 2. Add missing ones to the JSON file + 3. Generate Markdown from JSON file + """ recent_authors = set(iter_recent_authors()) # Add missing users to the JSON...
https://raw.githubusercontent.com/cookiecutter/cookiecutter-django/HEAD/scripts/update_contributors.py
Add well-formatted docstrings
import datetime as dt import os import re import subprocess from collections.abc import Iterable from pathlib import Path import git import github.PullRequest import github.Repository from github import Github from jinja2 import Template CURRENT_FILE = Path(__file__) ROOT = CURRENT_FILE.parents[1] GITHUB_TOKEN = os.g...
--- +++ @@ -19,6 +19,9 @@ def main() -> None: + """ + Script entry point. + """ # Generate changelog for PRs merged yesterday merged_date = dt.date.today() - dt.timedelta(days=1) # noqa: DTZ011 repo = Github(login_or_token=GITHUB_TOKEN).get_repo(GITHUB_REPO) @@ -69,6 +72,7 @@ repo: gith...
https://raw.githubusercontent.com/cookiecutter/cookiecutter-django/HEAD/scripts/update_changelog.py
Write Python docstrings for this snippet
from pwnlib.context import LocalContext from pwnlib.context import context class ABI(object): #: List or registers which should be filled with arguments before #: spilling onto the stack. register_arguments = [] #: Minimum alignment of the stack. #: The value used is min(context.bytes, stack_alig...
--- +++ @@ -3,6 +3,9 @@ class ABI(object): + """ + Encapsulates information about a calling convention. + """ #: List or registers which should be filled with arguments before #: spilling onto the stack. register_arguments = [] @@ -116,12 +119,21 @@ class SyscallABI(ABI): + """ + T...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/abi.py
Write beginner-friendly docstrings
import sys import threading import traceback from pwnlib.context import context __all__ = ['register', 'unregister'] _lock = threading.Lock() _ident = 0 _handlers = {} def register(func, *args, **kwargs): global _ident with _lock: ident = _ident _ident += 1 _handlers[ident] = (func, args...
--- +++ @@ -1,3 +1,7 @@+""" +Analogous to atexit, this module allows the programmer to register functions to +be run if an unhandled exception occurs. +""" import sys import threading import traceback @@ -11,6 +15,36 @@ _handlers = {} def register(func, *args, **kwargs): + """register(func, *args, **kwargs) + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/atexception.py
Generate docstrings for each module
import errno import os import platform import re import shutil import subprocess import tempfile from collections import defaultdict from glob import glob from os import environ from os import path from pwnlib import atexit from pwnlib import shellcraft from pwnlib.context import LocalContext from pwnlib.context impor...
--- +++ @@ -1,3 +1,43 @@+r""" +Utilities for assembling and disassembling code. + +Architecture Selection +------------------------ + + Architecture, endianness, and word size are selected by using :mod:`pwnlib.context`. + + Any parameters which can be specified to ``context`` can also be specified as + keywor...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/asm.py
Generate NumPy-style docstrings
from pwn import * from pwnlib.commandline import common from pwnlib.util.misc import which, parse_ldd_output, write from sys import stderr from mako.lookup import TemplateLookup, Template parser = common.parser_commands.add_parser( 'template', help = 'Generate an exploit template', description = 'Generate...
--- +++ @@ -32,6 +32,11 @@ parser.add_argument('--no-auto', help='Do not automatically detect missing binaries', action='store_false', dest='auto') def get_docker_image_libraries(): + """Tries to retrieve challenge libraries from a Docker image built from the Dockerfile in the current working directory. + + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/commandline/template.py
Please document this code using docstrings
class KernelConfig(object): def __init__(self, name, title, requires=[], excludes=[], minver=0, maxver=99): #: Name of the configuration option self.name = name #: Section to which the configuration point belongs self.title = title #: List of configuration items, one of wh...
--- +++ @@ -1,3 +1,6 @@+""" +Kernel-specific ELF functionality +""" class KernelConfig(object): def __init__(self, name, title, requires=[], excludes=[], minver=0, maxver=99): @@ -51,6 +54,18 @@ raise NotImplementedError() def __call__(self, config): + """__call__(config) -> str + + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/elf/config.py
Document functions with clear intent
import ctypes from elftools.elf.enums import ENUM_D_TAG from pwnlib import elf from pwnlib import libcdb from pwnlib.context import context from pwnlib.elf import ELF from pwnlib.elf import constants from pwnlib.log import getLogger from pwnlib.memleak import MemLeak from pwnlib.util.fiddling import enhex from pwnlib...
--- +++ @@ -1,3 +1,52 @@+""" +Resolve symbols in loaded, dynamically-linked ELF binaries. +Given a function which can leak data at an arbitrary address, +any symbol in any loaded library can be resolved. + +Example +^^^^^^^^ + +:: + + # Assume a process or remote connection + p = process('./pwnme') + + # Decla...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/dynelf.py
Replace inline comments with docstrings
import sys import threading import traceback import atexit as std_atexit from pwnlib.context import context __all__ = ['register', 'unregister'] _lock = threading.Lock() _ident = 0 _handlers = {} def register(func, *args, **kwargs): global _ident with _lock: ident = _ident _ident += 1 _h...
--- +++ @@ -1,3 +1,12 @@+""" +Replacement for the Python standard library's atexit.py. + +Whereas the standard :mod:`atexit` module only defines :func:`atexit.register`, +this replacement module also defines :func:`unregister`. + +This module also fixes a the issue that exceptions raised by an exit handler is +printed ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/atexit.py
Add docstrings with type hints explained
import logging from pwnlib.args import args from pwnlib.log import getLogger from pwnlib.util import fiddling from pwnlib.util import packing log = getLogger(__name__) def emulate_plt_instructions(elf, got, address, data, targets): rv = {} if not args.PLT_DEBUG: log.setLevel(logging.DEBUG + 1) ...
--- +++ @@ -1,3 +1,5 @@+"""Emulates instructions in the PLT to locate symbols more accurately. +""" import logging from pwnlib.args import args @@ -9,6 +11,19 @@ def emulate_plt_instructions(elf, got, address, data, targets): + """Emulates instructions in ``data`` + + Arguments: + elf(ELF): ELF tha...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/elf/plt.py
Help me comply with documentation standards
import atexit import collections import errno import functools import logging import os import os.path import platform import shutil import socket import string import sys import tempfile import threading import time import socks from pwnlib.config import register_config from pwnlib.device import Device from pwnlib.t...
--- +++ @@ -1,3 +1,7 @@+""" +Implements context management so that nested/scoped contexts and threaded +contexts work properly and as expected. +""" import atexit import collections import errno @@ -37,6 +41,34 @@ def close(self, *a, **kw): pass class _defaultdict(dict): + """ + Dictionary which loads m...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/context/__init__.py
Replace inline comments with docstrings
import collections import gzip import mmap import os import re import subprocess import tempfile from io import BytesIO from collections import namedtuple, defaultdict from elftools.elf.constants import P_FLAGS from elftools.elf.constants import SHN_INDICES from elftools.elf.descriptions import describe_e_type from ...
--- +++ @@ -1,3 +1,49 @@+"""Exposes functionality for manipulating ELF files + + +Stop hard-coding things! Look them up at runtime with :mod:`pwnlib.elf`. + +Example Usage +------------- + +.. code-block:: python + + >>> e = ELF('/bin/cat') + >>> print(hex(e.address)) #doctest: +SKIP + 0x400000 + >>> print...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/elf/elf.py
Write reusable docstrings
import ctypes import io import os import sys from pwnlib.log import getLogger log = getLogger(__name__) class img_info(ctypes.Structure): _fields_ = [ ('name', ctypes.c_char * 64), ('size', ctypes.c_uint32) ] class bootloader_images_header(ctypes.Structure): _fields_ = [ ('magic'...
--- +++ @@ -25,6 +25,11 @@ class BootloaderImage(object): def __init__(self, data): + """Android Bootloader image + + Arguments: + data(str): Binary data from the image file. + """ self.data = data self.header = bootloader_images_header.from_buffer_copy(data) @...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/adb/bootloader.py
Auto-generate documentation strings for this file
import configparser import os registered_configs = {} def register_config(section, function): registered_configs[section] = function def initialize(): from pwnlib.log import getLogger log = getLogger(__name__) xdg_config_home = os.environ.get('XDG_CONFIG_HOME', o...
--- +++ @@ -1,12 +1,53 @@+"""Allows per-user and per-host configuration of Pwntools settings. + +The list of configurable options includes all of the logging symbols +and colors, as well as all of the default values on the global context +object. + +The configuration file is read from ``~/.pwn.conf``, ``$XDG_CONFIG_HOM...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/config.py
Add docstrings for production code
import importlib import sys from types import ModuleType from pwnlib.constants.constant import Constant from pwnlib.context import context from pwnlib.util import safeeval class ConstantsModule(ModuleType): Constant = Constant possible_submodules = set(context.oses) | set(context.architectures) def __i...
--- +++ @@ -1,3 +1,55 @@+"""Module containing constants extracted from header files. + +The purpose of this module is to provide quick access to constants from +different architectures and operating systems. + +The constants are wrapped by a convenience class that allows accessing +the name of the constant, while perfo...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/constants/__init__.py
Write docstrings describing each step
import functools import glob import logging import os import re import shutil import stat import tempfile import time import dateutil.parser from pwnlib import atexit from pwnlib import tubes from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.device import Device from pwnlib.excep...
--- +++ @@ -1,3 +1,50 @@+"""Provides utilities for interacting with Android devices via the Android Debug Bridge. + +Using Android Devices with Pwntools +----------------------------------- + +Pwntools tries to be as easy as possible to use with Android devices. + +If you have only one device attached, everything "just...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/adb/adb.py
Insert docstrings into my code
import collections import logging import os import string import sys from pwnlib import term from pwnlib.context import context class PwnlibArgs(collections.defaultdict): def __getattr__(self, attr): if attr.startswith('_'): raise AttributeError(attr) return self[attr] args = PwnlibAr...
--- +++ @@ -1,3 +1,53 @@+""" +Pwntools exposes several magic command-line arguments and environment +variables when operating in `from pwn import *` mode. + +The arguments extracted from the command-line and removed from ``sys.argv``. + +Arguments can be set by appending them to the command-line, or setting +them in th...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/args.py
Auto-generate documentation strings for this file
import collections import ctypes import glob import gzip import re import os import socket import subprocess import tempfile from io import BytesIO, StringIO import elftools from elftools.common.utils import roundup from elftools.common.utils import struct_parse from elftools.construct import CString from pwnlib imp...
--- +++ @@ -1,3 +1,64 @@+"""Read information from Core Dumps. + +Core dumps are extremely useful when writing exploits, even outside of +the normal act of debugging things. + +Using Corefiles to Automate Exploitation +---------------------------------------- + +For example, if you have a trivial buffer overflow and don...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/elf/corefile.py
Add docstrings to existing functions
import os from pwnlib.args import args from pwnlib.log import getLogger from pwnlib.tubes.remote import remote env_server = args.get('FLAG_HOST', 'flag-submission-server').strip() env_port = args.get('FLAG_PORT', '31337').strip() env_file = args.get('FLAG_FILE', '/does/not/exist').strip() env_exploit_name = ar...
--- +++ @@ -1,3 +1,5 @@+"""Describes a way to submit a key to a key server. +""" import os from pwnlib.args import args @@ -19,6 +21,32 @@ server=env_server, port=env_port, team=env_team_name): + """ + Submits a flag to the game server + + Arguments: + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/flag/flag.py
Auto-generate documentation strings for this file
import os import platform import psutil import random import re import socket import tempfile from threading import Event import time from pwnlib import adb from pwnlib import atexit from pwnlib import elf from pwnlib import qemu from pwnlib import tubes from pwnlib.asm import _bfdname from pwnlib.asm import make_elf ...
--- +++ @@ -1,3 +1,142 @@+""" +During exploit development, it is frequently useful to debug the +target binary under GDB. + +Pwntools makes this easy-to-do with a handful of helper routines, designed +to make your exploit-debug-update cycles much faster. + +Useful Functions +---------------- + +- :func:`attach` - Attac...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/gdb.py
Provide clean and structured docstrings
import gdb import socket from threading import Condition import time from rpyc.core.protocol import Connection from rpyc.core.service import Service from rpyc.lib import spawn from rpyc.lib.compat import select_error from rpyc.utils.server import ThreadedServer class ServeResult: def __init__(self): sel...
--- +++ @@ -1,3 +1,4 @@+"""GDB Python API bridge.""" import gdb import socket @@ -12,6 +13,7 @@ class ServeResult: + """Result of serving requests on GDB thread.""" def __init__(self): self.cv = Condition() self.done = False @@ -32,10 +34,16 @@ class GdbConnection(Connection): + ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/gdb_api_bridge.py
Write docstrings including parameters and return values
from pwnlib.context import context from pwnlib.util.fiddling import ror, rol def ptr_mangle(guard: int, value: int) -> int: if context.arch == 'amd64' or context.arch == 'i386': return rol(value ^ guard, context.bytes * 2 + 1) return value ^ guard def ptr_demangle(guard: int, mangled: int) -> int: ...
--- +++ @@ -1,15 +1,74 @@+""" +Some glibc related convenient functions. +""" from pwnlib.context import context from pwnlib.util.fiddling import ror, rol def ptr_mangle(guard: int, value: int) -> int: + """ + Perform ``PTR_MANGLE`` in glibc to protect pointers. + + Arguments: + guard(int): The valu...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/libc/glibc.py
Add well-formatted docstrings
import os from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util import misc log = getLogger(__name__) @LocalContext def archname(): return { ('amd64', 'little'): 'x86_64', ('arm', 'big'): 'armeb', ('mips',...
--- +++ @@ -1,3 +1,77 @@+"""Run foreign-architecture binaries + +Overview +-------- + +So you want to exploit ARM binaries on your Intel PC? + +Pwntools has a good level of integration with QEMU user-mode emulation, +in order to run, debug, and pwn foreign architecture binaries. + +In general, everything magic happens ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/qemu.py
Write reusable docstrings
# https://github.com/Gallopsled/pwntools/pull/1667 from itertools import product from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.encoders.encoder import Encoder from pwnlib.encoders.encoder import all_chars from pwnlib.util.iters import group from pwnlib.util.packing import * ...
--- +++ @@ -1,141 +1,293 @@-# https://github.com/Gallopsled/pwntools/pull/1667 - -from itertools import product - -from pwnlib.context import LocalContext -from pwnlib.context import context -from pwnlib.encoders.encoder import Encoder -from pwnlib.encoders.encoder import all_chars -from pwnlib.util.iters import group ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/encoders/i386/ascii_shellcode.py
Document this script properly
from collections import OrderedDict from collections import defaultdict from random import randint from random import shuffle from pwnlib.context import context from pwnlib.log import getLogger log = getLogger(__name__) def check_cycle(reg, assignments, mapping=None): if mapping is None: mapping = {} ...
--- +++ @@ -1,3 +1,6 @@+""" +Topographical sort +""" from collections import OrderedDict from collections import defaultdict from random import randint @@ -9,6 +12,27 @@ log = getLogger(__name__) def check_cycle(reg, assignments, mapping=None): + """Walk down the assignment list of a register, + return the ...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/regsort.py
Add docstrings explaining edge cases
import collections import random import re import string from pwnlib.context import LocalContext from pwnlib.context import context from pwnlib.log import getLogger from pwnlib.util.fiddling import hexdump log = getLogger(__name__) class Encoder(object): _encoders = collections.defaultdict(lambda: []) #: Ar...
--- +++ @@ -20,14 +20,42 @@ blacklist = set() def __init__(self): + """Shellcode encoder class + + Implements an architecture-specific shellcode encoder + """ Encoder._encoders[self.arch].append(self) def __call__(self, raw_bytes, avoid, pcreg): + """avoid(raw_byte...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/encoders/encoder.py
Add well-formatted docstrings
import logging import functools import stat import time from pwnlib.context import context from pwnlib.log import Logger from pwnlib.log import getLogger from pwnlib.tubes.listen import listen from pwnlib.tubes.process import process from pwnlib.tubes.remote import remote from pwnlib.util.lists import group from pwnli...
--- +++ @@ -1,3 +1,10 @@+""" +Implementation of the Android Debug Bridge (ADB) protocol. + +Documentation is available here_. + +.. _here: https://android.googlesource.com/platform/system/core/+/master/adb/protocol.txt +""" import logging import functools import stat @@ -27,6 +34,7 @@ FAIL = b"FAIL" class Message...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/protocols/adb/__init__.py
Add standardized docstrings across the file
import os import shutil import sys try: import fcntl import termios except ImportError: pass from collections import namedtuple from struct import Struct def py2_monkey_patch(module): def decorator(f): if sys.version_info < (3,): f.__module__ = module.__name__ setattr(...
--- +++ @@ -1,3 +1,7 @@+""" +Compatibility layer with python 2, allowing us to write normal code. +Beware, some monkey-patching is done. +""" import os import shutil @@ -21,6 +25,24 @@ # python3 -c 'import shutil,inspect; print(inspect.getsource(shutil.get_terminal_size))' @py2_monkey_patch(shutil) def get_termin...
https://raw.githubusercontent.com/Gallopsled/pwntools/HEAD/pwnlib/py2compat.py