instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings for utility scripts
from typing import Literal from pydantic import BaseModel, Field CheckpointerType = Literal["memory", "sqlite", "postgres"] class CheckpointerConfig(BaseModel): type: CheckpointerType = Field( description="Checkpointer backend type. " "'memory' is in-process only (lost on restart). " "...
--- +++ @@ -1,3 +1,4 @@+"""Configuration for LangGraph checkpointer.""" from typing import Literal @@ -7,6 +8,7 @@ class CheckpointerConfig(BaseModel): + """Configuration for LangGraph state persistence checkpointer.""" type: CheckpointerType = Field( description="Checkpointer backend type. ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/checkpointer_config.py
Generate helpful docstrings for debugging
import os from pydantic import BaseModel, Field class GatewayConfig(BaseModel): host: str = Field(default="0.0.0.0", description="Host to bind the gateway server") port: int = Field(default=8001, description="Port to bind the gateway server") cors_origins: list[str] = Field(default_factory=lambda: ["htt...
--- +++ @@ -4,6 +4,7 @@ class GatewayConfig(BaseModel): + """Configuration for the API Gateway.""" host: str = Field(default="0.0.0.0", description="Host to bind the gateway server") port: int = Field(default=8001, description="Port to bind the gateway server") @@ -14,6 +15,7 @@ def get_gateway_c...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/config.py
Fully document this Python code with docstrings
import threading import time from dataclasses import dataclass, field from datetime import datetime from typing import Any from deerflow.config.memory_config import get_memory_config @dataclass class ConversationContext: thread_id: str messages: list[Any] timestamp: datetime = field(default_factory=dat...
--- +++ @@ -1,3 +1,4 @@+"""Memory update queue with debounce mechanism.""" import threading import time @@ -10,6 +11,7 @@ @dataclass class ConversationContext: + """Context for a conversation to be processed for memory update.""" thread_id: str messages: list[Any] @@ -18,14 +20,28 @@ class Mem...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/memory/queue.py
Document all public functions with docstrings
import logging import re from typing import Any import yaml from pydantic import BaseModel from deerflow.config.paths import get_paths logger = logging.getLogger(__name__) SOUL_FILENAME = "SOUL.md" AGENT_NAME_PATTERN = re.compile(r"^[A-Za-z0-9-]+$") class AgentConfig(BaseModel): name: str description: s...
--- +++ @@ -1,3 +1,4 @@+"""Configuration and loaders for custom agents.""" import logging import re @@ -15,6 +16,7 @@ class AgentConfig(BaseModel): + """Configuration for a custom agent.""" name: str description: str = "" @@ -23,6 +25,18 @@ def load_agent_config(name: str | None) -> AgentConf...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/agents_config.py
Can you add docstrings to this Python file?
import logging import os from pathlib import Path from typing import Any, Self import yaml from dotenv import load_dotenv from pydantic import BaseModel, ConfigDict, Field from deerflow.config.checkpointer_config import CheckpointerConfig, load_checkpointer_config_from_dict from deerflow.config.extensions_config impo...
--- +++ @@ -25,6 +25,7 @@ class AppConfig(BaseModel): + """Config for the DeerFlow application""" models: list[ModelConfig] = Field(default_factory=list, description="Available models") sandbox: SandboxConfig = Field(description="Sandbox configuration") @@ -38,6 +39,13 @@ @classmethod def ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/app_config.py
Write docstrings including parameters and return values
import math import re from typing import Any try: import tiktoken TIKTOKEN_AVAILABLE = True except ImportError: TIKTOKEN_AVAILABLE = False # Prompt template for updating memory based on conversation MEMORY_UPDATE_PROMPT = """You are a memory management system. Your task is to analyze a conversation and ...
--- +++ @@ -1,3 +1,4 @@+"""Prompt templates for memory update and injection.""" import math import re @@ -145,6 +146,15 @@ def _count_tokens(text: str, encoding_name: str = "cl100k_base") -> int: + """Count tokens in text using tiktoken. + + Args: + text: The text to count tokens for. + enco...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/memory/prompt.py
Write docstrings for utility functions
from pydantic import BaseModel, Field class MemoryConfig(BaseModel): enabled: bool = Field( default=True, description="Whether to enable memory mechanism", ) storage_path: str = Field( default="", description=( "Path to store memory data. " "If emp...
--- +++ @@ -1,8 +1,10 @@+"""Configuration for memory mechanism.""" from pydantic import BaseModel, Field class MemoryConfig(BaseModel): + """Configuration for global memory mechanism.""" enabled: bool = Field( default=True, @@ -60,14 +62,17 @@ def get_memory_config() -> MemoryConfig: + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/memory_config.py
Improve documentation using docstrings
from typing import Annotated, NotRequired, TypedDict from langchain.agents import AgentState class SandboxState(TypedDict): sandbox_id: NotRequired[str | None] class ThreadDataState(TypedDict): workspace_path: NotRequired[str | None] uploads_path: NotRequired[str | None] outputs_path: NotRequired[s...
--- +++ @@ -19,6 +19,7 @@ def merge_artifacts(existing: list[str] | None, new: list[str] | None) -> list[str]: + """Reducer for artifacts list - merges and deduplicates artifacts.""" if existing is None: return new or [] if new is None: @@ -28,6 +29,11 @@ def merge_viewed_images(existing: ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/thread_state.py
Include argument descriptions in docstrings
from pydantic import BaseModel, Field class TitleConfig(BaseModel): enabled: bool = Field( default=True, description="Whether to enable automatic title generation", ) max_words: int = Field( default=6, ge=1, le=20, description="Maximum number of words in t...
--- +++ @@ -1,8 +1,10 @@+"""Configuration for automatic thread title generation.""" from pydantic import BaseModel, Field class TitleConfig(BaseModel): + """Configuration for automatic thread title generation.""" enabled: bool = Field( default=True, @@ -35,14 +37,17 @@ def get_title_confi...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/title_config.py
Add docstrings for utility scripts
from typing import NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import AIMessage, HumanMessage, ToolMessage from langgraph.runtime import Runtime from deerflow.agents.thread_state import ViewedImageData class View...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for injecting image details into conversation before LLM call.""" from typing import NotRequired, override @@ -10,27 +11,65 @@ class ViewImageMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" viewed_images: NotRequired[dict[str, Viewe...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/view_image_middleware.py
Insert docstrings into my code
import json import os from pathlib import Path from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field class McpOAuthConfig(BaseModel): enabled: bool = Field(default=True, description="Whether OAuth token injection is enabled") token_url: str = Field(description="OAuth token endpo...
--- +++ @@ -1,3 +1,4 @@+"""Unified extensions configuration for MCP servers and skills.""" import json import os @@ -8,6 +9,7 @@ class McpOAuthConfig(BaseModel): + """OAuth configuration for an MCP server (HTTP/SSE transports).""" enabled: bool = Field(default=True, description="Whether OAuth token in...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/extensions_config.py
Add docstrings for production code
from __future__ import annotations import logging from typing import Any from app.channels.manager import ChannelManager from app.channels.message_bus import MessageBus from app.channels.store import ChannelStore logger = logging.getLogger(__name__) # Channel name → import path for lazy loading _CHANNEL_REGISTRY: ...
--- +++ @@ -1,3 +1,4 @@+"""ChannelService — manages the lifecycle of all IM channels.""" from __future__ import annotations @@ -19,6 +20,11 @@ class ChannelService: + """Manages the lifecycle of all configured IM channels. + + Reads configuration from ``config.yaml`` under the ``channels`` key, + inst...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/service.py
Write docstrings that follow conventions
import logging from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from fastapi import FastAPI from app.gateway.config import get_gateway_config from app.gateway.routers import ( agents, artifacts, channels, mcp, memory, models, skills, suggestions, ...
--- +++ @@ -30,6 +30,7 @@ @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + """Application lifespan handler.""" # Load config and check necessary environment variables at startup try: @@ -69,6 +70,11 @@ def create_app() -> FastAPI: + """Create and configure ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/app.py
Write docstrings for this repository
import json from langchain.tools import tool from tavily import TavilyClient from deerflow.config import get_app_config def _get_tavily_client() -> TavilyClient: config = get_app_config().get_tool_config("web_search") api_key = None if config is not None and "api_key" in config.model_extra: api_...
--- +++ @@ -16,6 +16,11 @@ @tool("web_search", parse_docstring=True) def web_search_tool(query: str) -> str: + """Search the web. + + Args: + query: The query to search for. + """ config = get_app_config().get_tool_config("web_search") max_results = 5 if config is not None and "max_res...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/tavily/tools.py
Add return value explanations in docstrings
from __future__ import annotations import contextlib import logging from collections.abc import Iterator from langgraph.types import Checkpointer from deerflow.config.app_config import get_app_config from deerflow.config.checkpointer_config import CheckpointerConfig from deerflow.config.paths import resolve_path l...
--- +++ @@ -1,3 +1,21 @@+"""Sync checkpointer factory. + +Provides a **sync singleton** and a **sync context manager** for LangGraph +graph compilation and CLI tools. + +Supported backends: memory, sqlite, postgres. + +Usage:: + + from deerflow.agents.checkpointer.provider import get_checkpointer, checkpointer_conte...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/checkpointer/provider.py
Add docstrings for internal functions
import logging from pathlib import Path from typing import NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import HumanMessage from langgraph.runtime import Runtime from deerflow.config.paths import Paths, get_paths l...
--- +++ @@ -1,3 +1,4 @@+"""Middleware to inject uploaded files information into agent context.""" import logging from pathlib import Path @@ -14,19 +15,40 @@ class UploadsMiddlewareState(AgentState): + """State schema for uploads middleware.""" uploaded_files: NotRequired[list[dict] | None] class...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/uploads_middleware.py
Add docstrings for better understanding
from __future__ import annotations import json import logging import tempfile import threading import time from pathlib import Path from typing import Any logger = logging.getLogger(__name__) class ChannelStore: def __init__(self, path: str | Path | None = None) -> None: if path is None: f...
--- +++ @@ -1,3 +1,4 @@+"""ChannelStore — persists IM chat-to-DeerFlow thread mappings.""" from __future__ import annotations @@ -13,6 +14,24 @@ class ChannelStore: + """JSON-file-backed store that maps IM conversations to DeerFlow threads. + + Data layout (on disk):: + + { + "<channel_...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/store.py
Document this script properly
import logging from collections.abc import Awaitable, Callable from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import ToolMessage from langgraph.errors import GraphBubbleUp from langgraph.prebuilt.tool_node import...
--- +++ @@ -1,3 +1,4 @@+"""Tool error handling middleware and shared runtime middleware builders.""" import logging from collections.abc import Awaitable, Callable @@ -16,6 +17,7 @@ class ToolErrorHandlingMiddleware(AgentMiddleware[AgentState]): + """Convert tool exceptions into error ToolMessages so the run...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/tool_error_handling_middleware.py
Add docstrings to improve code quality
from typing import NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from deerflow.config.title_config import get_title_config from deerflow.models import create_chat_model class TitleMiddlewareState(AgentStat...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for automatic thread title generation.""" from typing import NotRequired, override @@ -10,11 +11,13 @@ class TitleMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" title: NotRequired[str | None] class TitleMiddleware(AgentMiddlew...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/title_middleware.py
Add docstrings to make code maintainable
from pydantic import BaseModel, Field class ToolSearchConfig(BaseModel): enabled: bool = Field( default=False, description="Defer tools and enable tool_search", ) _tool_search_config: ToolSearchConfig | None = None def get_tool_search_config() -> ToolSearchConfig: global _tool_search...
--- +++ @@ -1,8 +1,15 @@+"""Configuration for deferred tool loading via tool_search.""" from pydantic import BaseModel, Field class ToolSearchConfig(BaseModel): + """Configuration for deferred tool loading via tool_search. + + When enabled, MCP tools are not loaded into the agent's context directly. + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/tool_search_config.py
Add docstrings to meet PEP guidelines
import asyncio import logging import os from langchain_core.tools import BaseTool logger = logging.getLogger(__name__) _mcp_tools_cache: list[BaseTool] | None = None _cache_initialized = False _initialization_lock = asyncio.Lock() _config_mtime: float | None = None # Track config file modification time def _get_...
--- +++ @@ -1,3 +1,4 @@+"""Cache for MCP tools to avoid repeated loading.""" import asyncio import logging @@ -14,6 +15,11 @@ def _get_config_mtime() -> float | None: + """Get the modification time of the extensions config file. + + Returns: + The modification time as a float, or None if the file d...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/mcp/cache.py
Write documentation strings for class attributes
import logging from typing import Any from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig logger = logging.getLogger(__name__) def build_server_params(server_name: str, config: McpServerConfig) -> dict[str, Any]: transport_type = config.type or "stdio" params: dict[str, Any] = {...
--- +++ @@ -1,3 +1,4 @@+"""MCP client using langchain-mcp-adapters.""" import logging from typing import Any @@ -8,6 +9,15 @@ def build_server_params(server_name: str, config: McpServerConfig) -> dict[str, Any]: + """Build server parameters for MultiServerMCPClient. + + Args: + server_name: Name of...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/mcp/client.py
Add standardized docstrings across the file
from typing import NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from deerflow.agents.thread_state import ThreadDataState from deerflow.config.paths import Paths, get_paths class ThreadDataMiddlewareState(A...
--- +++ @@ -9,20 +9,48 @@ class ThreadDataMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" thread_data: NotRequired[ThreadDataState | None] class ThreadDataMiddleware(AgentMiddleware[ThreadDataMiddlewareState]): + """Create thread data directories for each thread exec...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/thread_data_middleware.py
Auto-generate documentation strings for this file
import logging import os import threading from pydantic import BaseModel, Field logger = logging.getLogger(__name__) _config_lock = threading.Lock() class TracingConfig(BaseModel): enabled: bool = Field(...) api_key: str | None = Field(...) project: str = Field(...) endpoint: str = Field(...) ...
--- +++ @@ -9,6 +9,7 @@ class TracingConfig(BaseModel): + """Configuration for LangSmith tracing.""" enabled: bool = Field(...) api_key: str | None = Field(...) @@ -17,6 +18,7 @@ @property def is_configured(self) -> bool: + """Check if tracing is fully configured (enabled and has AP...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/tracing_config.py
Improve documentation using docstrings
class SandboxError(Exception): def __init__(self, message: str, details: dict | None = None): super().__init__(message) self.message = message self.details = details or {} def __str__(self) -> str: if self.details: detail_str = ", ".join(f"{k}={v}" for k, v in sel...
--- +++ @@ -1,6 +1,8 @@+"""Sandbox-related exceptions with structured error information.""" class SandboxError(Exception): + """Base exception for all sandbox-related errors.""" def __init__(self, message: str, details: dict | None = None): super().__init__(message) @@ -15,6 +17,7 @@ class S...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/exceptions.py
Add missing documentation to my Python functions
import json import logging from langchain.tools import tool from deerflow.config import get_app_config logger = logging.getLogger(__name__) def _search_images( query: str, max_results: int = 5, region: str = "wt-wt", safesearch: str = "moderate", size: str | None = None, color: str | None ...
--- +++ @@ -1,3 +1,6 @@+""" +Image Search Tool - Search images using DuckDuckGo for reference in image generation. +""" import json import logging @@ -20,6 +23,23 @@ layout: str | None = None, license_image: str | None = None, ) -> list[dict]: + """ + Execute image search using DuckDuckGo. + + Ar...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/image_search/tools.py
Document functions with clear intent
import json import logging import os from typing import Any import requests logger = logging.getLogger(__name__) class InfoQuestClient: def __init__(self, fetch_time: int = -1, fetch_timeout: int = -1, fetch_navigation_timeout: int = -1, search_time_range: int = -1): logger.info("\n===================...
--- +++ @@ -1,3 +1,8 @@+"""Util that calls InfoQuest Search And Fetch API. + +In order to set this up, follow instructions at: +https://docs.byteplus.com/en/docs/InfoQuest/What_is_Info_Quest +""" import json import logging @@ -10,6 +15,7 @@ class InfoQuestClient: + """Client for interacting with the InfoQues...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/infoquest/infoquest_client.py
Help me document legacy Python code
from importlib import import_module MODULE_TO_PACKAGE_HINTS = { "langchain_google_genai": "langchain-google-genai", "langchain_anthropic": "langchain-anthropic", "langchain_openai": "langchain-openai", "langchain_deepseek": "langchain-deepseek", } def _build_missing_dependency_hint(module_path: str, ...
--- +++ @@ -9,6 +9,7 @@ def _build_missing_dependency_hint(module_path: str, err: ImportError) -> str: + """Build an actionable hint when module import fails.""" module_root = module_path.split(".", 1)[0] missing_module = getattr(err, "name", None) or module_root @@ -25,6 +26,20 @@ variable_path:...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/reflection/resolvers.py
Create documentation for each function signature
from abc import ABC, abstractmethod from deerflow.config import get_app_config from deerflow.reflection import resolve_class from deerflow.sandbox.sandbox import Sandbox class SandboxProvider(ABC): @abstractmethod def acquire(self, thread_id: str | None = None) -> str: pass @abstractmethod ...
--- +++ @@ -6,17 +6,33 @@ class SandboxProvider(ABC): + """Abstract base class for sandbox providers""" @abstractmethod def acquire(self, thread_id: str | None = None) -> str: + """Acquire a sandbox environment and return its ID. + + Returns: + The ID of the acquired sandbox ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/sandbox_provider.py
Create docstrings for all classes and functions
import logging from typing import NotRequired, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from deerflow.agents.thread_state import SandboxState, ThreadDataState from deerflow.sandbox import get_sandbox_provider logger...
--- +++ @@ -12,16 +12,33 @@ class SandboxMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" sandbox: NotRequired[SandboxState | None] thread_data: NotRequired[ThreadDataState | None] class SandboxMiddleware(AgentMiddleware[SandboxMiddlewareState]): + """Create a sa...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/middleware.py
Add docstrings to improve readability
from abc import ABC, abstractmethod class Sandbox(ABC): _id: str def __init__(self, id: str): self._id = id @property def id(self) -> str: return self._id @abstractmethod def execute_command(self, command: str) -> str: pass @abstractmethod def read_file(sel...
--- +++ @@ -2,6 +2,7 @@ class Sandbox(ABC): + """Abstract base class for sandbox environments""" _id: str @@ -14,20 +15,58 @@ @abstractmethod def execute_command(self, command: str) -> str: + """Execute bash command in sandbox. + + Args: + command: The command to exec...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/sandbox.py
Document this script properly
import os from pathlib import Path from .parser import parse_skill_file from .types import Skill def get_skills_root_path() -> Path: # loader.py lives at packages/harness/deerflow/skills/loader.py — 5 parents up reaches backend/ backend_dir = Path(__file__).resolve().parent.parent.parent.parent.parent # ...
--- +++ @@ -6,6 +6,12 @@ def get_skills_root_path() -> Path: + """ + Get the root path of the skills directory. + + Returns: + Path to the skills directory (deer-flow/skills) + """ # loader.py lives at packages/harness/deerflow/skills/loader.py — 5 parents up reaches backend/ backend_di...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/skills/loader.py
Generate docstrings for each module
from __future__ import annotations import asyncio import logging import threading from typing import Any from app.channels.base import Channel from app.channels.message_bus import InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment logger = logging.getLogger(__name__) class TelegramChannel(Channel...
--- +++ @@ -1,3 +1,4 @@+"""Telegram channel — connects via long-polling (no public IP needed).""" from __future__ import annotations @@ -13,6 +14,12 @@ class TelegramChannel(Channel): + """Telegram bot channel using long-polling. + + Configuration keys (in ``config.yaml`` under ``channels.telegram``): + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/telegram.py
Add professional docstrings to my codebase
import re from pathlib import Path from langchain.tools import ToolRuntime, tool from langgraph.typing import ContextT from deerflow.agents.thread_state import ThreadDataState, ThreadState from deerflow.config.paths import VIRTUAL_PATH_PREFIX from deerflow.sandbox.exceptions import ( SandboxError, SandboxNotF...
--- +++ @@ -28,6 +28,12 @@ def _get_skills_container_path() -> str: + """Get the skills container path from config, with fallback to default. + + Result is cached after the first successful config load. If config loading + fails the default is returned *without* caching so that a later call can + pick ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/tools.py
Insert docstrings into my code
import logging from pydantic import BaseModel, Field logger = logging.getLogger(__name__) class SubagentOverrideConfig(BaseModel): timeout_seconds: int | None = Field( default=None, ge=1, description="Timeout in seconds for this subagent (None = use global default)", ) class Suba...
--- +++ @@ -1,3 +1,4 @@+"""Configuration for the subagent system loaded from config.yaml.""" import logging @@ -7,6 +8,7 @@ class SubagentOverrideConfig(BaseModel): + """Per-agent configuration overrides.""" timeout_seconds: int | None = Field( default=None, @@ -16,6 +18,7 @@ class Subag...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/subagents_config.py
Create docstrings for all classes and functions
from __future__ import annotations import time from dataclasses import dataclass, field @dataclass class SandboxInfo: sandbox_id: str sandbox_url: str # e.g. http://localhost:8080 or http://k3s:30001 container_name: str | None = None # Only for local container backend container_id: str | None = N...
--- +++ @@ -1,3 +1,4 @@+"""Sandbox metadata for cross-process discovery and state persistence.""" from __future__ import annotations @@ -7,6 +8,12 @@ @dataclass class SandboxInfo: + """Persisted sandbox metadata that enables cross-process discovery. + + This dataclass holds all the information needed to r...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/sandbox_info.py
Write docstrings for utility functions
from langchain.tools import tool from deerflow.config import get_app_config from deerflow.utils.readability import ReadabilityExtractor from .infoquest_client import InfoQuestClient readability_extractor = ReadabilityExtractor() def _get_infoquest_client() -> InfoQuestClient: search_config = get_app_config().g...
--- +++ @@ -34,6 +34,11 @@ @tool("web_search", parse_docstring=True) def web_search_tool(query: str) -> str: + """Search the web. + + Args: + query: The query to search for. + """ client = _get_infoquest_client() return client.web_search(query) @@ -41,9 +46,18 @@ @tool("web_fetch", pars...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/infoquest/tools.py
Add docstrings to meet PEP guidelines
from pydantic import BaseModel, ConfigDict, Field class VolumeMountConfig(BaseModel): host_path: str = Field(..., description="Path on the host machine") container_path: str = Field(..., description="Path inside the container") read_only: bool = Field(default=False, description="Whether the mount is read...
--- +++ @@ -2,6 +2,7 @@ class VolumeMountConfig(BaseModel): + """Configuration for a volume mount.""" host_path: str = Field(..., description="Path on the host machine") container_path: str = Field(..., description="Path inside the container") @@ -9,6 +10,20 @@ class SandboxConfig(BaseModel): + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/sandbox_config.py
Add verbose docstrings with examples
import logging from dataclasses import replace from deerflow.subagents.builtins import BUILTIN_SUBAGENTS from deerflow.subagents.config import SubagentConfig logger = logging.getLogger(__name__) def get_subagent_config(name: str) -> SubagentConfig | None: config = BUILTIN_SUBAGENTS.get(name) if config is N...
--- +++ @@ -1,3 +1,4 @@+"""Subagent registry for managing available subagents.""" import logging from dataclasses import replace @@ -9,6 +10,14 @@ def get_subagent_config(name: str) -> SubagentConfig | None: + """Get a subagent configuration by name, with config.yaml overrides applied. + + Args: + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/subagents/registry.py
Write beginner-friendly docstrings
import json import logging import re from dataclasses import dataclass from langchain.tools import BaseTool from langchain_core.tools import tool from langchain_core.utils.function_calling import convert_to_openai_function logger = logging.getLogger(__name__) MAX_RESULTS = 5 # Max tools returned per search # ── ...
--- +++ @@ -1,3 +1,13 @@+"""Tool search — deferred tool discovery at runtime. + +Contains: +- DeferredToolRegistry: stores deferred tools and handles regex search +- tool_search: the LangChain tool the agent calls to discover deferred tools + +The agent sees deferred tool names in <available-deferred-tools> but cannot ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/tools/builtins/tool_search.py
Generate helpful docstrings for debugging
import asyncio import logging import threading import uuid from concurrent.futures import Future, ThreadPoolExecutor from concurrent.futures import TimeoutError as FuturesTimeoutError from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Any from langchain.agents imp...
--- +++ @@ -1,3 +1,4 @@+"""Subagent execution engine.""" import asyncio import logging @@ -23,6 +24,7 @@ class SubagentStatus(Enum): + """Status of a subagent execution.""" PENDING = "pending" RUNNING = "running" @@ -33,6 +35,18 @@ @dataclass class SubagentResult: + """Result of a subagent ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/subagents/executor.py
Add docstrings to my Python code
import json from firecrawl import FirecrawlApp from langchain.tools import tool from deerflow.config import get_app_config def _get_firecrawl_client() -> FirecrawlApp: config = get_app_config().get_tool_config("web_search") api_key = None if config is not None: api_key = config.model_extra.get("...
--- +++ @@ -16,6 +16,11 @@ @tool("web_search", parse_docstring=True) def web_search_tool(query: str) -> str: + """Search the web. + + Args: + query: The query to search for. + """ try: config = get_app_config().get_tool_config("web_search") max_results = 5 @@ -43,6 +48,15 @@ ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/firecrawl/tools.py
Write docstrings for data processing functions
from pathlib import Path from pydantic import BaseModel, Field class SkillsConfig(BaseModel): path: str | None = Field( default=None, description="Path to skills directory. If not specified, defaults to ../skills relative to backend directory", ) container_path: str = Field( defa...
--- +++ @@ -4,6 +4,7 @@ class SkillsConfig(BaseModel): + """Configuration for skills system""" path: str | None = Field( default=None, @@ -15,6 +16,12 @@ ) def get_skills_path(self) -> Path: + """ + Get the resolved skills directory path. + + Returns: + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/skills_config.py
Add detailed docstrings explaining each function
import os import re from pathlib import Path # Virtual path prefix seen by agents inside the sandbox VIRTUAL_PATH_PREFIX = "/mnt/user-data" _SAFE_THREAD_ID_RE = re.compile(r"^[A-Za-z0-9_\-]+$") class Paths: def __init__(self, base_dir: str | Path | None = None) -> None: self._base_dir = Path(base_dir)....
--- +++ @@ -9,18 +9,53 @@ class Paths: + """ + Centralized path configuration for DeerFlow application data. + + Directory layout (host side): + {base_dir}/ + ├── memory.json + ├── USER.md <-- global user profile (injected into all agents) + ├── agents/ + │ └──...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/paths.py
Add standardized docstrings across the file
import logging from langchain_core.tools import BaseTool from deerflow.config.extensions_config import ExtensionsConfig from deerflow.mcp.client import build_servers_config from deerflow.mcp.oauth import build_oauth_tool_interceptor, get_initial_oauth_headers logger = logging.getLogger(__name__) async def get_mcp...
--- +++ @@ -1,3 +1,4 @@+"""Load MCP tools using langchain-mcp-adapters.""" import logging @@ -11,6 +12,11 @@ async def get_mcp_tools() -> list[BaseTool]: + """Get all tools from enabled MCP servers. + + Returns: + List of LangChain tools from all enabled MCP servers. + """ try: fr...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/mcp/tools.py
Generate NumPy-style docstrings
import socket import threading from contextlib import contextmanager class PortAllocator: def __init__(self): self._lock = threading.Lock() self._reserved_ports: set[int] = set() def _is_port_available(self, port: int) -> bool: if port in self._reserved_ports: return Fal...
--- +++ @@ -1,3 +1,4 @@+"""Thread-safe network utilities.""" import socket import threading @@ -5,12 +6,41 @@ class PortAllocator: + """Thread-safe port allocator that prevents port conflicts in concurrent environments. + + This class maintains a set of reserved ports and uses a lock to ensure that + p...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/utils/network.py
Add detailed docstrings explaining each function
from __future__ import annotations import asyncio import logging from dataclasses import dataclass from datetime import UTC, datetime, timedelta from typing import Any from deerflow.config.extensions_config import ExtensionsConfig, McpOAuthConfig logger = logging.getLogger(__name__) @dataclass class _OAuthToken: ...
--- +++ @@ -1,3 +1,4 @@+"""OAuth token support for MCP HTTP/SSE servers.""" from __future__ import annotations @@ -14,6 +15,7 @@ @dataclass class _OAuthToken: + """Cached OAuth token.""" access_token: str token_type: str @@ -21,6 +23,7 @@ class OAuthTokenManager: + """Acquire/cache/refresh...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/mcp/oauth.py
Add return value explanations in docstrings
from dataclasses import dataclass, field @dataclass class SubagentConfig: name: str description: str system_prompt: str tools: list[str] | None = None disallowed_tools: list[str] | None = field(default_factory=lambda: ["task"]) model: str = "inherit" max_turns: int = 50 timeout_secon...
--- +++ @@ -1,9 +1,22 @@+"""Subagent configuration definitions.""" from dataclasses import dataclass, field @dataclass class SubagentConfig: + """Configuration for a subagent. + + Attributes: + name: Unique identifier for the subagent. + description: When Claude should delegate to this suba...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/subagents/config.py
Add docstrings that explain logic
from typing import Any from langchain_core.language_models import LanguageModelInput from langchain_core.messages import AIMessage from langchain_deepseek import ChatDeepSeek class PatchedChatDeepSeek(ChatDeepSeek): def _get_request_payload( self, input_: LanguageModelInput, *, ...
--- +++ @@ -1,3 +1,11 @@+"""Patched ChatDeepSeek that preserves reasoning_content in multi-turn conversations. + +This module provides a patched version of ChatDeepSeek that properly handles +reasoning_content when sending messages back to the API. The original implementation +stores reasoning_content in additional_kwa...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/models/patched_deepseek.py
Improve documentation using docstrings
import logging from pathlib import Path logger = logging.getLogger(__name__) # File extensions that should be converted to markdown CONVERTIBLE_EXTENSIONS = { ".pdf", ".ppt", ".pptx", ".xls", ".xlsx", ".doc", ".docx", } async def convert_file_to_markdown(file_path: Path) -> Path | None:...
--- +++ @@ -1,3 +1,8 @@+"""File conversion utilities. + +Converts document files (PDF, PPT, Excel, Word) to Markdown using markitdown. +No FastAPI or HTTP dependencies — pure utility functions. +""" import logging from pathlib import Path @@ -17,6 +22,14 @@ async def convert_file_to_markdown(file_path: Path) ->...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/utils/file_conversion.py
Write docstrings that follow conventions
import os import shutil import subprocess from deerflow.sandbox.local.list_dir import list_dir from deerflow.sandbox.sandbox import Sandbox class LocalSandbox(Sandbox): def __init__(self, id: str): super().__init__(id) @staticmethod def _get_shell() -> str: for shell in ("/bin/zsh", "/bi...
--- +++ @@ -8,10 +8,22 @@ class LocalSandbox(Sandbox): def __init__(self, id: str): + """ + Initialize local sandbox. + + Args: + id: Sandbox identifier + """ super().__init__(id) @staticmethod def _get_shell() -> str: + """Detect available shell...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/local/local_sandbox.py
Add concise docstrings to each method
import re from pathlib import Path import yaml # Allowed properties in SKILL.md frontmatter ALLOWED_FRONTMATTER_PROPERTIES = {"name", "description", "license", "allowed-tools", "metadata", "compatibility", "version", "author"} def _validate_skill_frontmatter(skill_dir: Path) -> tuple[bool, str, str | None]: sk...
--- +++ @@ -1,3 +1,7 @@+"""Skill frontmatter validation utilities. + +Pure-logic validation of SKILL.md frontmatter — no FastAPI or HTTP dependencies. +""" import re from pathlib import Path @@ -9,6 +13,14 @@ def _validate_skill_frontmatter(skill_dir: Path) -> tuple[bool, str, str | None]: + """Validate a sk...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/skills/validation.py
Add docstrings with type hints explained
from dataclasses import dataclass from pathlib import Path @dataclass class Skill: name: str description: str license: str | None skill_dir: Path skill_file: Path relative_path: Path # Relative path from category root to skill directory category: str # 'public' or 'custom' enabled: ...
--- +++ @@ -4,6 +4,7 @@ @dataclass class Skill: + """Represents a skill with its metadata and file path""" name: str description: str @@ -16,10 +17,20 @@ @property def skill_path(self) -> str: + """Returns the relative path from the category root (skills/{category}) to this skill's d...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/skills/types.py
Improve my code by adding docstrings
from typing import Literal from pydantic import BaseModel, Field ContextSizeType = Literal["fraction", "tokens", "messages"] class ContextSize(BaseModel): type: ContextSizeType = Field(description="Type of context size specification") value: int | float = Field(description="Value for the context size spec...
--- +++ @@ -1,3 +1,4 @@+"""Configuration for conversation summarization.""" from typing import Literal @@ -7,15 +8,18 @@ class ContextSize(BaseModel): + """Context size specification for trigger or keep parameters.""" type: ContextSizeType = Field(description="Type of context size specification") ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/config/summarization_config.py
Create docstrings for API functions
#!/usr/bin/env python3 from __future__ import annotations import shutil import subprocess import sys from typing import Optional def run_command(command: list[str]) -> Optional[str]: try: result = subprocess.run(command, capture_output=True, text=True, check=True) except (OSError, subprocess.CalledP...
--- +++ @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +"""Cross-platform dependency checker for DeerFlow.""" from __future__ import annotations @@ -9,6 +10,7 @@ def run_command(command: list[str]) -> Optional[str]: + """Run a command and return trimmed stdout, or None on failure.""" try: result = sub...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/scripts/check.py
Add docstrings for utility scripts
#!/usr/bin/env python3 import argparse import json import os import re import shutil import subprocess import sys import textwrap from collections import Counter from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from pathlib import Path from typing import Optional # Optiona...
--- +++ @@ -1,4 +1,34 @@ #!/usr/bin/env python3 +""" +YouTube Design Concept Extractor +================================= +Extracts transcript + keyframes from a YouTube video and produces +a structured markdown reference document ready for agent consumption. + +Usage: + python3 tools/yt-design-extractor.py <youtube...
https://raw.githubusercontent.com/wshobson/agents/HEAD/tools/yt-design-extractor.py
Add docstrings that explain logic
from __future__ import annotations import logging import os import time from contextlib import asynccontextmanager import urllib3 from fastapi import FastAPI, HTTPException from kubernetes import client as k8s_client from kubernetes import config as k8s_config from kubernetes.client.rest import ApiException from pyd...
--- +++ @@ -1,3 +1,31 @@+"""DeerFlow Sandbox Provisioner Service. + +Dynamically creates and manages per-sandbox Pods in Kubernetes. +Each ``sandbox_id`` gets its own Pod + NodePort Service. The backend +accesses sandboxes directly via ``{NODE_HOST}:{NodePort}``. + +The provisioner connects to the host machine's Kuber...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/docker/provisioner/app.py
Please document this code using docstrings
import fnmatch from pathlib import Path IGNORE_PATTERNS = [ # Version Control ".git", ".svn", ".hg", ".bzr", # Dependencies "node_modules", "__pycache__", ".venv", "venv", ".env", "env", ".tox", ".nox", ".eggs", "*.egg-info", "site-packages", # Bu...
--- +++ @@ -62,6 +62,7 @@ def _should_ignore(name: str) -> bool: + """Check if a file/directory name matches any ignore pattern.""" for pattern in IGNORE_PATTERNS: if fnmatch.fnmatch(name, pattern): return True @@ -69,6 +70,18 @@ def list_dir(path: str, max_depth: int = 2) -> list[...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/sandbox/local/list_dir.py
Fully document this Python code with docstrings
from pathlib import Path from typing import Annotated from langchain.tools import InjectedToolCallId, ToolRuntime, tool from langchain_core.messages import ToolMessage from langgraph.types import Command from langgraph.typing import ContextT from deerflow.agents.thread_state import ThreadState from deerflow.config.pa...
--- +++ @@ -16,6 +16,20 @@ runtime: ToolRuntime[ContextT, ThreadState], filepath: str, ) -> str: + """Normalize a presented file path to the `/mnt/user-data/outputs/*` contract. + + Accepts either: + - A virtual sandbox path such as `/mnt/user-data/outputs/report.md` + - A host-side thread outputs...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/tools/builtins/present_file_tool.py
Document my Python code with docstrings
import argparse import base64 import json import logging import os import uuid from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Literal, Optional import requests logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Types class ScriptLine: def __init__(...
--- +++ @@ -39,6 +39,7 @@ def text_to_speech(text: str, voice_type: str) -> Optional[bytes]: + """Convert text to speech using Volcengine TTS.""" app_id = os.getenv("VOLCENGINE_TTS_APPID") access_token = os.getenv("VOLCENGINE_TTS_ACCESS_TOKEN") cluster = os.getenv("VOLCENGINE_TTS_CLUSTER", "volcan...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/skills/public/podcast-generation/scripts/generate.py
Add professional docstrings to my codebase
import logging import time import uuid from dataclasses import replace from typing import Annotated, Literal from langchain.tools import InjectedToolCallId, ToolRuntime, tool from langgraph.config import get_stream_writer from langgraph.typing import ContextT from deerflow.agents.lead_agent.prompt import get_skills_...
--- +++ @@ -1,3 +1,4 @@+"""Task tool for delegating work to subagents.""" import logging import time @@ -26,6 +27,36 @@ tool_call_id: Annotated[str, InjectedToolCallId], max_turns: int | None = None, ) -> str: + """Delegate a task to a specialized subagent that runs in its own context. + + Subagents...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/tools/builtins/task_tool.py
Add docstrings to my Python code
from fastapi import FastAPI, HTTPException, Query, Path, Depends, status from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.trustedhost import TrustedHostMiddleware from fastapi.responses import JSONResponse from pydantic import BaseModel, Field, EmailStr, ConfigDict from typing import Optional...
--- +++ @@ -1,3 +1,7 @@+""" +Production-ready REST API template using FastAPI. +Includes pagination, filtering, error handling, and best practices. +""" from fastapi import FastAPI, HTTPException, Query, Path, Depends, status from fastapi.middleware.cors import CORSMiddleware @@ -98,6 +102,7 @@ status: Optional...
https://raw.githubusercontent.com/wshobson/agents/HEAD/plugins/backend-development/skills/api-design-principles/assets/rest-api-template.py
Add documentation for all methods
import argparse import hashlib import json import logging import os import re import sys import tempfile logging.basicConfig(level=logging.INFO, format="%(message)s") logger = logging.getLogger(__name__) try: import duckdb except ImportError: logger.error("duckdb is not installed. Installing...") os.syst...
--- +++ @@ -1,3 +1,9 @@+""" +Data Analysis Script using DuckDB. + +Analyzes Excel (.xlsx/.xls) and CSV files using DuckDB's in-process SQL engine. +Supports schema inspection, SQL queries, statistical summaries, and result export. +""" import argparse import hashlib @@ -29,6 +35,7 @@ def compute_files_hash(file...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/skills/public/data-analysis/scripts/analyze.py
Add docstrings for better understanding
#!/usr/bin/env python3 import json import sys from typing import Any, Dict, List, Optional try: import requests except ImportError: # Fallback to urllib if requests not available import urllib.error import urllib.request class RequestsFallback: class Response: def __init__(se...
--- +++ @@ -1,4 +1,8 @@ #!/usr/bin/env python3 +""" +GitHub API client for deep research. +Uses requests for HTTP operations. +""" import json import sys @@ -12,6 +16,7 @@ import urllib.request class RequestsFallback: + """Minimal requests-like interface using urllib.""" class Response:...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/skills/public/github-deep-research/scripts/github_api.py
Add missing documentation to my Python functions
#!/usr/bin/env python3 import argparse import json import math import sys from datetime import datetime, timezone from pathlib import Path def calculate_stats(values: list[float]) -> dict: if not values: return {"mean": 0.0, "stddev": 0.0, "min": 0.0, "max": 0.0} n = len(values) mean = sum(value...
--- +++ @@ -1,4 +1,38 @@ #!/usr/bin/env python3 +""" +Aggregate individual run results into benchmark summary statistics. + +Reads grading.json files from run directories and produces: +- run_summary with mean, stddev, min, max for each metric +- delta between with_skill and without_skill configurations + +Usage: + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/skills/public/skill-creator/scripts/aggregate_benchmark.py
Document functions with clear intent
#!/usr/bin/env python3 import json import time from typing import List, Dict, Any from dataclasses import dataclass from concurrent.futures import ThreadPoolExecutor import numpy as np @dataclass class TestCase: input: Dict[str, Any] expected_output: str metadata: Dict[str, Any] = None class PromptOpti...
--- +++ @@ -1,4 +1,9 @@ #!/usr/bin/env python3 +""" +Prompt Optimization Script + +Automatically test and optimize prompts using A/B testing and metrics tracking. +""" import json import time @@ -23,9 +28,11 @@ self.executor = ThreadPoolExecutor() def shutdown(self): + """Shutdown the thread p...
https://raw.githubusercontent.com/wshobson/agents/HEAD/plugins/llm-application-dev/skills/prompt-engineering-patterns/scripts/optimize-prompt.py
Generate docstrings for each module
from __future__ import print_function, division import math import numpy as np import copy from mlfromscratch.deep_learning.activation_functions import Sigmoid, ReLU, SoftPlus, LeakyReLU from mlfromscratch.deep_learning.activation_functions import TanH, ELU, SELU, Softmax class Layer(object): def set_input_shap...
--- +++ @@ -10,25 +10,45 @@ class Layer(object): def set_input_shape(self, shape): + """ Sets the shape that the layer expects of the input in the forward + pass method """ self.input_shape = shape def layer_name(self): + """ The name of the layer. Used in model summary. """ ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/deep_learning/layers.py
Add docstrings for production code
from __future__ import division, print_function import numpy as np import math from mlfromscratch.utils import train_test_split, normalize from mlfromscratch.utils import Plot, accuracy_score class NaiveBayes(): def fit(self, X, y): self.X, self.y = X, y self.classes = np.unique(y) self.par...
--- +++ @@ -5,6 +5,7 @@ from mlfromscratch.utils import Plot, accuracy_score class NaiveBayes(): + """The Gaussian Naive Bayes classifier. """ def fit(self, X, y): self.X, self.y = X, y self.classes = np.unique(y) @@ -20,16 +21,33 @@ self.parameters[i].append(parameters) ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/naive_bayes.py
Include argument descriptions in docstrings
from __future__ import print_function, division import numpy as np from mlfromscratch.utils import euclidean_distance class KNN(): def __init__(self, k=5): self.k = k def _vote(self, neighbor_labels): counts = np.bincount(neighbor_labels.astype('int')) return counts.argmax() def p...
--- +++ @@ -3,10 +3,19 @@ from mlfromscratch.utils import euclidean_distance class KNN(): + """ K Nearest Neighbors classifier. + + Parameters: + ----------- + k: int + The number of closest neighbors that will determine the class of the + sample that we wish to predict. + """ def ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/k_nearest_neighbors.py
Add concise docstrings to each method
from __future__ import print_function, division import matplotlib.pyplot as plt import numpy as np from mlfromscratch.utils import calculate_covariance_matrix, normalize, standardize class MultiClassLDA(): def __init__(self, solver="svd"): self.solver = solver def _calculate_scatter_matrices(self, X,...
--- +++ @@ -5,6 +5,17 @@ class MultiClassLDA(): + """Enables dimensionality reduction for multiple + class distributions. It transforms the features space into a space where + the between class scatter is maximized and the within class scatter is + minimized. + + Parameters: + ----------- + sol...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/multi_class_lda.py
Improve my code by adding docstrings
from __future__ import print_function, division import numpy as np import copy class Neuroevolution(): def __init__(self, population_size, mutation_rate, model_builder): self.population_size = population_size self.mutation_rate = mutation_rate self.model_builder = model_builder def _bu...
--- +++ @@ -3,12 +3,24 @@ import copy class Neuroevolution(): + """ Evolutionary optimization of Neural Networks. + + Parameters: + ----------- + n_individuals: int + The number of neural networks that are allowed in the population at a time. + mutation_rate: float + The probability that...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/neuroevolution.py
Add standardized docstrings across the file
from __future__ import print_function, division import numpy as np import copy class ParticleSwarmOptimizedNN(): def __init__(self, population_size, model_builder, inertia_weight=0.8, cognitive_weight=2, social_weig...
--- +++ @@ -3,6 +3,24 @@ import copy class ParticleSwarmOptimizedNN(): + """ Particle Swarm Optimization of Neural Network. + + Parameters: + ----------- + n_individuals: int + The number of neural networks that are allowed in the population at a time. + model_builder: method + A method ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/particle_swarm_optimization.py
Please document this code using docstrings
from __future__ import division, print_function import numpy as np from mlfromscratch.utils import divide_on_feature, train_test_split, standardize, mean_squared_error from mlfromscratch.utils import calculate_entropy, accuracy_score, calculate_variance class DecisionNode(): def __init__(self, feature_i=None, thr...
--- +++ @@ -5,6 +5,22 @@ from mlfromscratch.utils import calculate_entropy, accuracy_score, calculate_variance class DecisionNode(): + """Class that represents a decision node or leaf in the decision tree + + Parameters: + ----------- + feature_i: int + Feature index which we want to use as the th...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/decision_tree.py
Create structured documentation for my script
from __future__ import print_function, division import numpy as np import math from mlfromscratch.utils import normalize, polynomial_features class l1_regularization(): def __init__(self, alpha): self.alpha = alpha def __call__(self, w): return self.alpha * np.linalg.norm(w) def grad(...
--- +++ @@ -4,6 +4,7 @@ from mlfromscratch.utils import normalize, polynomial_features class l1_regularization(): + """ Regularization for Lasso Regression """ def __init__(self, alpha): self.alpha = alpha @@ -14,6 +15,7 @@ return self.alpha * np.sign(w) class l2_regularization(): +...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/supervised_learning/regression.py
Document helper functions with docstrings
from __future__ import division, print_function import numpy as np import itertools class FPTreeNode(): def __init__(self, item=None, support=1): # 'Value' of the item self.item = item # Number of times the item occurs in a # transaction self.support = support # Chi...
--- +++ @@ -15,6 +15,17 @@ class FPGrowth(): + """A method for determining frequent itemsets in a transactional database. + This is done by building a so called FP Growth tree, which can then be mined + to collect the frequent itemsets. More effective than Apriori for large transactional + databases. +...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/fp_growth.py
Document this script properly
from __future__ import print_function, division import numpy as np from mlfromscratch.utils import Plot, euclidean_distance, normalize class DBSCAN(): def __init__(self, eps=1, min_samples=5): self.eps = eps self.min_samples = min_samples def _get_neighbors(self, sample_i): neighbors ...
--- +++ @@ -4,11 +4,25 @@ class DBSCAN(): + """A density based clustering method that expands clusters from + samples that have more neighbors within a radius specified by eps + than the value min_samples. + + Parameters: + ----------- + eps: float + The radius within which samples are con...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/dbscan.py
Write docstrings for backend logic
from __future__ import division, print_function import math from sklearn import datasets import numpy as np from mlfromscratch.utils import normalize, euclidean_distance, calculate_covariance_matrix from mlfromscratch.utils import Plot class GaussianMixtureModel(): def __init__(self, k=2, max_iterations=2000, to...
--- +++ @@ -8,6 +8,19 @@ class GaussianMixtureModel(): + """A probabilistic clustering method for determining groupings among data samples. + + Parameters: + ----------- + k: int + The number of clusters the algorithm will form. + max_iterations: int + The number of iterations the algor...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/gaussian_mixture_model.py
Add docstrings for production code
from __future__ import print_function, division import numpy as np from mlfromscratch.utils import normalize, euclidean_distance, Plot from mlfromscratch.unsupervised_learning import PCA class PAM(): def __init__(self, k=2): self.k = k def _init_random_medoids(self, X): n_samples, n_features ...
--- +++ @@ -5,10 +5,22 @@ class PAM(): + """A simple clustering method that forms k clusters by first assigning + samples to the closest medoids, and then swapping medoids with non-medoid + samples if the total distance (cost) between the cluster members and their medoid + is smaller than prevoisly. + +...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/partitioning_around_medoids.py
Add docstrings that explain purpose and usage
from __future__ import division, print_function import numpy as np import itertools class Rule(): def __init__(self, antecedent, concequent, confidence, support): self.antecedent = antecedent self.concequent = concequent self.confidence = confidence self.support = support class A...
--- +++ @@ -12,6 +12,18 @@ class Apriori(): + """A method for determining frequent itemsets in a transactional database and + also for generating rules for those itemsets. + + Parameters: + ----------- + min_sup: float + The minimum fraction of transactions an itemets needs to + occur ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/apriori.py
Document this code for team use
from __future__ import print_function, division import numpy as np from mlfromscratch.utils import calculate_covariance_matrix class PCA(): def transform(self, X, n_components): covariance_matrix = calculate_covariance_matrix(X) # Where (eigenvector[:,0] corresponds to eigenvalue[0]) eige...
--- +++ @@ -4,7 +4,14 @@ class PCA(): + """A method for doing dimensionality reduction by transforming the feature + space to a lower dimensionality, removing correlation between features and + maximizing the variance along each feature axis. This class is also used throughout + the project to plot data...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/principal_component_analysis.py
Generate consistent docstrings
from __future__ import print_function, division import numpy as np from mlfromscratch.utils import normalize, euclidean_distance, Plot from mlfromscratch.unsupervised_learning import * class KMeans(): def __init__(self, k=2, max_iterations=500): self.k = k self.max_iterations = max_iterations ...
--- +++ @@ -4,11 +4,25 @@ from mlfromscratch.unsupervised_learning import * class KMeans(): + """A simple clustering method that forms k clusters by iteratively reassigning + samples to the closest centroids and after that moves the centroids to the center + of the new formed clusters. + + + Parameters: ...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/k_means.py
Write docstrings for data processing functions
import logging import numpy as np import progressbar from mlfromscratch.utils.misc import bar_widgets from mlfromscratch.utils import batch_iterator from mlfromscratch.deep_learning.activation_functions import Sigmoid sigmoid = Sigmoid() class RBM(): def __init__(self, n_hidden=128, learning_rate=0.1, batch_size...
--- +++ @@ -9,6 +9,23 @@ sigmoid = Sigmoid() class RBM(): + """Bernoulli Restricted Boltzmann Machine (RBM) + + Parameters: + ----------- + n_hidden: int: + The number of processing nodes (neurons) in the hidden layer. + learning_rate: float + The step length that will be used when upda...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/restricted_boltzmann_machine.py
Add docstrings to clarify complex logic
import sys from pathlib import Path from textwrap import dedent sys.path.insert(0, str(Path(__file__).parent.parent)) import tqdm # NOQA import tqdm.cli # NOQA HEAD_ARGS = """ Parameters ---------- """ HEAD_RETS = """ Returns ------- """ HEAD_CLI = """ Extra CLI Options ----------------- name : type, optional ...
--- +++ @@ -1,3 +1,6 @@+""" +Auto-generate README.rst from .meta/.readme.rst and docstrings. +""" import sys from pathlib import Path from textwrap import dedent @@ -23,6 +26,10 @@ def doc2rst(doc, arglist=True, raw=False): + """ + arglist : bool, whether to create argument lists + raw : bool, ignores...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/.meta/mkdocs.py
Fully document this Python code with docstrings
from __future__ import division from itertools import combinations_with_replacement import numpy as np import math import sys def shuffle_data(X, y, seed=None): if seed: np.random.seed(seed) idx = np.arange(X.shape[0]) np.random.shuffle(idx) return X[idx], y[idx] def batch_iterator(X, y=None...
--- +++ @@ -6,6 +6,7 @@ def shuffle_data(X, y, seed=None): + """ Random shuffle of the samples in X and y """ if seed: np.random.seed(seed) idx = np.arange(X.shape[0]) @@ -14,6 +15,7 @@ def batch_iterator(X, y=None, batch_size=64): + """ Simple batch generator """ n_samples = X.sha...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/utils/data_manipulation.py
Write docstrings for this repository
from ._monitor import TMonitor, TqdmSynchronisationWarning from ._tqdm_pandas import tqdm_pandas from .cli import main # TODO: remove in v5.0.0 from .gui import tqdm as tqdm_gui # TODO: remove in v5.0.0 from .gui import trange as tgrange # TODO: remove in v5.0.0 from .std import ( TqdmDeprecationWarning, TqdmExp...
--- +++ @@ -18,6 +18,7 @@ def tqdm_notebook(*args, **kwargs): # pragma: no cover + """See tqdm.notebook.tqdm for full documentation""" from warnings import warn from .notebook import tqdm as _tqdm_notebook @@ -28,9 +29,10 @@ def tnrange(*args, **kwargs): # pragma: no cover + """Shortcut for ...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/__init__.py
Write documentation strings for class attributes
import warnings from .std import TqdmExperimentalWarning with warnings.catch_warnings(): warnings.simplefilter("ignore", category=TqdmExperimentalWarning) from .autonotebook import tqdm as notebook_tqdm from .asyncio import tqdm as asyncio_tqdm from .std import tqdm as std_tqdm if notebook_tqdm != std_tqdm:...
--- +++ @@ -1,3 +1,17 @@+""" +Enables multiple commonly used features. + +Method resolution order: + +- `tqdm.autonotebook` without import warnings +- `tqdm.asyncio` +- `tqdm.std` base class + +Usage: +>>> from tqdm.auto import trange, tqdm +>>> for i in trange(10): +... ... +""" import warnings from .std impor...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/auto.py
Document functions with clear intent
import asyncio from sys import version_info from .std import tqdm as std_tqdm __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_asyncio', 'tarange', 'tqdm', 'trange'] class tqdm_asyncio(std_tqdm): def __init__(self, iterable=None, *args, **kwargs): super().__init__(iterable, *args, **kwargs) ...
--- +++ @@ -1,3 +1,12 @@+""" +Asynchronous progressbar decorator for iterators. +Includes a default `range` iterator printing to `stderr`. + +Usage: +>>> from tqdm.asyncio import trange, tqdm +>>> async for i in trange(10): +... ... +""" import asyncio from sys import version_info @@ -8,6 +17,9 @@ class tqd...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/asyncio.py
Write Python docstrings for this snippet
from __future__ import division import numpy as np import math import sys def calculate_entropy(y): log2 = lambda x: math.log(x) / math.log(2) unique_labels = np.unique(y) entropy = 0 for label in unique_labels: count = len(y[y == label]) p = count / len(y) entropy += -p * log2...
--- +++ @@ -5,6 +5,7 @@ def calculate_entropy(y): + """ Calculate the entropy of label array y """ log2 = lambda x: math.log(x) / math.log(2) unique_labels = np.unique(y) entropy = 0 @@ -16,11 +17,13 @@ def mean_squared_error(y_true, y_pred): + """ Returns the mean squared error between y_t...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/utils/data_operation.py
Help me add docstrings to my project
from __future__ import print_function, division import string import numpy as np class GeneticAlgorithm(): def __init__(self, target_string, population_size, mutation_rate): self.target = target_string self.population_size = population_size self.mutation_rate = mutation_rate self.le...
--- +++ @@ -3,6 +3,19 @@ import numpy as np class GeneticAlgorithm(): + """An implementation of a Genetic Algorithm which will try to produce the user + specified target string. + + Parameters: + ----------- + target_string: string + The string which the GA should try to produce. + populatio...
https://raw.githubusercontent.com/eriklindernoren/ML-From-Scratch/HEAD/mlfromscratch/unsupervised_learning/genetic_algorithm.py
Write docstrings for this repository
from os import getenv from warnings import warn from requests import Session from requests.utils import default_user_agent from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..version import __version__ from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl", "guigoruiz1"]...
--- +++ @@ -1,3 +1,13 @@+""" +Sends updates to a Discord bot. + +Usage: +>>> from tqdm.contrib.discord import tqdm, trange +>>> for i in trange(10, token='{token}', channel_id='{channel_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-discord.png) +""" from os import getenv from warnings imp...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/discord.py
Write docstrings for utility functions
from contextlib import contextmanager from operator import length_hint from os import cpu_count from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning __author__ = {"github.com/": ["casperdcl"]} __all__ = ['thread_map', 'process_map'] @contextmanager def ensure_lock(tqdm_class, lock_name=""): old_lo...
--- +++ @@ -1,3 +1,6 @@+""" +Thin wrappers around `concurrent.futures`. +""" from contextlib import contextmanager from operator import length_hint from os import cpu_count @@ -11,6 +14,7 @@ @contextmanager def ensure_lock(tqdm_class, lock_name=""): + """get (create if necessary) and then restore `tqdm_class`'...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/concurrent.py
Write docstrings describing functionality
import logging import re import sys from ast import literal_eval as numeric from textwrap import indent from .std import TqdmKeyError, TqdmTypeError, tqdm from .version import __version__ __all__ = ["main"] log = logging.getLogger(__name__) def cast(val, typ): log.debug((val, typ)) if " or " in typ: ...
--- +++ @@ -1,3 +1,6 @@+""" +Module version for monitoring CLI pipes (`... | python -m tqdm | ...`). +""" import logging import re import sys @@ -51,6 +54,15 @@ def posix_pipe(fin, fout, delim=b'\\n', buf_size=256, callback=lambda float: None, callback_len=True): + """ + Params + ------ + ...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/cli.py
Create structured documentation for my script
import itertools from ..auto import tqdm as tqdm_auto __author__ = {"github.com/": ["casperdcl"]} __all__ = ['product'] def product(*iterables, **tqdm_kwargs): kwargs = tqdm_kwargs.copy() tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) try: lens = list(map(len, iterables)) except TypeError:...
--- +++ @@ -1,3 +1,6 @@+""" +Thin wrappers around `itertools`. +""" import itertools from ..auto import tqdm as tqdm_auto @@ -7,6 +10,13 @@ def product(*iterables, **tqdm_kwargs): + """ + Equivalent of `itertools.product`. + + Parameters + ---------- + tqdm_class : [default: tqdm.auto.tqdm]. + ...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/itertools.py
Add minimal docstrings for each function
import logging from os import getenv try: from slack_sdk import WebClient except ImportError: raise ImportError("Please `pip install slack-sdk`") from ..auto import tqdm as tqdm_auto from .utils_worker import MonoWorker __author__ = {"github.com/": ["0x2b3bfa0", "casperdcl"]} __all__ = ['SlackIO', 'tqdm_slac...
--- +++ @@ -1,3 +1,13 @@+""" +Sends updates to a Slack app. + +Usage: +>>> from tqdm.contrib.slack import tqdm, trange +>>> for i in trange(10, token='{token}', channel='{channel}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-slack.png) +""" import logging from os import getenv @@ -14,7 +24...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/slack.py
Insert docstrings into my code
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange'] class TelegramIO(M...
--- +++ @@ -1,3 +1,13 @@+""" +Sends updates to a Telegram bot. + +Usage: +>>> from tqdm.contrib.telegram import tqdm, trange +>>> for i in trange(10, token='{token}', chat_id='{chat_id}'): +... ... + +![screenshot](https://tqdm.github.io/img/screenshot-telegram.gif) +""" from os import getenv from warnings import...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/telegram.py
Turn comments into proper docstrings
from collections import deque from concurrent.futures import ThreadPoolExecutor from ..auto import tqdm as tqdm_auto __author__ = {"github.com/": ["casperdcl"]} __all__ = ['MonoWorker'] class MonoWorker: def __init__(self): self.pool = ThreadPoolExecutor(max_workers=1) self.futures = deque([], 2...
--- +++ @@ -1,3 +1,6 @@+""" +IO/concurrency helpers for `tqdm.contrib`. +""" from collections import deque from concurrent.futures import ThreadPoolExecutor @@ -8,11 +11,16 @@ class MonoWorker: + """ + Supports one running task and one waiting task. + The waiting task is the most recent submitted (othe...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/utils_worker.py
Generate consistent docstrings
import logging import sys from contextlib import contextmanager try: from typing import Iterator, List, Optional, Type # noqa: F401 except ImportError: pass from ..std import tqdm as std_tqdm class _TqdmLoggingHandler(logging.StreamHandler): def __init__( self, tqdm_class=std_tqdm # ty...
--- +++ @@ -1,3 +1,6 @@+""" +Helper functionality for interoperability with stdlib `logging`. +""" import logging import sys from contextlib import contextmanager @@ -46,6 +49,34 @@ tqdm_class=std_tqdm # type: Type[std_tqdm] ): # type: (...) -> Iterator[None] + """ + Context manager redirecting cons...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/logging.py
Add docstrings that explain purpose and usage
from warnings import warn from ..auto import tqdm as tqdm_auto from ..std import TqdmDeprecationWarning, tqdm from ..utils import ObjectWrapper __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tenumerate', 'tzip', 'tmap'] class DummyTqdmFile(ObjectWrapper): def __init__(self, wrapped): super()._...
--- +++ @@ -1,3 +1,8 @@+""" +Thin wrappers around common functions. + +Subpackages contain potentially unstable extensions. +""" from warnings import warn from ..auto import tqdm as tqdm_auto @@ -9,6 +14,7 @@ class DummyTqdmFile(ObjectWrapper): + """Dummy file-like that will write to tqdm""" def __ini...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/contrib/__init__.py
Add docstrings to existing functions
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich', 'trrange', 'tqdm', 'tra...
--- +++ @@ -1,3 +1,11 @@+""" +`rich.progress` decorator for iterators. + +Usage: +>>> from tqdm.rich import trange, tqdm +>>> for i in trange(10): +... ... +""" from warnings import warn from rich.progress import ( @@ -11,12 +19,14 @@ class FractionColumn(ProgressColumn): + """Renders completed/total, e....
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/rich.py
Add missing documentation to my Python functions
# future division is important to divide integers and get as # a result precise floating numbers (instead of truncated int) import re from warnings import warn # to inherit from the tqdm class from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm # import compatibility functions and utilities __...
--- +++ @@ -1,3 +1,11 @@+""" +Matplotlib GUI progressbar decorator for iterators. + +Usage: +>>> from tqdm.gui import trange, tqdm +>>> for i in trange(10): +... ... +""" # future division is important to divide integers and get as # a result precise floating numbers (instead of truncated int) import re @@ -14,6...
https://raw.githubusercontent.com/tqdm/tqdm/HEAD/tqdm/gui.py