instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Add minimal docstrings for each function |
import collections
import email.message
import functools
import itertools
import json
import logging
import os
import urllib.parse
import urllib.request
from dataclasses import dataclass
from html.parser import HTMLParser
from optparse import Values
from typing import (
Callable,
Dict,
Iterable,
List,
... | --- +++ @@ -1,3 +1,6 @@+"""
+The main purpose of this module is to expose LinkCollector.collect_sources().
+"""
import collections
import email.message
@@ -46,6 +49,10 @@
def _match_vcs_scheme(url: str) -> Optional[str]:
+ """Look for VCS schemes in the URL.
+
+ Returns the matched VCS scheme, or None if ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/index/collector.py |
Document all public functions with docstrings | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import absolute_import
import os
import re
import shutil
import sys
try:
import ssl
except ImportError: # pragma: ... | --- +++ @@ -94,6 +94,10 @@ pass
def _dnsname_match(dn, hostname, max_wildcards=1):
+ """Matching according to RFC 6125, section 6.4.3
+
+ http://tools.ietf.org/html/rfc6125#section-6.4.3
+ """
pats = []
if not dn:
return False
@@ -139,6 +143,13 @@ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/compat.py |
Improve documentation using docstrings | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2023 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import hashlib
import logging
import os
import shutil
import subprocess
import tempfile
try:
from threading import Thread
except Impo... | --- +++ @@ -27,10 +27,20 @@
class PackageIndex(object):
+ """
+ This class represents a package index compatible with PyPI, the Python
+ Package Index.
+ """
boundary = b'----------ThIs_Is_tHe_distlib_index_bouNdaRY_$'
def __init__(self, url=None):
+ """
+ Initialise an insta... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/index.py |
Document this module using docstrings | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2023 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import logging
import re
from .compat import string_types
from .util import parse_requirement
__all__ = ['NormalizedVersion', 'NormalizedMatcher',
'LegacyVersion', 'LegacyMatcher',... | --- +++ @@ -3,6 +3,10 @@ # Copyright (C) 2012-2023 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
+"""
+Implementation of a flexible versioning scheme providing support for PEP-440,
+setuptools-compatible and semantic versioning.
+"""
import logging
import re
@@ -19,6 +23,7 @@
class... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/version.py |
Create docstrings for reusable components | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2023 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import base64
import codecs
import datetime
from email import message_from_file
import hashlib
i... | --- +++ @@ -173,11 +173,17 @@
class Wheel(object):
+ """
+ Class to build and install from Wheel files (PEP 427).
+ """
wheel_version = (1, 1)
hash_kind = 'sha256'
def __init__(self, filename=None, sign=False, verify=False):
+ """
+ Initialise an instance using a (valid) fi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/wheel.py |
Document helper functions with docstrings |
import logging
import warnings
from typing import Any, Optional, TextIO, Type, Union
from pip._vendor.packaging.version import parse
from pip import __version__ as current_version # NOTE: tests patch this name.
DEPRECATION_MSG_PREFIX = "DEPRECATION: "
class PipDeprecationWarning(Warning):
pass
_original_sh... | --- +++ @@ -1,3 +1,6 @@+"""
+A module that implements tooling to enable easy warnings about deprecations.
+"""
import logging
import warnings
@@ -57,6 +60,25 @@ feature_flag: Optional[str] = None,
issue: Optional[int] = None,
) -> None:
+ """Helper to deprecate existing functionality.
+
+ reason:
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/deprecation.py |
Write docstrings for this repository | #!/usr/bin/env python
# Copyright 2015-2021 Nir Cohen
#
# 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 a... | --- +++ @@ -13,6 +13,20 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+The ``distro`` package (``distro`` stands for Linux Distribution) provides
+information about the Linux distribution it runs on, such as a reliable
+machine-readable distro ID, or v... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distro/distro.py |
Add docstrings to improve collaboration | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2023 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import base64
import codecs
import contextlib
import hashlib
import logging
import os
import posixpath
import sys
import zipimport
from . import Distli... | --- +++ @@ -3,6 +3,7 @@ # Copyright (C) 2012-2023 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
+"""PEP 376 implementation."""
from __future__ import unicode_literals
@@ -41,26 +42,50 @@
class _Cache(object):
+ """
+ A simple cache mapping names and .dist-info paths to distr... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/database.py |
Add verbose docstrings with examples | from typing import Optional
from pip._internal.models.format_control import FormatControl
# TODO: This needs Python 3.10's improved slots support for dataclasses
# to be converted into a dataclass.
class SelectionPreferences:
__slots__ = [
"allow_yanked",
"allow_all_prereleases",
"format... | --- +++ @@ -6,6 +6,10 @@ # TODO: This needs Python 3.10's improved slots support for dataclasses
# to be converted into a dataclass.
class SelectionPreferences:
+ """
+ Encapsulates the candidate selection preferences for downloading
+ and installing files.
+ """
__slots__ = [
"allow_yanke... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/models/selection_prefs.py |
Create docstrings for reusable components | import collections
import math
from functools import lru_cache
from typing import (
TYPE_CHECKING,
Dict,
Iterable,
Iterator,
Mapping,
Sequence,
TypeVar,
Union,
)
from pip._vendor.resolvelib.providers import AbstractProvider
from .base import Candidate, Constraint, Requirement
from .can... | --- +++ @@ -56,6 +56,13 @@ identifier: str,
default: D,
) -> Union[D, V]:
+ """Get item from a package name lookup mapping with a resolver identifier.
+
+ This extra logic is needed when the target mapping is keyed by package
+ name, which cannot be directly looked up with an identifier (which may
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/resolution/resolvelib/provider.py |
Generate docstrings for script automation | from . import idnadata
import bisect
import unicodedata
import re
from typing import Union, Optional
from .intranges import intranges_contain
_virama_combining_class = 9
_alabel_prefix = b'xn--'
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class IDNAError(UnicodeError):
pass
class IDNABidiError(I... | --- +++ @@ -10,18 +10,22 @@ _unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class IDNAError(UnicodeError):
+ """ Base exception for all IDNA-encoding related problems """
pass
class IDNABidiError(IDNAError):
+ """ Exception when bidirectional requirements are not satisfied """
pass
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/idna/core.py |
Create docstrings for API functions | # SPDX-FileCopyrightText: 2015 Eric Larson
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import calendar
import time
from datetime import datetime, timedelta, timezone
from email.utils import formatdate, parsedate, parsedate_tz
from typing import TYPE_CHECKING, Any, Mapping
if TYPE_CHECKI... | --- +++ @@ -26,9 +26,23 @@
class BaseHeuristic:
def warning(self, response: HTTPResponse) -> str | None:
+ """
+ Return a valid 1xx warning header value describing the cache
+ adjustments.
+
+ The response is provided too allow warnings like 113
+ http://tools.ietf.org/html/rfc... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/cachecontrol/heuristics.py |
Add verbose docstrings with examples | from collections import namedtuple
import datetime
import struct
class ExtType(namedtuple("ExtType", "code data")):
def __new__(cls, code, data):
if not isinstance(code, int):
raise TypeError("code must be int")
if not isinstance(data, bytes):
raise TypeError("data must be... | --- +++ @@ -4,6 +4,7 @@
class ExtType(namedtuple("ExtType", "code data")):
+ """ExtType represents ext type in msgpack."""
def __new__(cls, code, data):
if not isinstance(code, int):
@@ -16,10 +17,30 @@
class Timestamp:
+ """Timestamp represents the Timestamp extension type in msgpack.
+
+... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/msgpack/ext.py |
Add docstrings to meet PEP guidelines | from datetime import datetime as _DateTime
import sys
import struct
if hasattr(sys, "pypy_version_info"):
# StringIO is slow on PyPy, StringIO is faster. However: PyPy's own
# StringBuilder is fastest.
from __pypy__ import newlist_hint
try:
from __pypy__.builders import BytesBuilder as Strin... | --- +++ @@ -1,3 +1,4 @@+"""Fallback pure Python implementation of msgpack"""
from datetime import datetime as _DateTime
import sys
import struct
@@ -74,6 +75,17 @@
def unpackb(packed, **kwargs):
+ """
+ Unpack an object from `packed`.
+
+ Raises ``ExtraData`` when *packed* contains extra bytes.
+ Rai... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/msgpack/fallback.py |
Add docstrings following best practices |
from __future__ import annotations
import enum
import os
import struct
from typing import IO
class ELFInvalid(ValueError):
pass
class EIClass(enum.IntEnum):
C32 = 1
C64 = 2
class EIData(enum.IntEnum):
Lsb = 1
Msb = 2
class EMachine(enum.IntEnum):
I386 = 3
S390 = 22
Arm = 40
... | --- +++ @@ -1,3 +1,12 @@+"""
+ELF file parser.
+
+This provides a class ``ELFFile`` that parses an ELF executable in a similar
+interface to ``ZipFile``. Only the read interface is implemented.
+
+Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca
+ELF header: https://refspecs.linuxfoundation.or... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/_elffile.py |
Add docstrings for better understanding | from __future__ import annotations
import collections
import contextlib
import functools
import os
import re
import sys
import warnings
from typing import Generator, Iterator, NamedTuple, Sequence
from ._elffile import EIClass, EIData, ELFFile, EMachine
EF_ARM_ABIMASK = 0xFF000000
EF_ARM_ABI_VER5 = 0x05000000
EF_ARM... | --- +++ @@ -83,6 +83,9 @@
def _glibc_version_string_confstr() -> str | None:
+ """
+ Primary implementation of glibc_version_string using os.confstr.
+ """
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is used in the standard li... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/_manylinux.py |
Improve documentation using docstrings | import hashlib
from typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, NoReturn, Optional
from pip._internal.exceptions import HashMismatch, HashMissing, InstallationError
from pip._internal.utils.misc import read_chunks
if TYPE_CHECKING:
from hashlib import _Hash
# The recommended hash algo of the mo... | --- +++ @@ -19,8 +19,16 @@
class Hashes:
+ """A wrapper that builds multiple hashes at once and checks them against
+ known-good values
+
+ """
def __init__(self, hashes: Optional[Dict[str, List[str]]] = None) -> None:
+ """
+ :param hashes: A dict of algorithm names pointing to lists ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/hashes.py |
Create docstrings for all classes and functions | from __future__ import annotations
import email.feedparser
import email.header
import email.message
import email.parser
import email.policy
import typing
from typing import (
Any,
Callable,
Generic,
Literal,
TypedDict,
cast,
)
from . import requirements, specifiers, utils
from . import version... | --- +++ @@ -26,6 +26,11 @@ except NameError: # pragma: no cover
class ExceptionGroup(Exception):
+ """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11.
+
+ If :external:exc:`ExceptionGroup` is already defined by Python itself,
+ that version is used instead.
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/metadata.py |
Write docstrings for data processing functions | import functools
import logging
import re
from typing import NewType, Optional, Tuple, cast
from pip._vendor.packaging import specifiers, version
from pip._vendor.packaging.requirements import Requirement
NormalizedExtra = NewType("NormalizedExtra", str)
logger = logging.getLogger(__name__)
def check_requires_pyth... | --- +++ @@ -14,6 +14,17 @@ def check_requires_python(
requires_python: Optional[str], version_info: Tuple[int, ...]
) -> bool:
+ """
+ Check if the given Python version matches a "Requires-Python" specifier.
+
+ :param version_info: A 3-tuple of ints representing a Python
+ major-minor-micro versi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/packaging.py |
Fill in missing docstrings in my code | # 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 annotations
from typing import Any, Iterator
from ._parser import parse_requirement as _parse_requirement
from ._to... | --- +++ @@ -13,9 +13,18 @@
class InvalidRequirement(ValueError):
+ """
+ An invalid requirement was found, users should refer to PEP 508.
+ """
class Requirement:
+ """Parse a requirement.
+
+ Parse a given requirement string into its parts, such as name, specifier,
+ URL, and extras. Raises ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/requirements.py |
Provide docstrings following PEP 257 | import os
import re
import sys
from typing import List, Optional
from pip._internal.locations import site_packages, user_site
from pip._internal.utils.virtualenv import (
running_under_virtualenv,
virtualenv_no_global,
)
__all__ = [
"egg_link_path_from_sys_path",
"egg_link_path_from_location",
]
def... | --- +++ @@ -16,6 +16,14 @@
def _egg_link_names(raw_name: str) -> List[str]:
+ """
+ Convert a Name metadata value to a .egg-link name, by applying
+ the same substitution as pkg_resources's safe_name function.
+ Note: we cannot use canonicalize_name because it has a different logic.
+
+ We also look ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/egg_link.py |
Generate docstrings for this 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 annotations
import abc
import itertools
import re
from typing import Callable, Iterable, Iterator, TypeVar, Union
... | --- +++ @@ -1,6 +1,12 @@ # 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.
+"""
+.. testsetup::
+
+ from pip._vendor.packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifie... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/specifiers.py |
Add docstrings for internal functions |
from __future__ import annotations
import functools
import re
import subprocess
import sys
from typing import Iterator, NamedTuple, Sequence
from ._elffile import ELFFile
class _MuslVersion(NamedTuple):
major: int
minor: int
def _parse_musl_version(output: str) -> _MuslVersion | None:
lines = [n for ... | --- +++ @@ -1,3 +1,8 @@+"""PEP 656 support.
+
+This module implements logic to detect if the currently running Python is
+linked against musl, and what musl version is used.
+"""
from __future__ import annotations
@@ -27,6 +32,16 @@
@functools.lru_cache
def _get_musl_version(executable: str) -> _MuslVersion | N... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/_musllinux.py |
Create documentation for each function signature | import fnmatch
import os
import os.path
import random
import sys
from contextlib import contextmanager
from tempfile import NamedTemporaryFile
from typing import Any, BinaryIO, Generator, List, Union, cast
from pip._internal.utils.compat import get_path_uid
from pip._internal.utils.misc import format_size
from pip._in... | --- +++ @@ -41,6 +41,14 @@
@contextmanager
def adjacent_tmp_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:
+ """Return a file-like object pointing to a tmp file next to path.
+
+ The file is created securely and is ensured to be written to disk
+ after the context reaches its end.
+
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/filesystem.py |
Write reusable docstrings | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2023 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
# Note: In PEP 345, the micro-language was Python compatible, so the ast
# module could be used to parse it. However, PEP 508 introduced... | --- +++ @@ -4,6 +4,9 @@ # Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
+"""
+Parser for the environment markers micro-language defined in PEP 508.
+"""
# Note: In PEP 345, the micro-language was Python compatible, so the ast
# module could be ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/markers.py |
Generate consistent documentation across files | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2017 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import bisect
import io
import logging
import os
import pkgutil
import sys
import types
import z... | --- +++ @@ -32,10 +32,23 @@ super(ResourceCache, self).__init__(base)
def is_stale(self, resource, path):
+ """
+ Is the cache stale for the given resource?
+
+ :param resource: The :class:`Resource` being cached.
+ :param path: The path of the resource in the cache.
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/resources.py |
Create docstrings for each class method |
import logging
from email.message import Message
from email.parser import Parser
from typing import Tuple
from zipfile import BadZipFile, ZipFile
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import UnsupportedWheel
VERSION_COMPATIBLE = (1, 0)
logger = logging.getLogger(_... | --- +++ @@ -1,3 +1,5 @@+"""Support functions for working with wheel files.
+"""
import logging
from email.message import Message
@@ -16,6 +18,11 @@
def parse_wheel(wheel_zip: ZipFile, name: str) -> Tuple[str, Message]:
+ """Extract information from the provided wheel, ensuring it meets basic
+ standards.
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_internal/utils/wheel.py |
Add professional docstrings to my codebase | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from __future__ import unicode_literals
import codecs
from email import message_from_file
import json
import logging
import re
from . import DistlibException, __version__
from .compat import Strin... | --- +++ @@ -3,6 +3,10 @@ # Copyright (C) 2012 The Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
+"""Implementation of the Metadata for Python packages PEPs.
+
+Supports all metadata formats (1.0, 1.1, 1.2, 1.3/2.1 and 2.2).
+"""
from __future__ import unicode_literals
import codecs
@@ -22,... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/metadata.py |
Create documentation strings for testing functions | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2023 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import gzip
from io import BytesIO
import json
import logging
import os
import posixpath
import re
try:
import threading
except Impo... | --- +++ @@ -40,6 +40,11 @@
def get_all_distribution_names(url=None):
+ """
+ Return all distribution names known by an index.
+ :param url: The URL of the index.
+ :return: A list of all known distribution names.
+ """
if url is None:
url = DEFAULT_INDEX
client = ServerProxy(url, t... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/locators.py |
Add docstrings for better understanding |
from __future__ import annotations
import os
from abc import ABC, abstractmethod
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Iterator, Literal
class PlatformDirsABC(ABC): # noqa: PLR0904
def __init__( # noqa: PLR0913, PLR0917
self,
appna... | --- +++ @@ -1,3 +1,4 @@+"""Base API."""
from __future__ import annotations
@@ -11,6 +12,7 @@
class PlatformDirsABC(ABC): # noqa: PLR0904
+ """Abstract base class for platform directories."""
def __init__( # noqa: PLR0913, PLR0917
self,
@@ -22,6 +24,18 @@ opinion: bool = True, # no... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/api.py |
Generate consistent documentation across files |
from __future__ import annotations
import os
import re
import sys
from functools import lru_cache
from typing import TYPE_CHECKING, cast
from .api import PlatformDirsABC
class Android(PlatformDirsABC):
@property
def user_data_dir(self) -> str:
return self._append_app_name_and_version(cast(str, _an... | --- +++ @@ -1,3 +1,4 @@+"""Android."""
from __future__ import annotations
@@ -11,37 +12,58 @@
class Android(PlatformDirsABC):
+ """
+ Follows the guidance `from here <https://android.stackexchange.com/a/216132>`_.
+
+ Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `version
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/android.py |
Add missing documentation to my Python functions |
from __future__ import annotations
import ast
from typing import NamedTuple, Sequence, Tuple, Union
from ._tokenizer import DEFAULT_RULES, Tokenizer
class Node:
def __init__(self, value: str) -> None:
self.value = value
def __str__(self) -> str:
return self.value
def __repr__(self) ->... | --- +++ @@ -1,3 +1,8 @@+"""Handwritten parser of dependency specifiers.
+
+The docstring for each __parse_* function contains EBNF-inspired grammar representing
+the implementation.
+"""
from __future__ import annotations
@@ -58,6 +63,9 @@
def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/_parser.py |
Add missing documentation to my Python functions | # -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2023 Vinay Sajip.
# Licensed to the Python Software Foundation under a contributor agreement.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
from io import BytesIO
import logging
import os
import re
import struct
import sys
import time
from zipfile import ZipInfo
from .compat ... | --- +++ @@ -89,6 +89,10 @@
class ScriptMaker(object):
+ """
+ A class to copy or create scripts from source scripts or callable
+ specifications.
+ """
script_template = SCRIPT_TEMPLATE
executable = None # for shebangs
@@ -124,6 +128,10 @@ if sys.platform.startswith('java'): # pragma: ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/scripts.py |
Fully document this Python code with docstrings |
esc = "\x1b["
codes = {}
codes[""] = ""
codes["reset"] = esc + "39;49;00m"
codes["bold"] = esc + "01m"
codes["faint"] = esc + "02m"
codes["standout"] = esc + "03m"
codes["underline"] = esc + "04m"
codes["blink"] = esc + "05m"
codes["overline"] = esc + "06m"
dark_colors = ["black", "red", "green", "yellow", "blue",
... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.console
+ ~~~~~~~~~~~~~~~~
+
+ Format colored console output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
esc = "\x1b["
@@ -37,6 +46,14 @@
def ansiformat(attr, text):
+ """
+ F... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/console.py |
Help me write clear docstrings |
import bisect
from typing import List, Tuple
def intranges_from_list(list_: List[int]) -> Tuple[int, ...]:
sorted_list = sorted(list_)
ranges = []
last_write = -1
for i in range(len(sorted_list)):
if i+1 < len(sorted_list):
if sorted_list[i] == sorted_list[i+1]-1:
... | --- +++ @@ -1,8 +1,20 @@+"""
+Given a list of integers, made up of (hopefully) a small number of long runs
+of consecutive integers, compute a representation of the form
+((start1, end1), (start2, end2) ...). Then answer the question "was x present
+in the original list?" in time O(log(# runs)).
+"""
import bisect
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/idna/intranges.py |
Add docstrings to improve collaboration | # -*- coding: utf-8 -*-
#
# Copyright (C) 2012-2023 Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
import fnmatch
import logging
import os
import re
import sys
from . import DistlibException
from .compat import fsdecode
from .util import convert_path
__all__ = ['Manifest']
logger = logging.ge... | --- +++ @@ -3,6 +3,11 @@ # Copyright (C) 2012-2023 Python Software Foundation.
# See LICENSE.txt and CONTRIBUTORS.txt.
#
+"""
+Class representing the list of files in a distribution.
+
+Equivalent to distutils.filelist, but fixes some problems.
+"""
import fnmatch
import logging
import os
@@ -31,8 +36,17 @@
cl... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/distlib/manifest.py |
Add docstrings to improve collaboration |
def apply_filters(stream, filters, lexer=None):
def _apply(filter_, stream):
yield from filter_.filter(lexer, stream)
for filter_ in filters:
stream = _apply(filter_, stream)
return stream
def simplefilter(f):
return type(f.__name__, (FunctionFilter,), {
'__module__': getattr... | --- +++ @@ -1,6 +1,20 @@+"""
+ pygments.filter
+ ~~~~~~~~~~~~~~~
+
+ Module that implements the default filter.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
def apply_filters(stream, filters, lexer=None):
+ """
+ Use this... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/filter.py |
Improve my code by adding docstrings |
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.util import get_bool_opt
__all__ = ['BBCodeFormatter']
class BBCodeFormatter(Formatter):
name = 'BBCode'
aliases = ['bbcode', 'bb']
filenames = []
def __init__(self, **options):
Formatter.__init__(self, **option... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.bbcode
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ BBcode formatter.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter import Formatter
@@ -7,6 +16,34 @@
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/bbcode.py |
Write docstrings including parameters and return values |
import math
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.util import get_bool_opt, get_int_opt
__all__ = ['GroffFormatter']
class GroffFormatter(Formatter):
name = 'groff'
aliases = ['groff','troff','roff']
filenames = []
def __init__(self, **options):
For... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.groff
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for groff output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import math
from pip._vendor.pygments.formatter import Formatter
@... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/groff.py |
Add detailed documentation for each class |
from __future__ import annotations
import os
import sys
from typing import TYPE_CHECKING
from .api import PlatformDirsABC
from .version import __version__
from .version import __version_tuple__ as __version_info__
if TYPE_CHECKING:
from pathlib import Path
from typing import Literal
def _set_platform_dir_... | --- +++ @@ -1,3 +1,9 @@+"""
+Utilities for determining application-specific dirs.
+
+See <https://github.com/platformdirs/platformdirs> for details and usage.
+
+"""
from __future__ import annotations
@@ -47,6 +53,14 @@ roaming: bool = False, # noqa: FBT001, FBT002
ensure_exists: bool = False, # noqa: F... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/__init__.py |
Help me add docstrings to my project |
import functools
import os
import sys
import os.path
from io import StringIO
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.token import Token, Text, STANDARD_TYPES
from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt
try:
import ctags
except ImportError:
... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.html
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for HTML output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import functools
import os
@@ -27,6 +36,7 @@
def escape_html(text... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/html.py |
Fully document this Python code with docstrings | from .exceptions import *
from .ext import ExtType, Timestamp
import os
version = (1, 0, 8)
__version__ = "1.0.8"
if os.environ.get("MSGPACK_PUREPYTHON"):
from .fallback import Packer, unpackb, Unpacker
else:
try:
from ._cmsgpack import Packer, unpackb, Unpacker
except ImportError:
from... | --- +++ @@ -18,15 +18,31 @@
def pack(o, stream, **kwargs):
+ """
+ Pack object `o` and write it to `stream`
+
+ See :class:`Packer` for options.
+ """
packer = Packer(**kwargs)
stream.write(packer.pack(o))
def packb(o, **kwargs):
+ """
+ Pack object `o` and return packed bytes
+
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/msgpack/__init__.py |
Add well-formatted docstrings |
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.token import Comment
from pip._vendor.pygments.util import get_bool_opt, get_int_opt
__all__ = ['SvgFormatter']
def escape_html(text):
return text.replace('&', '&'). \
replace('<', '<'). \
re... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.svg
+ ~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for SVG output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.py... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/svg.py |
Help me comply with documentation standards | # 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 annotations
import logging
import platform
import re
import struct
import subprocess
import sys
import sysconfig
fr... | --- +++ @@ -40,6 +40,12 @@
class Tag:
+ """
+ A representation of the tag triple for a wheel.
+
+ Instances are considered immutable and thus are hashable. Equality checking
+ is also supported.
+ """
__slots__ = ["_interpreter", "_abi", "_platform", "_hash"]
@@ -88,6 +94,12 @@
def parse... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/tags.py |
Write documentation strings for class attributes | # 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 annotations
import operator
import os
import platform
import sys
from typing import Any, Callable, TypedDict, cast
... | --- +++ @@ -28,12 +28,22 @@
class InvalidMarker(ValueError):
+ """
+ An invalid marker was found, users should refer to PEP 508.
+ """
class UndefinedComparison(ValueError):
+ """
+ An invalid operation was attempted on a value that doesn't support it.
+ """
class UndefinedEnvironmentNam... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/markers.py |
Write docstrings for data processing functions | import os
import sys
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
get_choice_opt
import subprocess
# Import this carefully
try:
from PIL import Image, ImageDraw, ImageFont
pil_available = True
except ImportError:
... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.img
+ ~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for Pixmap output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import os
import sys
@@ -41,12 +50,17 @@
class PilNotAvailable(Im... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/img.py |
Add docstrings to improve code quality |
import re
import sys
import time
from pip._vendor.pygments.filter import apply_filters, Filter
from pip._vendor.pygments.filters import get_filter_by_name
from pip._vendor.pygments.token import Error, Text, Other, Whitespace, _TokenType
from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.lexer
+ ~~~~~~~~~~~~~~
+
+ Base lexer classes.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
import sys
@@ -26,6 +35,10 @@
class LexerMeta(type):
+ """
+ This metaclass ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/lexer.py |
Create documentation for each function signature | class UnpackException(Exception):
class BufferFull(UnpackException):
pass
class OutOfData(UnpackException):
pass
class FormatError(ValueError, UnpackException):
class StackError(ValueError, UnpackException):
# Deprecated. Use ValueError instead
UnpackValueError = ValueError
class ExtraData(UnpackVa... | --- +++ @@ -1,4 +1,10 @@ class UnpackException(Exception):
+ """Base class for some exceptions raised while unpacking.
+
+ NOTE: unpack may raise exception other than subclass of
+ UnpackException. If you want to catch all error, catch
+ Exception instead.
+ """
class BufferFull(UnpackException):
@... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/msgpack/exceptions.py |
Add docstrings for better understanding |
import keyword
from pip._vendor.pygments.lexer import DelegatingLexer, RegexLexer, include, \
bygroups, using, default, words, combined, this
from pip._vendor.pygments.util import get_bool_opt, shebang_matches
from pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \
Number, Pun... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.lexers.python
+ ~~~~~~~~~~~~~~~~~~~~~~
+
+ Lexers for Python and related languages.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import keyword
@@ -14,6 +23,13 @@
class PythonLexer(Re... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/lexers/python.py |
Fully document this Python code with docstrings |
import re
__all__ = ['get_filetype_from_buffer']
modeline_re = re.compile(r'''
(?: vi | vim | ex ) (?: [<=>]? \d* )? :
.* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ )
''', re.VERBOSE)
def get_filetype_from_line(l): # noqa: E741
m = modeline_re.search(l)
if m:
return m.group(1)
def ge... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.modeline
+ ~~~~~~~~~~~~~~~~~
+
+ A simple modeline parser (based on pymodeline).
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
@@ -17,6 +26,9 @@
def get_filetype_from_buffer(... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/modeline.py |
Add detailed documentation for each class |
class _TokenType(tuple):
parent = None
def split(self):
buf = []
node = self
while node is not None:
buf.append(node)
node = node.parent
buf.reverse()
return buf
def __init__(self, *args):
# no need to call super.__init__
se... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.token
+ ~~~~~~~~~~~~~~
+
+ Basic token types and the standard tokens.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
class _TokenType(tuple):
@@ -74,10 +83,30 @@
def is_token_subtype(tt... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/token.py |
Write proper docstrings for these functions | # TODO: Add Generic type annotations to initialized collections.
# For now we'd simply use implicit Any/Unknown which would add redundant annotations
# mypy: disable-error-code="var-annotated"
from __future__ import annotations
import sys
if sys.version_info < (3, 8): # noqa: UP036 # Check for unsupported versions
... | --- +++ @@ -1,6 +1,24 @@ # TODO: Add Generic type annotations to initialized collections.
# For now we'd simply use implicit Any/Unknown which would add redundant annotations
# mypy: disable-error-code="var-annotated"
+"""
+Package resource API
+--------------------
+
+A resource is a logical file contained within a ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py |
Write documentation strings for class attributes | # 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 annotations
import itertools
import re
from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union
fro... | --- +++ @@ -1,6 +1,11 @@ # 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.
+"""
+.. testsetup::
+
+ from pip._vendor.packaging.version import parse, Version
+"""
from __future__ impo... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/version.py |
Create docstrings for reusable components |
from __future__ import annotations
import os
import sys
from functools import lru_cache
from typing import TYPE_CHECKING
from .api import PlatformDirsABC
if TYPE_CHECKING:
from collections.abc import Callable
class Windows(PlatformDirsABC):
@property
def user_data_dir(self) -> str:
const = "C... | --- +++ @@ -1,3 +1,4 @@+"""Windows."""
from __future__ import annotations
@@ -13,9 +14,23 @@
class Windows(PlatformDirsABC):
+ """
+ `MSDN on where to store app data files <https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_.
+
+ Makes use of the `appname <platformdirs.api.PlatformD... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/windows.py |
Add docstrings to make code maintainable | # 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 annotations
import re
from typing import NewType, Tuple, Union, cast
from .tags import Tag, parse_tag
from .versio... | --- +++ @@ -15,12 +15,21 @@
class InvalidName(ValueError):
+ """
+ An invalid distribution name; users should refer to the packaging user guide.
+ """
class InvalidWheelFilename(ValueError):
+ """
+ An invalid wheel filename was found, users should refer to PEP 427.
+ """
class InvalidSd... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/utils.py |
Create docstrings for API functions |
import re
from pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \
string_to_tokentype
from pip._vendor.pygments.filter import Filter
from pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \
get_choice_opt, ClassNotFound, OptionError
from pip._vendor.... | --- +++ @@ -1,3 +1,13 @@+"""
+ pygments.filters
+ ~~~~~~~~~~~~~~~~
+
+ Module containing filter lookup functions and default
+ filters.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
@@ -10,6 +20,7 @@
def find_fi... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/filters/__init__.py |
Create simple docstrings for beginners |
from __future__ import annotations
import os.path
import sys
from .api import PlatformDirsABC
class MacOS(PlatformDirsABC):
@property
def user_data_dir(self) -> str:
return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support")) # noqa: PTH111
@property
def... | --- +++ @@ -1,3 +1,4 @@+"""macOS."""
from __future__ import annotations
@@ -8,13 +9,32 @@
class MacOS(PlatformDirsABC):
+ """
+ Platform directories for the macOS operating system.
+
+ Follows the guidance from
+ `Apple documentation <https://developer.apple.com/library/archive/documentation/FileMa... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/macos.py |
Turn comments into proper docstrings |
from __future__ import annotations
import os
import sys
from configparser import ConfigParser
from pathlib import Path
from typing import Iterator, NoReturn
from .api import PlatformDirsABC
if sys.platform == "win32":
def getuid() -> NoReturn:
msg = "should only be used on Unix"
raise RuntimeEr... | --- +++ @@ -1,3 +1,4 @@+"""Unix."""
from __future__ import annotations
@@ -20,9 +21,24 @@
class Unix(PlatformDirsABC): # noqa: PLR0904
+ """
+ On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-
+ latest.html>`_.
+
+ The spec allows ove... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/platformdirs/unix.py |
Write Python docstrings for this snippet | from io import StringIO, BytesIO
__version__ = '2.18.0'
__docformat__ = 'restructuredtext'
__all__ = ['lex', 'format', 'highlight']
def lex(code, lexer):
try:
return lexer.get_tokens(code)
except TypeError:
# Heuristic to catch a common mistake.
from pip._vendor.pygments.lexer import... | --- +++ @@ -1,3 +1,29 @@+"""
+ Pygments
+ ~~~~~~~~
+
+ Pygments is a syntax highlighting package written in Python.
+
+ It is a generic syntax highlighter for general use in all kinds of software
+ such as forum systems, wikis or other applications that need to prettify
+ source code. Highlights are:
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/__init__.py |
Write docstrings including parameters and return values |
import re
import sys
import types
import fnmatch
from os.path import basename
from pip._vendor.pygments.formatters._mapping import FORMATTERS
from pip._vendor.pygments.plugin import find_plugin_formatters
from pip._vendor.pygments.util import ClassNotFound
__all__ = ['get_formatter_by_name', 'get_formatter_for_filen... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters
+ ~~~~~~~~~~~~~~~~~~~
+
+ Pygments formatters.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
import sys
@@ -17,6 +26,7 @@
def _fn_matches(fn, glob):
+ """Return ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/__init__.py |
Insert docstrings into my code |
import codecs
from pip._vendor.pygments.util import get_bool_opt
from pip._vendor.pygments.styles import get_style_by_name
__all__ = ['Formatter']
def _lookup_style(style):
if isinstance(style, str):
return get_style_by_name(style)
return style
class Formatter:
#: Full name for the formatter... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatter
+ ~~~~~~~~~~~~~~~~~~
+
+ Base formatter class.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import codecs
@@ -14,6 +23,46 @@
class Formatter:
+ """
+ Converts a token ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatter.py |
Add structured docstrings to improve clarity | from __future__ import annotations
import contextlib
import re
from dataclasses import dataclass
from typing import Iterator, NoReturn
from .specifiers import Specifier
@dataclass
class Token:
name: str
text: str
position: int
class ParserSyntaxError(Exception):
def __init__(
self,
... | --- +++ @@ -16,6 +16,7 @@
class ParserSyntaxError(Exception):
+ """The provided source text could not be parsed correctly."""
def __init__(
self,
@@ -87,6 +88,11 @@
class Tokenizer:
+ """Context-sensitive token parsing.
+
+ Provides methods to examine the input stream to check whether t... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/packaging/_tokenizer.py |
Add structured docstrings to improve clarity | import json
import os
import os.path
import re
import shutil
import sys
import traceback
from glob import glob
from importlib import import_module
from os.path import join as pjoin
# This file is run as a script, and `import wrappers` is not zip-safe, so we
# include write_json() and read_json() from wrappers.py.
de... | --- +++ @@ -1,3 +1,17 @@+"""This is invoked in a subprocess to call the build backend hooks.
+
+It expects:
+- Command line args: hook_name, control_dir
+- Environment variables:
+ PEP517_BUILD_BACKEND=entry.point:spec
+ PEP517_BACKEND_PATH=paths (separated with os.pathsep)
+- control_dir/input.json:
+ - {"k... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py |
Create documentation strings for testing functions |
from pip._vendor.pygments.plugin import find_plugin_styles
from pip._vendor.pygments.util import ClassNotFound
from pip._vendor.pygments.styles._mapping import STYLES
#: A dictionary of built-in styles, mapping style names to
#: ``'submodule::classname'`` strings.
#: This list is deprecated. Use `pygments.styles.STYL... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.styles
+ ~~~~~~~~~~~~~~~
+
+ Contains built-in styles.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.plugin import find_plugin_styles
from pip._vendor.pygments.uti... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/styles/__init__.py |
Add professional docstrings to my codebase |
from io import StringIO
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.lexer import Lexer, do_insertions
from pip._vendor.pygments.token import Token, STANDARD_TYPES
from pip._vendor.pygments.util import get_bool_opt, get_int_opt
__all__ = ['LatexFormatter']
def escape_tex(text, co... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.latex
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for LaTeX fancyvrb output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from io import StringIO
@@ -136,6 +145,110 @@
class ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/latex.py |
Generate docstrings for script automation |
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Token, Whitespace
from pip._vendor.pygments.util import get_choice_opt
__all__ = ['IRCFormatter']
#: Map token types to a tuple of color values for lig... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.irc
+ ~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for IRC output
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pyg... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/irc.py |
Provide clean and structured docstrings |
from pip._vendor.pygments.formatter import Formatter
__all__ = ['PangoMarkupFormatter']
_escape_table = {
ord('&'): '&',
ord('<'): '<',
}
def escape_special_chars(text, table=_escape_table):
return text.translate(table)
class PangoMarkupFormatter(Formatter):
name = 'Pango Markup'
al... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.pangomarkup
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for Pango markup output.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter import Forma... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py |
Add docstrings to make code maintainable |
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.util import get_choice_opt
from pip._vendor.pygments.token import Token
from pip._vendor.pygments.console import colorize
__all__ = ['NullFormatter', 'RawTokenFormatter', 'TestcaseFormatter']
class NullFormatter(Formatter):
name = 'T... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.other
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Other formatters: NullFormatter, RawTokenFormatter.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter import ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/other.py |
Add detailed docstrings explaining each function |
import hashlib
import os
import re
import threading
import time
import warnings
from base64 import b64encode
from ._internal_utils import to_native_string
from .compat import basestring, str, urlparse
from .cookies import extract_cookies_to_jar
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = "app... | --- +++ @@ -1,3 +1,9 @@+"""
+requests.auth
+~~~~~~~~~~~~~
+
+This module contains the authentication handlers for Requests.
+"""
import hashlib
import os
@@ -17,6 +23,7 @@
def _basic_auth_str(username, password):
+ """Returns a Basic Auth string."""
# "I want us to put a big-ol' comment on top of it t... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/auth.py |
Add inline docstrings for readability |
from collections import OrderedDict
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.style import _ansimap
from pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, surrogatepair
__all__ = ['RtfFormatter']
class RtfFormatter(Formatter):
name = 'RTF'
aliase... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.rtf
+ ~~~~~~~~~~~~~~~~~~~~~~~
+
+ A formatter that generates RTF files.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from collections import OrderedDict
from pip._vendor.pygment... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/rtf.py |
Fill in missing docstrings in my code |
from pip._vendor.pygments.formatter import Formatter
from pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \
Number, Operator, Generic, Token, Whitespace
from pip._vendor.pygments.console import ansiformat
from pip._vendor.pygments.util import get_choice_opt
__all__ = ['TerminalFormatter'... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.formatters.terminal
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for terminal output with ANSI sequences.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
from pip._vendor.pygments.formatter im... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/terminal.py |
Help me write clear docstrings |
# TODO:
# - Options to map style's bold/underline/italic/border attributes
# to some ANSI attrbutes (something like 'italic=underline')
# - An option to output "style RGB to xterm RGB/index" conversion table
# - An option to indicate that we are running in "reverse background"
# xterm. This means that default... | --- +++ @@ -1,3 +1,18 @@+"""
+ pygments.formatters.terminal256
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ Formatter for 256-color terminal output with ANSI sequences.
+
+ RGB-to-XTERM color conversion routines adapted from xterm256-conv
+ tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/formatters/terminal256.py |
Add verbose docstrings with examples | HOOKS = ["response"]
def default_hooks():
return {event: [] for event in HOOKS}
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
hooks = hooks or {}
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, "__call__"):
hooks = [hooks]
for h... | --- +++ @@ -1,3 +1,14 @@+"""
+requests.hooks
+~~~~~~~~~~~~~~
+
+This module provides the capabilities for the Requests hooks system.
+
+Available hooks:
+
+``response``:
+ The response generated from a Request.
+"""
HOOKS = ["response"]
@@ -9,6 +20,7 @@
def dispatch_hook(key, hooks, hook_data, **kwargs):
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/hooks.py |
Add docstrings with type hints explained | import re
class EndOfText(RuntimeError):
class Scanner:
def __init__(self, text, flags=0):
self.data = text
self.data_length = len(text)
self.start_pos = 0
self.pos = 0
self.flags = flags
self.last = None
self.match = None
self._re_cache = {}
... | --- +++ @@ -1,12 +1,42 @@+"""
+ pygments.scanner
+ ~~~~~~~~~~~~~~~~
+
+ This library implements a regex based scanner. Some languages
+ like Pascal are easy to parse but have some keywords that
+ depend on the context. Because of this it's impossible to lex
+ that just by using a regular expression le... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/scanner.py |
Provide clean and structured docstrings |
import datetime
# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
import encodings.idna # noqa: F401
from io import UnsupportedOperation
from ... | --- +++ @@ -1,3 +1,9 @@+"""
+requests.models
+~~~~~~~~~~~~~~~
+
+This module contains the primary objects that power Requests.
+"""
import datetime
@@ -78,6 +84,7 @@ class RequestEncodingMixin:
@property
def path_url(self):
+ """Build the path URL to use."""
url = []
@@ -98,6 +105,12 ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/models.py |
Write Python docstrings for this snippet | import os
import sys
import time
from collections import OrderedDict
from datetime import timedelta
from ._internal_utils import to_native_string
from .adapters import HTTPAdapter
from .auth import _basic_auth_str
from .compat import Mapping, cookielib, urljoin, urlparse
from .cookies import (
RequestsCookieJar,
... | --- +++ @@ -1,3 +1,10 @@+"""
+requests.sessions
+~~~~~~~~~~~~~~~~~
+
+This module provides a Session object to manage and persist settings across
+requests (cookies, auth, proxies).
+"""
import os
import sys
import time
@@ -52,6 +59,10 @@
def merge_setting(request_setting, session_setting, dict_class=OrderedDict... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/sessions.py |
Document classes and their methods |
import os.path
import socket # noqa: F401
import typing
import warnings
from pip._vendor.urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError
from pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader
from pip._vendor.urllib... | --- +++ @@ -1,3 +1,10 @@+"""
+requests.adapters
+~~~~~~~~~~~~~~~~~
+
+This module contains the transport adapters that Requests uses to define
+and maintain connections.
+"""
import os.path
import socket # noqa: F401
@@ -128,6 +135,7 @@
class BaseAdapter:
+ """The Base Transport Adapter"""
def __init... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/adapters.py |
Help me add docstrings to my project |
import json
import platform
import ssl
import sys
from pip._vendor import idna
from pip._vendor import urllib3
from . import __version__ as requests_version
charset_normalizer = None
chardet = None
try:
from pip._vendor.urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = Non... | --- +++ @@ -1,3 +1,4 @@+"""Module containing bug report helper(s)."""
import json
import platform
@@ -24,6 +25,16 @@
def _implementation():
+ """Return a dict with the Python implementation and version.
+
+ Provide both the name and the version of the Python implementation
+ currently running. For exam... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/help.py |
Document classes and their methods | from pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError
from .compat import JSONDecodeError as CompatJSONDecodeError
class RequestException(IOError):
def __init__(self, *args, **kwargs):
response = kwargs.pop("response", None)
self.response = response
self.request = kwargs.... | --- +++ @@ -1,11 +1,21 @@+"""
+requests.exceptions
+~~~~~~~~~~~~~~~~~~~
+
+This module contains the set of Requests' exceptions.
+"""
from pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError
from .compat import JSONDecodeError as CompatJSONDecodeError
class RequestException(IOError):
+ """There... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/exceptions.py |
Document my Python code with docstrings |
import re
from re import escape
from os.path import commonprefix
from itertools import groupby
from operator import itemgetter
CS_ESCAPE = re.compile(r'[\[\^\\\-\]]')
FIRST_ELEMENT = itemgetter(0)
def make_charset(letters):
return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']'
def reg... | --- +++ @@ -1,3 +1,13 @@+"""
+ pygments.regexopt
+ ~~~~~~~~~~~~~~~~~
+
+ An algorithm that generates optimized regexes for matching long lists of
+ literal strings.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
from ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/regexopt.py |
Add docstrings explaining edge cases |
import re
import sys
import types
import fnmatch
from os.path import basename
from pip._vendor.pygments.lexers._mapping import LEXERS
from pip._vendor.pygments.modeline import get_filetype_from_buffer
from pip._vendor.pygments.plugin import find_plugin_lexers
from pip._vendor.pygments.util import ClassNotFound, guess... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.lexers
+ ~~~~~~~~~~~~~~~
+
+ Pygments lexers.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
import sys
@@ -24,6 +33,7 @@
def _fn_matches(fn, glob):
+ """Return whether the ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/lexers/__init__.py |
Add docstrings to improve collaboration |
import sys
from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from sphinx.util.nodes import nested_parse_with_titles
MODULEDOC = '''
.. module:: %s
%s
%s
'''
LEXERDOC = '''
.. class:: %s
:Short names: %s
:Filenames: %s
:MIME types: %s
... | --- +++ @@ -1,3 +1,13 @@+"""
+ pygments.sphinxext
+ ~~~~~~~~~~~~~~~~~~
+
+ Sphinx extension to generate automatic documentation of lexers,
+ formatters and filters.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import sys
@@ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/sphinxext.py |
Add standardized docstrings across the file | import json
import os
import sys
import tempfile
from contextlib import contextmanager
from os.path import abspath
from os.path import join as pjoin
from subprocess import STDOUT, check_call, check_output
from ._in_process import _in_proc_script_path
def write_json(obj, path, **kwargs):
with open(path, 'w', enco... | --- +++ @@ -21,11 +21,13 @@
class BackendUnavailable(Exception):
+ """Will be raised if the backend cannot be imported in the hook process."""
def __init__(self, traceback):
self.traceback = traceback
class BackendInvalid(Exception):
+ """Will be raised if the backend is invalid."""
de... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py |
Create documentation for each function signature | from __future__ import absolute_import
import inspect
from inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature
from typing import Any, Collection, Iterable, Optional, Tuple, Type, Union
from .console import Group, RenderableType
from .control import escape_control_codes
from .highlighter import Rep... | --- +++ @@ -15,11 +15,26 @@
def _first_paragraph(doc: str) -> str:
+ """Get the first paragraph from a docstring."""
paragraph, _, _ = doc.partition("\n\n")
return paragraph
class Inspect(JupyterMixin):
+ """A renderable to inspect any Python Object.
+
+ Args:
+ obj (Any): An object t... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/_inspect.py |
Document functions with clear intent |
import re
from io import TextIOWrapper
split_path_re = re.compile(r'[/\\ ]')
doctype_lookup_re = re.compile(r'''
<!DOCTYPE\s+(
[a-zA-Z_][a-zA-Z0-9]*
(?: \s+ # optional in HTML5
[a-zA-Z_][a-zA-Z0-9]*\s+
"[^"]*")?
)
[^>]*>
''', re.DOTALL | re.MULTILINE | re.VERBOSE)
tag_re = re.c... | --- +++ @@ -1,3 +1,12 @@+"""
+ pygments.util
+ ~~~~~~~~~~~~~
+
+ Utility functions.
+
+ :copyright: Copyright 2006-2024 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
import re
from io import TextIOWrapper
@@ -19,11 +28,20 @@
class ClassNotFound(ValueError):
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/pygments/util.py |
Add docstrings for better understanding |
import sys
# -------------------
# Character Detection
# -------------------
def _resolve_char_detection():
chardet = None
return chardet
chardet = _resolve_char_detection()
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = _ver[0] == 2
#: Python 3.x?
is_py3... | --- +++ @@ -1,3 +1,11 @@+"""
+requests.compat
+~~~~~~~~~~~~~~~
+
+This module previously handled import compatibility issues
+between Python 2 and Python 3. It remains for backwards
+compatibility until the next major version.
+"""
import sys
@@ -7,6 +15,7 @@
def _resolve_char_detection():
+ """Find support... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/compat.py |
Document functions with detailed explanations |
import codecs
import contextlib
import io
import os
import re
import socket
import struct
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from pip._vendor.urllib3.util import make_headers, parse_url
from . import certs
from .__version__ import __version__
# to_native_st... | --- +++ @@ -1,3 +1,10 @@+"""
+requests.utils
+~~~~~~~~~~~~~~
+
+This module provides utility functions that are used within Requests
+that are also useful for external consumption.
+"""
import codecs
import contextlib
@@ -105,6 +112,11 @@ return False
def proxy_bypass(host): # noqa
+ """Retur... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/utils.py |
Document all public functions with docstrings | import sys
from fractions import Fraction
from math import ceil
from typing import cast, List, Optional, Sequence
if sys.version_info >= (3, 8):
from typing import Protocol
else:
from pip._vendor.typing_extensions import Protocol # pragma: no cover
class Edge(Protocol):
size: Optional[int] = None
r... | --- +++ @@ -10,6 +10,7 @@
class Edge(Protocol):
+ """Any object that defines an edge (such as Layout)."""
size: Optional[int] = None
ratio: int = 1
@@ -17,6 +18,21 @@
def ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:
+ """Divide total space to satisfy size, ratio, and minimum_... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/_ratio.py |
Add docstrings explaining edge cases | import re
from .compat import builtin_str
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.compile(r"^[^:\s][^:\r\n]*$")
_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb"^\S[^\r\n]*$|^$")
_VALID_HEADER_VALUE_RE_STR = re.compile(r"^\S[^\r\n]*$|^$")
_HEADER_VALIDATORS_STR = (_VA... | --- +++ @@ -1,3 +1,10 @@+"""
+requests._internal_utils
+~~~~~~~~~~~~~~
+
+Provides utility functions that are consumed internally by Requests
+which depend on extremely few external helpers (such as compat)
+"""
import re
from .compat import builtin_str
@@ -16,6 +23,10 @@
def to_native_string(string, encoding="... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/requests/_internal_utils.py |
Add detailed documentation for each class | import platform
import re
from colorsys import rgb_to_hls
from enum import IntEnum
from functools import lru_cache
from typing import TYPE_CHECKING, NamedTuple, Optional, Tuple
from ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE
from .color_triplet import ColorTriplet
from .repr import Result, ... | --- +++ @@ -19,6 +19,7 @@
class ColorSystem(IntEnum):
+ """One of the 3 color system supported by terminals."""
STANDARD = 1
EIGHT_BIT = 2
@@ -33,6 +34,7 @@
class ColorType(IntEnum):
+ """Type of color stored in Color class."""
DEFAULT = 0
STANDARD = 1
@@ -284,6 +286,7 @@
class... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/color.py |
Write docstrings including parameters and return values |
import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
from ._extension import load_ipython_extension # noqa: F401
__all__ = ["get_console", "reconfigure", "print", "inspect", "print_json"]
if TYPE_CHECKING:
from .console import Console
# Global console used by alternative print
_conso... | --- +++ @@ -1,3 +1,4 @@+"""Rich text and beautiful formatting in the terminal."""
import os
from typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union
@@ -20,6 +21,12 @@
def get_console() -> "Console":
+ """Get a global :class:`~rich.console.Console` instance. This function is used when Rich requir... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/__init__.py |
Create docstrings for reusable components | import itertools
from .compat import collections_abc
class DirectedGraph(object):
def __init__(self):
self._vertices = set()
self._forwards = {} # <key> -> Set[<key>]
self._backwards = {} # <key> -> Set[<key>]
def __iter__(self):
return iter(self._vertices)
def __len_... | --- +++ @@ -4,6 +4,7 @@
class DirectedGraph(object):
+ """A graph structure with directed edges."""
def __init__(self):
self._vertices = set()
@@ -20,6 +21,7 @@ return key in self._vertices
def copy(self):
+ """Return a shallow copy of this graph."""
other = Directe... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/resolvelib/structs.py |
Generate docstrings with examples | class BaseReporter(object):
def starting(self):
def starting_round(self, index):
def ending_round(self, index, state):
def ending(self, state):
def adding_requirement(self, requirement, parent):
def resolving_conflicts(self, causes):
def rejecting_candidate(self, criterion, candidate)... | --- +++ @@ -1,17 +1,43 @@ class BaseReporter(object):
+ """Delegate class to provider progress reporting for the resolver."""
def starting(self):
+ """Called before the resolution actually starts."""
def starting_round(self, index):
+ """Called before each round of resolution starts.
+
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/resolvelib/reporters.py |
Help me document legacy Python code | from abc import ABC
class RichRenderable(ABC):
@classmethod
def __subclasshook__(cls, other: type) -> bool:
return hasattr(other, "__rich_console__") or hasattr(other, "__rich__")
if __name__ == "__main__": # pragma: no cover
from pip._vendor.rich.text import Text
t = Text()
print(isi... | --- +++ @@ -2,9 +2,19 @@
class RichRenderable(ABC):
+ """An abstract base class for Rich renderables.
+
+ Note that there is no need to extend this class, the intended use is to check if an
+ object supports the Rich renderable protocol. For example::
+
+ if isinstance(my_object, RichRenderable):
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/abc.py |
Add docstrings that explain logic | from pathlib import Path
from json import loads, dumps
from typing import Any, Callable, Optional, Union
from .text import Text
from .highlighter import JSONHighlighter, NullHighlighter
class JSON:
def __init__(
self,
json: str,
indent: Union[None, int, str] = 2,
highlight: bool ... | --- +++ @@ -7,6 +7,20 @@
class JSON:
+ """A renderable which pretty prints JSON.
+
+ Args:
+ json (str): JSON encoded data.
+ indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.
+ highlight (bool, optional): Enable highlighting. Defaults to True.
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/json.py |
Create Google-style docstrings for my code | # coding: utf-8
__all__ = ["decimal"]
from typing import Iterable, List, Optional, Tuple
def _to_str(
size: int,
suffixes: Iterable[str],
base: int,
*,
precision: Optional[int] = 1,
separator: Optional[str] = " ",
) -> str:
if size == 1:
return "1 byte"
elif size < base:
... | --- +++ @@ -1,4 +1,15 @@ # coding: utf-8
+"""Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2
+
+The functions declared in this module should cover the different
+use cases needed to generate a string representation of a file size
+using several different units. Since there... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/filesize.py |
Add well-formatted docstrings | import logging
from datetime import datetime
from logging import Handler, LogRecord
from pathlib import Path
from types import ModuleType
from typing import ClassVar, Iterable, List, Optional, Type, Union
from pip._vendor.rich._null_file import NullFile
from . import get_console
from ._log_render import FormatTimeCal... | --- +++ @@ -16,6 +16,37 @@
class RichHandler(Handler):
+ """A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.
+ The level is color coded, and the message is syntax highlighted.
+
+ Note:
+ Be careful when enabling console markup in log mes... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/logging.py |
Add docstrings following best practices | import re
from ast import literal_eval
from operator import attrgetter
from typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union
from ._emoji_replace import _emoji_replace
from .emoji import EmojiVariant
from .errors import MarkupError
from .style import Style
from .text import Span, Text
... | --- +++ @@ -18,6 +18,7 @@
class Tag(NamedTuple):
+ """A tag in console markup."""
name: str
"""The tag name. e.g. 'bold'."""
@@ -31,6 +32,7 @@
@property
def markup(self) -> str:
+ """Get the string representation of this tag."""
return (
f"[{self.name}]"
... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/markup.py |
Add documentation for all methods | import re
import sys
from contextlib import suppress
from typing import Iterable, NamedTuple, Optional
from .color import Color
from .style import Style
from .text import Text
re_ansi = re.compile(
r"""
(?:\x1b\](.*?)\x1b\\)|
(?:\x1b([(@-Z\\-_]|\[[0-?]*[ -/]*[@-~]))
""",
re.VERBOSE,
)
class _AnsiToken(Named... | --- +++ @@ -17,6 +17,7 @@
class _AnsiToken(NamedTuple):
+ """Result of ansi tokenized string."""
plain: str = ""
sgr: Optional[str] = ""
@@ -24,6 +25,14 @@
def _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:
+ """Tokenize a string in to plain text and ANSI codes.
+
+ Args:
+ ... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/ansi.py |
Create documentation for each function signature | from __future__ import annotations
import re
from functools import lru_cache
from typing import Callable
from ._cell_widths import CELL_WIDTHS
# Regex to match sequence of the most common character ranges
_is_single_cell_widths = re.compile("^[\u0020-\u006f\u00a0\u02ff\u0370-\u0482]*$").match
@lru_cache(4096)
def ... | --- +++ @@ -12,12 +12,31 @@
@lru_cache(4096)
def cached_cell_len(text: str) -> int:
+ """Get the number of cells required to display text.
+
+ This method always caches, which may use up a lot of memory. It is recommended to use
+ `cell_len` over this method.
+
+ Args:
+ text (str): Text to displa... | https://raw.githubusercontent.com/geekcomputers/Python/HEAD/venv/Lib/site-packages/pip/_vendor/rich/cells.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.