instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Help me write clear docstrings |
import logging
import os
import pathlib
import shutil
import threading
from typing import cast
from overrides import override
from solidlsp.ls import SolidLanguageServer
from solidlsp.ls_config import LanguageServerConfig
from solidlsp.ls_utils import PlatformId, PlatformUtils
from solidlsp.lsp_protocol_handler.lsp_... | --- +++ @@ -1,3 +1,8 @@+"""
+Language Server implementation for TypeScript/JavaScript using https://github.com/yioneko/vtsls,
+which provides TypeScript language server functionality via VSCode's TypeScript extension
+(contrary to typescript-language-server, which uses the TypeScript compiler directly).
+"""
import ... | https://raw.githubusercontent.com/oraios/serena/HEAD/src/solidlsp/language_servers/vts_language_server.py |
Generate consistent docstrings |
import gzip
import logging
import os
import platform
import shutil
import subprocess
import uuid
import zipfile
from enum import Enum
from pathlib import Path, PurePath
import charset_normalizer
import requests
from solidlsp.ls_exceptions import SolidLSPException
from solidlsp.ls_types import UnifiedSymbolInformatio... | --- +++ @@ -1,3 +1,6 @@+"""
+This file contains various utility functions like I/O operations, handling paths, etc.
+"""
import gzip
import logging
@@ -24,9 +27,15 @@
class TextUtils:
+ """
+ Utilities for text operations.
+ """
@staticmethod
def get_line_col_from_index(text: str, index: in... | https://raw.githubusercontent.com/oraios/serena/HEAD/src/solidlsp/ls_utils.py |
Generate docstrings for script automation |
import logging
import os
import pathlib
import shutil
import threading
from pathlib import Path
from time import sleep
from typing import Any
from overrides import override
from solidlsp import ls_types
from solidlsp.language_servers.common import RuntimeDependency, RuntimeDependencyCollection
from solidlsp.language... | --- +++ @@ -1,3 +1,7 @@+"""
+Vue Language Server implementation using @vue/language-server (Volar) with companion TypeScript LS.
+Operates in hybrid mode: Vue LS handles .vue files, TypeScript LS handles .ts/.js files.
+"""
import logging
import os
@@ -30,10 +34,17 @@
class VueTypeScriptServer(TypeScriptLanguag... | https://raw.githubusercontent.com/oraios/serena/HEAD/src/solidlsp/language_servers/vue_language_server.py |
Add standardized docstrings across the file |
from __future__ import annotations
from enum import Enum, IntEnum
from typing import TYPE_CHECKING, NotRequired, Union
from typing_extensions import TypedDict
from solidlsp.lsp_protocol_handler.lsp_types import DiagnosticSeverity
if TYPE_CHECKING:
from .ls import SymbolBody
URI = str
DocumentUri = str
Uint =... | --- +++ @@ -1,3 +1,6 @@+"""
+Defines wrapper objects around the types returned by LSP to ensure decoupling between LSP versions and SolidLSP
+"""
from __future__ import annotations
@@ -19,6 +22,34 @@
class Position(TypedDict):
+ r"""Position in a text document expressed as zero-based line and character
+ ... | https://raw.githubusercontent.com/oraios/serena/HEAD/src/solidlsp/ls_types.py |
Add clean documentation to messy code |
from pathlib import Path
from typing import Any, Dict
class ConfidenceChecker:
def assess(self, context: Dict[str, Any]) -> float:
score = 0.0
checks = []
# Check 1: No duplicate implementations (25%)
if self._no_duplicates(context):
score += 0.25
checks.... | --- +++ @@ -1,11 +1,61 @@+"""
+Pre-implementation Confidence Check
+
+Prevents wrong-direction execution by assessing confidence BEFORE starting.
+
+Token Budget: 100-200 tokens
+ROI: 25-250x token savings when stopping wrong direction
+
+Confidence Levels:
+ - High (≥90%): Root cause identified, solution verified, ... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/pm_agent/confidence.py |
Expand my code with proper documentation strings |
import sys
from pathlib import Path
import click
# Add parent directory to path to import superclaude
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from superclaude import __version__
@click.group()
@click.version_option(version=__version__, prog_name="SuperClaude")
def main():
pass
@main.com... | --- +++ @@ -1,3 +1,8 @@+"""
+SuperClaude CLI Main Entry Point
+
+Provides command-line interface for SuperClaude operations.
+"""
import sys
from pathlib import Path
@@ -13,6 +18,11 @@ @click.group()
@click.version_option(version=__version__, prog_name="SuperClaude")
def main():
+ """
+ SuperClaude - AI-enh... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/cli/main.py |
Add docstrings following best practices |
import shutil
from pathlib import Path
from typing import List, Optional, Tuple
def install_skill_command(
skill_name: str, target_path: Path, force: bool = False
) -> Tuple[bool, str]:
# Get skill source directory
skill_source = _get_skill_source(skill_name)
if not skill_source:
return Fals... | --- +++ @@ -1,3 +1,8 @@+"""
+Skill Installation Command
+
+Installs SuperClaude skills to ~/.claude/skills/ directory.
+"""
import shutil
from pathlib import Path
@@ -7,6 +12,17 @@ def install_skill_command(
skill_name: str, target_path: Path, force: bool = False
) -> Tuple[bool, str]:
+ """
+ Install a... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/cli/install_skill.py |
Add detailed docstrings explaining each function | #!/usr/bin/env python3
import re
import sys
from pathlib import Path
from typing import Tuple
def find_project_root() -> Path:
script_dir = Path(__file__).parent.absolute()
current_dir = script_dir.parent
# Look for plugin.json up to 3 levels up
for _ in range(3):
if (current_dir / "plugin.j... | --- +++ @@ -1,4 +1,18 @@ #!/usr/bin/env python3
+"""
+SuperClaude Plugin - Command Name Attribute Cleanup Script
+
+This script automatically removes redundant 'name:' attributes from command
+frontmatter in markdown files. The plugin naming system derives command names
+from the plugin name + filename, making explicit... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/plugins/superclaude/scripts/clean_command_names.py |
Add docstrings to clarify complex logic |
import json
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional
class ReflexionPattern:
def __init__(self, memory_dir: Optional[Path] = None):
if memory_dir is None:
# Default to docs/memory/ in current working directory
memory_dir = Path... | --- +++ @@ -1,3 +1,27 @@+"""
+Reflexion Error Learning Pattern
+
+Learn from past errors to prevent recurrence.
+
+Token Budget:
+ - Cache hit: 0 tokens (known error → instant solution)
+ - Cache miss: 1-2K tokens (new investigation)
+
+Performance:
+ - Error recurrence rate: <10%
+ - Solution reuse rate: >... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/pm_agent/reflexion.py |
Add docstrings following best practices | #!/usr/bin/env python3
import re
import sys
from pathlib import Path
from typing import Tuple
def find_project_root() -> Path:
script_dir = Path(__file__).parent.absolute()
current_dir = script_dir.parent
# Look for plugin.json up to 3 levels up
for _ in range(3):
if (current_dir / "plugin.j... | --- +++ @@ -1,4 +1,18 @@ #!/usr/bin/env python3
+"""
+SuperClaude Plugin - Command Name Attribute Cleanup Script
+
+This script automatically removes redundant 'name:' attributes from command
+frontmatter in markdown files. The plugin naming system derives command names
+from the plugin name + filename, making explicit... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/scripts/clean_command_names.py |
Document classes and their methods |
import shutil
from pathlib import Path
from typing import List, Tuple
def install_commands(target_path: Path = None, force: bool = False) -> Tuple[bool, str]:
# Default to ~/.claude/commands/sc to maintain /sc: namespace
if target_path is None:
target_path = Path.home() / ".claude" / "commands" / "sc... | --- +++ @@ -1,3 +1,8 @@+"""
+Command Installation
+
+Installs SuperClaude slash commands to ~/.claude/commands/sc/ directory.
+"""
import shutil
from pathlib import Path
@@ -5,6 +10,16 @@
def install_commands(target_path: Path = None, force: bool = False) -> Tuple[bool, str]:
+ """
+ Install all SuperClau... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/cli/install_commands.py |
Document this script properly | #!/usr/bin/env python3
import argparse
import json
import statistics
from collections import defaultdict
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List
class WorkflowMetricsAnalyzer:
def __init__(self, metrics_file: Path):
self.metrics_file = metrics_file... | --- +++ @@ -1,4 +1,14 @@ #!/usr/bin/env python3
+"""
+Workflow Metrics Analysis Script
+
+Analyzes workflow_metrics.jsonl for continuous optimization and A/B testing.
+
+Usage:
+ python scripts/analyze_workflow_metrics.py --period week
+ python scripts/analyze_workflow_metrics.py --period month
+ python script... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/scripts/analyze_workflow_metrics.py |
Write beginner-friendly docstrings |
import hashlib
import json
from dataclasses import asdict, dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
@dataclass
class RootCause:
category: str # e.g., "validation", "dependency", "logic", "assumption"
description: str
evidence: List[st... | --- +++ @@ -1,3 +1,16 @@+"""
+Self-Correction Engine - Learn from Mistakes
+
+Detects failures, analyzes root causes, and prevents recurrence
+through Reflexion-based learning.
+
+Key features:
+- Automatic failure detection
+- Root cause analysis
+- Pattern recognition across failures
+- Prevention rule generation
+- ... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/execution/self_correction.py |
Provide clean and structured docstrings |
from pathlib import Path
from typing import Any, Dict
def run_doctor(verbose: bool = False) -> Dict[str, Any]:
checks = []
# Check 1: pytest plugin loaded
plugin_check = _check_pytest_plugin()
checks.append(plugin_check)
# Check 2: Skills installed
skills_check = _check_skills_installed()
... | --- +++ @@ -1,9 +1,23 @@+"""
+SuperClaude Doctor Command
+
+Health check for SuperClaude installation.
+"""
from pathlib import Path
from typing import Any, Dict
def run_doctor(verbose: bool = False) -> Dict[str, Any]:
+ """
+ Run SuperClaude health checks
+
+ Args:
+ verbose: Include detailed ... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/cli/doctor.py |
Add docstrings for utility scripts |
import json
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
@dataclass
class ReflectionResult:
stage: str
score: float # 0.0 - 1.0
evidence: List[str]
concerns: List[str]
def __repr__(self) -> str:
em... | --- +++ @@ -1,3 +1,13 @@+"""
+Reflection Engine - 3-Stage Pre-Execution Confidence Check
+
+Implements the "Triple Reflection" pattern:
+1. Requirement clarity analysis
+2. Past mistake pattern detection
+3. Context sufficiency validation
+
+Only proceeds with execution if confidence >70%.
+"""
import json
from dat... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/execution/reflection.py |
Write docstrings describing each step | #!/usr/bin/env python3
import sys
import argparse
import tempfile
import shutil
import hashlib
from pathlib import Path
from typing import Dict, List, Tuple, Optional
import json
import re
import subprocess
from dataclasses import dataclass, asdict
from datetime import datetime
import logging
# Configure logging
logg... | --- +++ @@ -1,4 +1,21 @@ #!/usr/bin/env python3
+"""
+SuperClaude Framework Sync Script
+Automated pull-sync with namespace isolation for Plugin distribution
+
+This script synchronizes content from SuperClaude_Framework repository and
+transforms it for distribution as a Claude Code plugin with proper namespace
+isola... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/scripts/sync_from_framework.py |
Add return value explanations in docstrings |
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional
from .parallel import ExecutionPlan, ParallelExecutor, Task, should_parallelize
from .reflection import ConfidenceScore, ReflectionEngine, reflect_before_execution
from .self_correction import RootCause, SelfCorrectionEngine, learn_from_f... | --- +++ @@ -1,3 +1,20 @@+"""
+SuperClaude Execution Engine
+
+Integrates three execution engines:
+1. Reflection Engine: Think × 3 before execution
+2. Parallel Engine: Execute at maximum speed
+3. Self-Correction Engine: Learn from mistakes
+
+Usage:
+ from superclaude.execution import intelligent_execute
+
+ re... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/execution/__init__.py |
Write docstrings for data processing functions |
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, List, Optional, Set
class TaskStatus(Enum):
PENDING = "pending"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
... | --- +++ @@ -1,3 +1,15 @@+"""
+Parallel Execution Engine - Automatic Parallelization
+
+Analyzes task dependencies and executes independent operations
+concurrently for maximum speed.
+
+Key features:
+- Dependency graph construction
+- Automatic parallel group detection
+- Concurrent execution with ThreadPoolExecutor
+... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/execution/parallel.py |
Generate docstrings with examples |
import os
import platform
import shlex
import subprocess
from typing import Dict, List, Optional, Tuple
import click
# AIRIS MCP Gateway - Unified MCP solution (recommended)
AIRIS_GATEWAY = {
"name": "airis-mcp-gateway",
"description": "Unified MCP gateway with 60+ tools, HOT/COLD management, 98% token reduc... | --- +++ @@ -1,3 +1,9 @@+"""
+MCP Server Installation Module for SuperClaude
+
+Installs and manages MCP servers using the latest Claude Code API.
+Based on the installer logic from commit d4a17fc but adapted for modern Claude Code.
+"""
import os
import platform
@@ -87,6 +93,16 @@
def _run_command(cmd: List[str... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/cli/install_mcp.py |
Can you add docstrings to this Python file? |
from typing import Literal
ComplexityLevel = Literal["simple", "medium", "complex"]
class TokenBudgetManager:
# Token limits by complexity
LIMITS = {
"simple": 200,
"medium": 1000,
"complex": 2500,
}
def __init__(self, complexity: ComplexityLevel = "medium"):
# Vali... | --- +++ @@ -1,3 +1,13 @@+"""
+Token Budget Manager
+
+Manages token allocation based on task complexity.
+
+Token Budget by Complexity:
+ - simple: 200 tokens (typo fix, trivial change)
+ - medium: 1,000 tokens (bug fix, small feature)
+ - complex: 2,500 tokens (large feature, refactoring)
+"""
from typing ... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/pm_agent/token_budget.py |
Improve documentation using docstrings |
from typing import Any, Dict, List, Tuple
class SelfCheckProtocol:
# 7 Red Flags for Hallucination Detection
HALLUCINATION_RED_FLAGS = [
"tests pass", # without showing output
"everything works", # without evidence
"implementation complete", # with failing tests
# Skipping... | --- +++ @@ -1,8 +1,54 @@+"""
+Post-implementation Self-Check Protocol
+
+Hallucination prevention through evidence-based validation.
+
+Token Budget: 200-2,500 tokens (complexity-dependent)
+Detection Rate: 94% (Reflexion benchmark)
+
+The Four Questions:
+1. Are all tests passing?
+2. Are all requirements met?
+3. No ... | https://raw.githubusercontent.com/SuperClaude-Org/SuperClaude_Framework/HEAD/src/superclaude/pm_agent/self_check.py |
Add return value explanations in docstrings | import string
from functools import cached_property
from typing import List, Optional, Tuple
import tokenizers
class Tokenizer:
def __init__(
self,
tokenizer: tokenizers.Tokenizer,
multilingual: bool,
task: Optional[str] = None,
language: Optional[str] = None,
):
... | --- +++ @@ -7,6 +7,7 @@
class Tokenizer:
+ """Simple wrapper around a tokenizers.Tokenizer."""
def __init__(
self,
@@ -112,6 +113,16 @@
@cached_property
def non_speech_tokens(self) -> Tuple[int]:
+ """
+ Returns the list of tokens to suppress in order to avoid any speaker... | https://raw.githubusercontent.com/SYSTRAN/faster-whisper/HEAD/faster_whisper/tokenizer.py |
Write docstrings for algorithm functions | import logging
import os
import re
from typing import List, Optional, Union
import huggingface_hub
from tqdm.auto import tqdm
_MODELS = {
"tiny.en": "Systran/faster-whisper-tiny.en",
"tiny": "Systran/faster-whisper-tiny",
"base.en": "Systran/faster-whisper-base.en",
"base": "Systran/faster-whisper-b... | --- +++ @@ -32,14 +32,17 @@
def available_models() -> List[str]:
+ """Returns the names of available models."""
return list(_MODELS.keys())
def get_assets_path():
+ """Returns the path to the assets directory."""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
def... | https://raw.githubusercontent.com/SYSTRAN/faster-whisper/HEAD/faster_whisper/utils.py |
Create documentation strings for testing functions | import bisect
import functools
import os
from dataclasses import dataclass
from typing import Dict, List, Optional, Tuple
import numpy as np
from faster_whisper.utils import get_assets_path
# The code below is adapted from https://github.com/snakers4/silero-vad.
@dataclass
class VadOptions:
threshold: float =... | --- +++ @@ -13,6 +13,30 @@ # The code below is adapted from https://github.com/snakers4/silero-vad.
@dataclass
class VadOptions:
+ """VAD options.
+
+ Attributes:
+ threshold: Speech threshold. Silero VAD outputs speech probabilities for each audio chunk,
+ probabilities ABOVE this value are conside... | https://raw.githubusercontent.com/SYSTRAN/faster-whisper/HEAD/faster_whisper/vad.py |
Fully document this Python code with docstrings |
import gc
import io
import itertools
from typing import BinaryIO, Union
import av
import numpy as np
def decode_audio(
input_file: Union[str, BinaryIO],
sampling_rate: int = 16000,
split_stereo: bool = False,
):
resampler = av.audio.resampler.AudioResampler(
format="s16",
layout="mo... | --- +++ @@ -1,3 +1,10 @@+"""We use the PyAV library to decode the audio: https://github.com/PyAV-Org/PyAV
+
+The advantage of PyAV is that it bundles the FFmpeg libraries so there is no additional
+system dependencies. FFmpeg does not need to be installed on the system.
+
+However, the API is quite low-level so we need... | https://raw.githubusercontent.com/SYSTRAN/faster-whisper/HEAD/faster_whisper/audio.py |
Generate docstrings with examples | import itertools
import json
import logging
import os
import zlib
from dataclasses import asdict, dataclass
from inspect import signature
from math import ceil
from typing import BinaryIO, Iterable, List, Optional, Tuple, Union
from warnings import warn
import ctranslate2
import numpy as np
import tokenizers
from tq... | --- +++ @@ -297,6 +297,82 @@ language_detection_threshold: Optional[float] = 0.5,
language_detection_segments: int = 1,
) -> Tuple[Iterable[Segment], TranscriptionInfo]:
+ """transcribe audio in chunks in batched fashion and return with language info.
+
+ Arguments:
+ audi... | https://raw.githubusercontent.com/SYSTRAN/faster-whisper/HEAD/faster_whisper/transcribe.py |
Write docstrings that follow conventions | # -*- coding: utf-8 -*-
import asyncio
import logging
import os
from typing import Optional, Union
# pylint: disable=relative-beyond-top-level
from .common import load_json_file
_LOGGER = logging.getLogger(__name__)
class MIoTI18n:
_main_loop: asyncio.AbstractEventLoop
_lang: str
_data: dict
def __... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_i18n.py |
Can you add docstrings to this Python file? | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.notify import ... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/notify.py |
Document helper functions with docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.select import SelectEntity
from .... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/select.py |
Add missing documentation to my Python functions | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.media_player import... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/media_player.py |
Include argument descriptions in docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.binary_sensor import BinarySensorEntity
from .miot.miot_spec ... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/binary_sensor.py |
Create docstrings for all classes and functions | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.device_tracker import TrackerEntit... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/device_tracker.py |
Write documentation strings for class attributes | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.switch import SwitchEntity
from .miot.... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/switch.py |
Write docstrings describing each step | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.sensor import SensorEnti... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/sensor.py |
Please document this code using docstrings | # -*- coding: utf-8 -*-
import asyncio
import base64
import hashlib
import json
import logging
import re
import time
from typing import Any, Optional
from urllib.parse import urlencode
import aiohttp
# pylint: disable=relative-beyond-top-level
from .common import calc_group_id
from .const import (
UNSUPPORTED_MODE... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_cloud.py |
Add docstrings for better understanding | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any, Optional
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.fan import (
... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/fan.py |
Add docstrings for utility scripts | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any, Optional
import re
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.cove... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/cover.py |
Write docstrings describing each step | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.number import NumberEntity
from .... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/number.py |
Create documentation strings for testing functions | # -*- coding: utf-8 -*-
import asyncio
import json
import logging
import random
import re
import ssl
import struct
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum, auto
from typing import Any, Callable, Optional, final, Coroutine
from paho.mqtt.client import... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_mips.py |
Create docstrings for reusable components | # -*- coding: utf-8 -*-
import os
import asyncio
import binascii
import json
import shutil
import time
import traceback
import hashlib
from datetime import datetime, timezone
from enum import Enum, auto
from pathlib import Path
from typing import Any, Optional, Union
import logging
from cryptography.hazmat.primitives i... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_storage.py |
Document my Python code with docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.light import (... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/light.py |
Add inline docstrings for readability | # -*- coding: utf-8 -*-
import asyncio
from abc import abstractmethod
from typing import Any, Callable, Optional
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER,
CONCENTRATION... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_device.py |
Generate consistent documentation across files | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.water_heater i... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/water_heater.py |
Write docstrings for backend logic | # -*- coding: utf-8 -*-
from __future__ import annotations
from typing import Any, Optional
import re
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.vacu... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/vacuum.py |
Write docstrings for data processing functions | # -*- coding: utf-8 -*-
import asyncio
import base64
import binascii
import copy
from enum import Enum
from typing import Callable, Coroutine, Optional
import logging
from zeroconf import (
DNSQuestionType,
IPVersion,
ServiceStateChange,
Zeroconf)
from zeroconf.asyncio import (
AsyncServiceInfo,
... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_mdns.py |
Add docstrings for internal functions | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.humidifier imp... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/humidifier.py |
Document this script properly | # -*- coding: utf-8 -*-
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.button import ButtonEntity
from .miot.miot_device import MIoT... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/button.py |
Write docstrings for utility functions | # -*- coding: utf-8 -*-
from copy import deepcopy
from typing import Any, Callable, Optional, final
import asyncio
import json
import logging
import time
import traceback
from dataclasses import dataclass
from enum import Enum, auto
from homeassistant.core import HomeAssistant
from homeassistant.components import zero... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_client.py |
Add minimal docstrings for each function | # -*- coding: utf-8 -*-
import asyncio
import json
from os import path
import random
from typing import Any, Optional
import hashlib
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from paho.mqtt.matcher import MQTTMatcher
import yaml
from slugify import slugify
MIOT_ROOT_PATH: str = pat... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/common.py |
Expand my code with proper documentation strings | # -*- coding: utf-8 -*-
import asyncio
import os
import platform
import time
from typing import Any, Optional, Type, Union
import logging
from slugify import slugify
# pylint: disable=relative-beyond-top-level
from .const import DEFAULT_INTEGRATION_LANGUAGE, SPEC_STD_LIB_EFFECTIVE_TIME
from .common import MIoTHttp, lo... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/miot/miot_spec.py |
Create docstrings for each class method | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any, Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import UnitOfTemperature
from homeassistant.helpers.entity_platform import AddEntitiesCal... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/climate.py |
Improve documentation using docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.components.event import EventEntity... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/event.py |
Generate consistent docstrings | # -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from typing import Optional
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.components import persistent_notification
from homeassistant.helpers import device_registry, entity_... | --- +++ @@ -1,300 +1,351 @@-# -*- coding: utf-8 -*-
-from __future__ import annotations
-import logging
-from typing import Optional
-
-from homeassistant.config_entries import ConfigEntry
-from homeassistant.core import HomeAssistant
-from homeassistant.components import persistent_notification
-from homeassistant.hel... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/__init__.py |
Write docstrings for utility functions | # -*- coding: utf-8 -*-
import asyncio
import hashlib
import ipaddress
import json
import secrets
import traceback
from typing import Optional, Set, Tuple
from urllib.parse import urlparse
from aiohttp import web
from aiohttp.hdrs import METH_GET
import voluptuous as vol
import logging
from homeassistant import config... | --- +++ @@ -1,4 +1,50 @@ # -*- coding: utf-8 -*-
+"""
+Copyright (C) 2024 Xiaomi Corporation.
+
+The ownership and intellectual property rights of Xiaomi Home Assistant
+Integration and related Xiaomi cloud service API interface provided under this
+license, including source code and object code (collectively, "License... | https://raw.githubusercontent.com/XiaoMi/ha_xiaomi_home/HEAD/custom_components/xiaomi_home/config_flow.py |
Create structured documentation for my script | # Copyright 2010-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,9 +12,16 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Representation for the MongoDB internal MaxKey type.
+"""
class MaxKey(object):
+ """MongoDB internal MaxKey type.
+
+ .. versionchanged:: 2.7
+ ``MaxKey`` now implem... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/max_key.py |
Improve documentation using docstrings | # -*- test-case-name: automat._test.test_methodical -*-
import collections
from functools import wraps
from itertools import count
try:
# Python 3
from inspect import getfullargspec as getArgsSpec
except ImportError:
# Python 2
from inspect import getargspec as getArgsSpec
import attr
import six
fro... | --- +++ @@ -24,6 +24,14 @@
def _getArgSpec(func):
+ """
+ Normalize inspect.ArgSpec across python versions
+ and convert mutable attributes to immutable types.
+
+ :param Callable func: A function.
+ :return: The function's ArgSpec.
+ :rtype: ArgSpec
+ """
spec = getArgsSpec(func)
ret... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/automat/_methodical.py |
Write docstrings for utility functions |
from __future__ import absolute_import, division, print_function
from ._make import NOTHING, Factory
def optional(converter):
def optional_converter(val):
if val is None:
return None
return converter(val)
return optional_converter
def default_if_none(default=NOTHING, factory=... | --- +++ @@ -1,3 +1,6 @@+"""
+Commonly useful converters.
+"""
from __future__ import absolute_import, division, print_function
@@ -5,6 +8,15 @@
def optional(converter):
+ """
+ A converter that allows an attribute to be optional. An optional attribute
+ is one which can be set to ``None``.
+
+ :par... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/converters.py |
Add docstrings to improve collaboration | # Copyright 2009-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for manipulating DBRefs (references to MongoDB documents)."""
from copy import deepcopy
@@ -20,11 +21,30 @@
class DBRef(object):
+ """A reference to a document stored... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/dbref.py |
Create documentation for each function signature | # Copyright 2015-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for representing raw BSON documents.
+"""
from bson import _raw_to_dict, _get_object_size
from bson.py3compat import abc, iteritems
@@ -21,11 +23,49 @@
class RawBSONDocum... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/raw_bson.py |
Write docstrings for algorithm functions | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,98 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for using Python's :mod:`json` module with BSON documents.
+
+This module provides two helper methods `dumps` and `loads` that wrap the
+native :mod:`json` methods and provide e... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/json_util.py |
Add docstrings to make code maintainable | # Copyright 2014-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""A BSON wrapper for long (int in python3)"""
from bson.py3compat import PY3
@@ -20,5 +21,14 @@
class Int64(long):
+ """Representation of the BSON int64 type.
- _type_ma... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/int64.py |
Generate docstrings with examples | # Copyright 2016-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,12 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for working with the BSON decimal128 type.
+
+.. versionadded:: 3.4
+
+.. note:: The Decimal128 BSON type requires MongoDB 3.4+.
+"""
import decimal
import struct
@@ -26,6 +... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/decimal128.py |
Generate docstrings with examples | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,11 +12,39 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for representing JavaScript code in BSON.
+"""
from bson.py3compat import abc, string_type, PY3, text_type
class Code(str):
+ """BSON's JavaScript code type.
+
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/code.py |
Generate helpful docstrings for debugging | from __future__ import absolute_import, division, print_function
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
if not isinstance(run, bool):
raise TypeError("'run' must be bool.")
global _run_validators
_run_validators = run
def get... | --- +++ @@ -7,6 +7,9 @@
def set_run_validators(run):
+ """
+ Set whether or not validators are run. By default, they are run.
+ """
if not isinstance(run, bool):
raise TypeError("'run' must be bool.")
global _run_validators
@@ -14,4 +17,7 @@
def get_run_validators():
- return _ru... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/_config.py |
Add structured docstrings to improve clarity | # Copyright 2014-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for specifying BSON codec options."""
import datetime
@@ -29,35 +30,92 @@
def _raw_document_class(document_class):
+ """Determine if a document_class is a RawBSONDocu... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/codec_options.py |
Write docstrings that follow conventions | # pkg-config, https://www.freedesktop.org/wiki/Software/pkg-config/ integration for cffi
import sys, os, subprocess
from .error import PkgConfigError
def merge_flags(cfg1, cfg2):
for key, value in cfg2.items():
if key not in cfg1:
cfg1[key] = value
else:
if not isinstance(... | --- +++ @@ -5,6 +5,12 @@
def merge_flags(cfg1, cfg2):
+ """Merge values from cffi config flags cfg2 to cf1
+
+ Example:
+ merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
+ {"libraries": ["one", "two"]}
+ """
for key, value in cfg2.items():
if key not in cfg1:
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cffi/pkgconfig.py |
Help me comply with documentation standards | import datetime
from base64 import b16encode
from functools import partial
from operator import __eq__, __ne__, __lt__, __le__, __gt__, __ge__
from six import (
integer_types as _integer_types,
text_type as _text_type,
PY3 as _PY3)
from cryptography import x509
from cryptography.hazmat.primitives.asymmet... | --- +++ @@ -76,6 +76,9 @@
class Error(Exception):
+ """
+ An error occurred in an `OpenSSL.crypto` API.
+ """
_raise_current_error = partial(_exception_from_error_queue, Error)
@@ -83,15 +86,35 @@
def _get_backend():
+ """
+ Importing the backend from cryptography has the side effect of acti... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/crypto.py |
Annotate my code with docstrings | from __future__ import absolute_import, division, print_function
class FrozenInstanceError(AttributeError):
msg = "can't set attribute"
args = [msg]
class AttrsAttributeNotFoundError(ValueError):
class NotAnAttrsClassError(ValueError):
class DefaultAlreadySetError(RuntimeError):
class UnannotatedAttr... | --- +++ @@ -2,27 +2,68 @@
class FrozenInstanceError(AttributeError):
+ """
+ A frozen/immutable instance has been attempted to be modified.
+
+ It mirrors the behavior of ``namedtuples`` by using the same error message
+ and subclassing `AttributeError`.
+
+ .. versionadded:: 16.1.0
+ """
m... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/exceptions.py |
Add structured docstrings to improve clarity | # -*- test-case-name: automat._test.test_core -*-
from itertools import chain
_NO_STATE = "<no state>"
class NoTransition(Exception):
def __init__(self, state, symbol):
self.state = state
self.symbol = symbol
super(Exception, self).__init__(
"no transition for {} in {}".for... | --- +++ @@ -1,5 +1,10 @@ # -*- test-case-name: automat._test.test_core -*-
+"""
+A core state-machine abstraction.
+
+Perhaps something that could be replaced with or integrated into machinist.
+"""
from itertools import chain
@@ -7,6 +12,14 @@
class NoTransition(Exception):
+ """
+ A finite state mach... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/automat/_core.py |
Add docstrings for production code | # Copyright 2013-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for representing MongoDB regular expressions.
+"""
import re
@@ -38,10 +40,34 @@
class Regex(object):
+ """BSON regular expression data."""
_type_marker = 11
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/regex.py |
Add docstrings to existing functions | # Copyright 2010-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | --- +++ @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Timezone related utilities for BSON."""
from datetime import (timedelta,
tzinfo)
@@ -20,6 +21,12 @@
class FixedOffset(tzinfo):
+ """Fixed offset timezo... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/tz_util.py |
Add professional docstrings to my codebase | from __future__ import absolute_import, division, print_function
from functools import total_ordering
from ._funcs import astuple
from ._make import attrib, attrs
@total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo(object):
year = attrib(type=int)
minor = attrib(type=in... | --- +++ @@ -9,6 +9,25 @@ @total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo(object):
+ """
+ A version object that can be compared to tuple of length 1--4:
+
+ >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2)
+ True
+ >>> attr.VersionInfo(19, 1, 0, "final") < (1... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/_version_info.py |
Write reusable docstrings |
class FFIError(Exception):
__module__ = 'cffi'
class CDefError(Exception):
__module__ = 'cffi'
def __str__(self):
try:
current_decl = self.args[1]
filename = current_decl.coord.file
linenum = current_decl.coord.line
prefix = '%s:%d: ' % (filename, li... | --- +++ @@ -15,10 +15,17 @@ return '%s%s' % (prefix, self.args[0])
class VerificationError(Exception):
+ """ An error raised when verification fails
+ """
__module__ = 'cffi'
class VerificationMissing(Exception):
+ """ An error raised when incomplete structures are passed into
+ cdef, but... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cffi/error.py |
Add professional docstrings to my codebase | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class CipherBack... | --- +++ @@ -13,94 +13,171 @@ class CipherBackend(object):
@abc.abstractmethod
def cipher_supported(self, cipher, mode):
+ """
+ Return True if the given cipher and mode are supported.
+ """
@abc.abstractmethod
def create_symmetric_encryption_ctx(self, cipher, mode):
+ "... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/backends/interfaces.py |
Document helper functions with docstrings | from __future__ import absolute_import, division, print_function
import platform
import sys
import types
import warnings
PY2 = sys.version_info[0] == 2
PYPY = platform.python_implementation() == "PyPy"
if PYPY or sys.version_info[:2] >= (3, 6):
ordered_dict = dict
else:
from collections import OrderedDict
... | --- +++ @@ -35,6 +35,9 @@
# Python 2 is bereft of a read-only dict proxy, so we make one!
class ReadOnlyDict(IterableUserDict):
+ """
+ Best-effort read-only dict wrapper.
+ """
def __setitem__(self, key, val):
# We gently pretend we're a Python 3 mappingproxy.
@@... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/_compat.py |
Add detailed docstrings explaining each function | from __future__ import print_function
import argparse
import sys
import graphviz
from ._discover import findMachines
def _gvquote(s):
return '"{}"'.format(s.replace('"', r'\"'))
def _gvhtml(s):
return '<{}>'.format(s)
def elementMaker(name, *children, **attrs):
formattedAttrs = ' '.join('{}={}'.form... | --- +++ @@ -16,6 +16,9 @@
def elementMaker(name, *children, **attrs):
+ """
+ Construct a string from the HTML element description.
+ """
formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value)))
for key, value in sorted(attrs.items()))
formattedChildren =... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/automat/_visualize.py |
Generate docstrings with examples | # Copyright 2010-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | --- +++ @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for representing MongoDB internal Timestamps.
+"""
import calendar
import datetime
@@ -23,10 +25,29 @@
class Timestamp(object):
+ """MongoDB internal timestamps used i... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/timestamp.py |
Write reusable docstrings |
from OpenSSL._util import lib as _lib
def add(buffer, entropy):
if not isinstance(buffer, bytes):
raise TypeError("buffer must be a byte string")
if not isinstance(entropy, int):
raise TypeError("entropy must be an integer")
_lib.RAND_add(buffer, len(buffer), entropy)
def status():
... | --- +++ @@ -1,8 +1,27 @@+"""
+PRNG management routines, thin wrappers.
+"""
from OpenSSL._util import lib as _lib
def add(buffer, entropy):
+ """
+ Mix bytes from *string* into the PRNG state.
+
+ The *entropy* argument is (the lower bound of) an estimate of how much
+ randomness is contained in *st... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/rand.py |
Add detailed documentation for each class | # -*- test-case-name: constantly.test.test_constants -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
from __future__ import division, absolute_import
__all__ = [
'NamedConstant', 'ValueConstant', 'FlagConstant',
'Names', 'Values', 'Flags']
from functools import partial
from itert... | --- +++ @@ -2,6 +2,10 @@ # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
+"""
+Symbolic constant support, including collections and constants with text,
+numeric, and bit flag values.
+"""
from __future__ import division, absolute_import
@@ -18,16 +22,39 @@
class _Constant(object):
+... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/constantly/_constants.py |
Write docstrings for algorithm functions | import sys
import warnings
from six import PY3, binary_type, text_type
from cryptography.hazmat.bindings.openssl.binding import Binding
binding = Binding()
binding.init_static_locks()
ffi = binding.ffi
lib = binding.lib
# This is a special CFFI allocator that does not bother to zero its memory
# after allocation.... | --- +++ @@ -19,12 +19,27 @@
def text(charp):
+ """
+ Get a native string type representing of the given CFFI ``char*`` object.
+
+ :param charp: A C-style string represented using CFFI.
+
+ :return: :class:`str`
+ """
if not charp:
return ""
return native(ffi.string(charp))
de... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/_util.py |
Expand my code with proper documentation strings | # Copyright 2009-2015 MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | --- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for working with MongoDB `ObjectIds
+<http://dochub.mongodb.org/core/objectids>`_.
+"""
import binascii
import calendar
@@ -38,10 +41,13 @@
def _random_bytes():
+ """G... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/objectid.py |
Auto-generate documentation strings for this file | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -117,6 +117,31 @@
class Binary(bytes):
+ """Representation of BSON binary data.
+
+ This is necessary because we want to represent Python strings as
+ the BSON string type. We need to wrap binary data so we can tell
+ the difference between what should be considered binary data and
+ what ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/binary.py |
Add docstrings to meet PEP guidelines | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import base64
import collections
import contextlib
import itertools
from ... | --- +++ @@ -110,6 +110,9 @@ binding.Binding().lib.Cryptography_HAS_SCRYPT, ScryptBackend
)
class Backend(object):
+ """
+ OpenSSL API binding interfaces.
+ """
name = "openssl"
def __init__(self):
@@ -182,6 +185,12 @@ return self._ffi.string(buf).decode('ascii')
def openssl_ver... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/backend.py |
Annotate my code with docstrings | import collections
import inspect
from automat import MethodicalMachine
from twisted.python.modules import PythonModule, getModule
def isOriginalLocation(attr):
sourceModule = inspect.getmodule(attr.load())
if sourceModule is None:
return False
currentModule = attr
while not isinstance(curren... | --- +++ @@ -5,6 +5,11 @@
def isOriginalLocation(attr):
+ """
+ Attempt to discover if this appearance of a PythonAttribute
+ representing a class refers to the module where that class was
+ defined.
+ """
sourceModule = inspect.getmodule(attr.load())
if sourceModule is None:
return... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/automat/_discover.py |
Create documentation for each function signature | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,18 +12,29 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Exceptions raised by the BSON package."""
class BSONError(Exception):
+ """Base class for all BSON exceptions.
+ """
class InvalidBSON(BSONError):
+ """Raised when... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/errors.py |
Document my Python code with docstrings | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,57 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""BSON (Binary JSON) encoding and decoding.
+
+The mapping from Python types to BSON types is as follows:
+
+======================================= ============= ===================
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/__init__.py |
Document this code for team use | from __future__ import absolute_import, division, print_function
import copy
import linecache
import sys
import threading
import uuid
import warnings
from operator import itemgetter
from . import _config
from ._compat import (
PY2,
isclass,
iteritems,
metadata_proxy,
ordered_dict,
set_closure... | --- +++ @@ -47,6 +47,11 @@
class _Nothing(object):
+ """
+ Sentinel class to indicate the lack of a value when ``None`` is ambiguous.
+
+ ``_Nothing`` is a singleton. There is only ever one of it.
+ """
_singleton = None
@@ -80,6 +85,113 @@ eq=None,
order=None,
):
+ """
+ Create... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/_make.py |
Add docstrings to clarify complex logic | import time
import requests
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
... | --- +++ @@ -16,6 +16,12 @@
def mergy_Image(image_file, location_list):
+ """
+ 将原始图片进行合成
+ :param image_file: 图片文件
+ :param location_list: 图片位置
+ :return: 合成新的图片
+ """
# 存放上下部分的各个小块
upper_half_list = []
@@ -118,6 +124,11 @@
def recognize_code(driver):
+ """
+ 识别滑动验证码
+ :pa... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/fuck_bilibili_captcha.py |
Create docstrings for each class method | #
# DEPRECATED: implementation for ffi.verify()
#
import sys, os, binascii, shutil, io
from . import __version_verifier_modules__
from . import ffiplatform
from .error import VerificationError
if sys.version_info >= (3, 3):
import importlib.machinery
def _extension_suffixes():
return importlib.machiner... | --- +++ @@ -70,6 +70,8 @@ self._has_module = False
def write_source(self, file=None):
+ """Write the C source code. It is produced in 'self.sourcefilename',
+ which can be tweaked beforehand."""
with self.ffi._lock:
if self._has_source and file is None:
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cffi/verifier.py |
Document this script properly |
from __future__ import absolute_import, division, print_function
import re
from ._make import _AndValidator, and_, attrib, attrs
from .exceptions import NotCallableError
__all__ = [
"and_",
"deep_iterable",
"deep_mapping",
"in_",
"instance_of",
"is_callable",
"matches_re",
"optional... | --- +++ @@ -1,3 +1,6 @@+"""
+Commonly useful validators.
+"""
from __future__ import absolute_import, division, print_function
@@ -25,6 +28,9 @@ type = attrib()
def __call__(self, inst, attr, value):
+ """
+ We use a callable class to be able to change the ``__repr__``.
+ """
... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/validators.py |
Provide clean and structured docstrings |
from __future__ import absolute_import, division, print_function
from ._compat import isclass
from ._make import Attribute
def _split_what(what):
return (
frozenset(cls for cls in what if isclass(cls)),
frozenset(cls for cls in what if isinstance(cls, Attribute)),
)
def include(*what):
... | --- +++ @@ -1,3 +1,6 @@+"""
+Commonly useful filters for `attr.asdict`.
+"""
from __future__ import absolute_import, division, print_function
@@ -6,6 +9,9 @@
def _split_what(what):
+ """
+ Returns a tuple of `frozenset`s of classes and attributes.
+ """
return (
frozenset(cls for cls in ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/filters.py |
Add docstrings for utility scripts | import os
import socket
from sys import platform
from functools import wraps, partial
from itertools import count, chain
from weakref import WeakValueDictionary
from errno import errorcode
from cryptography.utils import deprecated
from six import (
binary_type as _binary_type, integer_types as integer_types, int2... | --- +++ @@ -237,6 +237,9 @@
class Error(Exception):
+ """
+ An error occurred in an `OpenSSL.SSL` API.
+ """
_raise_current_error = partial(_exception_from_error_queue, Error)
@@ -264,11 +267,25 @@
class _CallbackExceptionHelper(object):
+ """
+ A base class for wrapper classes that allow fo... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/OpenSSL/SSL.py |
Add docstrings for production code | import sys, types
from .lock import allocate_lock
from .error import CDefError
from . import model
try:
callable
except NameError:
# Python 3.1
from collections import Callable
callable = lambda x: isinstance(x, Callable)
try:
basestring
except NameError:
# Python 3.x
basestring = str
_un... | --- +++ @@ -21,8 +21,27 @@
class FFI(object):
+ r'''
+ The main top-level class that you instantiate once, or once per module.
+
+ Example usage:
+
+ ffi = FFI()
+ ffi.cdef("""
+ int printf(const char *, ...);
+ """)
+
+ C = ffi.dlopen(None) # standard library
+ ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cffi/api.py |
Create docstrings for all classes and functions | from __future__ import absolute_import, division, print_function
import copy
from ._compat import iteritems
from ._make import NOTHING, _obj_setattr, fields
from .exceptions import AttrsAttributeNotFoundError
def asdict(
inst,
recurse=True,
filter=None,
dict_factory=dict,
retain_collection_types... | --- +++ @@ -14,6 +14,33 @@ dict_factory=dict,
retain_collection_types=False,
):
+ """
+ Return the ``attrs`` attribute values of *inst* as a dict.
+
+ Optionally recurse into other ``attrs``-decorated classes.
+
+ :param inst: Instance of an ``attrs``-decorated class.
+ :param bool recurse: Rec... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/attr/_funcs.py |
Can you add docstrings to this Python file? | # Copyright 2009-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,6 +12,11 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Tools for creating and manipulating SON, the Serialized Ocument Notation.
+
+Regular dictionaries can be used instead of SON objects, but not when the order
+of keys is important. A S... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/son.py |
Create docstrings for API functions | # Copyright 2010-present MongoDB, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | --- +++ @@ -12,9 +12,16 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Representation for the MongoDB internal MinKey type.
+"""
class MinKey(object):
+ """MongoDB internal MinKey type.
+
+ .. versionchanged:: 2.7
+ ``MinKey`` now implem... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/bson/min_key.py |
Add docstrings that explain purpose and usage | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography.exceptions import UnsupportedAl... | --- +++ @@ -26,9 +26,15 @@
@abc.abstractmethod
def public_bytes(self, encoding, format):
+ """
+ The serialized bytes of the public key.
+ """
@abc.abstractmethod
def verify(self, signature, data):
+ """
+ Verify the signature.
+ """
@six.add_metacla... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py |
Write docstrings including parameters and return values | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography.exceptions import UnsupportedAl... | --- +++ @@ -26,6 +26,9 @@
@abc.abstractmethod
def public_bytes(self, encoding, format):
+ """
+ The serialized bytes of the public key.
+ """
@six.add_metaclass(abc.ABCMeta)
@@ -53,9 +56,18 @@
@abc.abstractmethod
def public_key(self):
+ """
+ The serialized ... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py |
Create structured documentation for my script | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import abc
import six
from cryptography import utils
@six.add_metacla... | --- +++ @@ -15,60 +15,105 @@ class DSAParameters(object):
@abc.abstractmethod
def generate_private_key(self):
+ """
+ Generates and returns a DSAPrivateKey.
+ """
@six.add_metaclass(abc.ABCMeta)
class DSAParametersWithNumbers(DSAParameters):
@abc.abstractmethod
def paramet... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py |
Document this code for team use | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import calendar
import ipaddress
import six
from cryptography import ut... | --- +++ @@ -21,6 +21,13 @@
def _encode_asn1_int(backend, x):
+ """
+ Converts a python integer to an ASN1_INTEGER. The returned ASN1_INTEGER
+ will not be garbage collected (to support adding them to structs that take
+ ownership of the object). Be sure to register it for GC if it will be
+ discarded... | https://raw.githubusercontent.com/wistbean/learn_python3_spider/HEAD/stackoverflow/venv/lib/python3.6/site-packages/cryptography/hazmat/backends/openssl/encode_asn1.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.