index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
35,898 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/resolver.py | 30,33 | 20,78 | resolve | ThreadedResolver | 33,74 | 33,74 | class ThreadedResolver(AbstractResolver):
"""Threaded resolver.
Uses an Executor for synchronous getaddrinfo() calls.
concurrent.futures.ThreadPoolExecutor is used by default.
"""
def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
self._loop = get_running_loop(lo... | class ThreadedResolver(AbstractResolver):
"""Threaded resolver.
Uses an Executor for synchronous getaddrinfo() calls.
concurrent.futures.ThreadPoolExecutor is used by default.
"""
def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None:
self._loop = get_running_loop(lo... | infos = await self._loop.getaddrinfo(
hostname,
port,
type=socket.SOCK_STREAM,
family=family,
flags=socket.AI_ADDRCONFIG,
)
hosts = []
for family, _, proto, _, address in infos:
if family == socket.AF_INET6:
... | infos = await self._loop.getaddrinfo(
hostname,
port,
type=socket.SOCK_STREAM,
family=family,
flags=socket.AI_ADDRCONFIG,
)
hosts = []
for family, _, proto, _, address in infos:
if family == socket.AF_INET6:
... | 131 | 169 | 414 | 583 | import asyncio
import socket
from typing import Any, Dict, List, Optional, Type, Union
from .abc import AbstractResolver
from .helpers import get_running_loop
__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver")
try:
import aiodns
# aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')... | import asyncio
import socket
from typing import Any, Dict, List, Optional, Type, Union
from .abc import AbstractResolver
from .helpers import get_running_loop
__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver")
try:
import aiodns
# aiodns_default = hasattr(aiodns.DNSResolver, 'gethostbyname')... |
35,899 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/streams.py | 77,78 | 57,88 | iter_chunks | AsyncStreamReaderMixin | 85,88 | 78,88 | class AsyncStreamReaderMixin:
def __aiter__(self) -> AsyncStreamIterator[bytes]:
return AsyncStreamIterator(self.readline) # type: ignore[attr-defined]
def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]:
"""Returns an asynchronous iterator that yields chunks of size n.
Pytho... | class AsyncStreamReaderMixin:
def __aiter__(self) -> AsyncStreamIterator[bytes]:
return AsyncStreamIterator(self.readline) # type: ignore[attr-defined]
def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]:
"""Returns an asynchronous iterator that yields chunks of size n.
Pytho... | return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type]
| """Yield chunks of data as they are received by the server.
The yielded objects are tuples
of (bytes, bool) as returned by the StreamReader.readchunk method.
Python-3.5 available for Python 3.5+ only
"""
return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-typ... | 5 | 326 | 28 | 354 | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... |
35,900 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/streams.py | 611,612 | 562,635 | read | DataQueue | 612,631 | 612,631 | class DataQueue(Generic[_T]):
"""DataQueue is a general-purpose blocking queue with one reader."""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._eof = False
self._waiter: Optional[asyncio.Future[None]] = None
self._exception: Optional[BaseE... | class DataQueue(Generic[_T]):
"""DataQueue is a general-purpose blocking queue with one reader."""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
self._loop = loop
self._eof = False
self._waiter: Optional[asyncio.Future[None]] = None
self._exception: Optional[BaseE... | if not self._buffer and not self._eof:
assert not self._waiter
self._waiter = self._loop.create_future()
try:
await self._waiter
except (asyncio.CancelledError, asyncio.TimeoutError):
self._waiter = None
raise
... | if not self._buffer and not self._eof:
assert not self._waiter
self._waiter = self._loop.create_future()
try:
await self._waiter
except (asyncio.CancelledError, asyncio.TimeoutError):
self._waiter = None
raise
... | 44 | 490 | 161 | 651 | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... |
35,901 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/streams.py | 555,556 | 507,559 | read_nowait | EmptyStreamReader | 556,559 | 556,559 | class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init]
def __init__(self) -> None:
pass
def exception(self) -> Optional[BaseException]:
return None
def set_exception(self, exc: BaseException) -> None:
pass
def on_eof(self, callback: Callable[[], None]) -> Non... | class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init]
def __init__(self) -> None:
pass
def exception(self) -> Optional[BaseException]:
return None
def set_exception(self, exc: BaseException) -> None:
pass
def on_eof(self, callback: Callable[[], None]) -> Non... | return b""
| return b""
| 2 | 404 | 10 | 414 | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... |
35,902 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/streams.py | 655,656 | 635,661 | read | FlowControlDataQueue | 656,661 | 656,661 | class FlowControlDataQueue(DataQueue[_T]):
"""FlowControlDataQueue resumes and pauses an underlying stream.
It is a destination for parsed data.
"""
def __init__(
self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop
) -> None:
super().__init__(loop=loop)
... | class FlowControlDataQueue(DataQueue[_T]):
"""FlowControlDataQueue resumes and pauses an underlying stream.
It is a destination for parsed data.
"""
def __init__(
self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop
) -> None:
super().__init__(loop=loop)
... | try:
return await super().read()
finally:
if self._size < self._limit and self._protocol._reading_paused:
self._protocol.resume_reading()
| try:
return await super().read()
finally:
if self._size < self._limit and self._protocol._reading_paused:
self._protocol.resume_reading()
| 12 | 204 | 52 | 256 | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... | import asyncio
import collections
import warnings
from typing import Awaitable, Callable, Deque, Generic, List, Optional, Tuple, TypeVar
from .base_protocol import BaseProtocol
from .helpers import BaseTimerContext, set_exception, set_result
from .log import internal_logger
from .typedefs import Final
__all__ = (
... |
35,904 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/tcp_helpers.py | 24,25 | 1,38 | tcp_nodelay | 25,38 | 25,38 | """Helper methods to tune a TCP connection"""
import asyncio
import socket
from contextlib import suppress
from typing import Optional # noqa
__all__ = ("tcp_keepalive", "tcp_nodelay")
if hasattr(socket, "SO_KEEPALIVE"):
def tcp_keepalive(transport: asyncio.Transport) -> None:
sock = transport.get_ext... | """Helper methods to tune a TCP connection"""
import asyncio
import socket
from contextlib import suppress
from typing import Optional # noqa
__all__ = ("tcp_keepalive", "tcp_nodelay")
if hasattr(socket, "SO_KEEPALIVE"):
def tcp_keepalive(transport: asyncio.Transport) -> None:
sock = transport.get_ext... | sock = transport.get_extra_info("socket")
if sock is None:
return
if sock.family not in (socket.AF_INET, socket.AF_INET6):
return
value = bool(value)
# socket may be closed already, on windows OSError get raised
with suppress(OSError):
sock.setsockopt(socket.IPPROTO_T... | sock = transport.get_extra_info("socket")
if sock is None:
return
if sock.family not in (socket.AF_INET, socket.AF_INET6):
return
value = bool(value)
# socket may be closed already, on windows OSError get raised
with suppress(OSError):
sock.setsockopt(socket.IPPROTO_T... | 34 | 222 | 132 | 354 | """Helper methods to tune a TCP connection"""
import asyncio
import socket
from contextlib import suppress
from typing import Optional # noqa
__all__ = ("tcp_keepalive", "tcp_nodelay")
if hasattr(socket, "SO_KEEPALIVE"):
def tcp_keepalive(transport: asyncio.Transport) -> None:
sock = transport.get_ext... | """Helper methods to tune a TCP connection"""
import asyncio
import socket
from contextlib import suppress
from typing import Optional # noqa
__all__ = ("tcp_keepalive", "tcp_nodelay")
if hasattr(socket, "SO_KEEPALIVE"):
def tcp_keepalive(transport: asyncio.Transport) -> None:
sock = transport.get_ext... | |
35,905 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/tracing.py | 420,421 | 337,473 | send_connection_queued_start | Trace | 421,425 | 421,425 | class Trace:
"""Internal dependency holder class.
Used to keep together the main dependencies used
at the moment of send a signal.
"""
def __init__(
self,
session: "ClientSession",
trace_config: TraceConfig,
trace_config_ctx: SimpleNamespace,
) -> None:
... | class Trace:
"""Internal dependency holder class.
Used to keep together the main dependencies used
at the moment of send a signal.
"""
def __init__(
self,
session: "ClientSession",
trace_config: TraceConfig,
trace_config_ctx: SimpleNamespace,
) -> None:
... | return await self._trace_config.on_connection_queued_start.send(
self._session, self._trace_config_ctx, TraceConnectionQueuedStartParams()
)
| return await self._trace_config.on_connection_queued_start.send(
self._session, self._trace_config_ctx, TraceConnectionQueuedStartParams()
)
| 7 | 1,404 | 51 | 1,455 | from types import SimpleNamespace
from typing import TYPE_CHECKING, Awaitable, Optional, Type, TypeVar
import attr
from aiosignal import Signal
from multidict import CIMultiDict
from yarl import URL
from .client_reqrep import ClientResponse
if TYPE_CHECKING: # pragma: no cover
from .client import ClientSession
... | from types import SimpleNamespace
from typing import TYPE_CHECKING, Awaitable, Optional, Type, TypeVar
import attr
from aiosignal import Signal
from multidict import CIMultiDict
from yarl import URL
from .client_reqrep import ClientResponse
if TYPE_CHECKING: # pragma: no cover
from .client import ClientSession
... |
35,906 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/tracing.py | 211,215 | 48,218 | on_request_headers_sent | TraceConfig | 215,218 | 215,218 | class TraceConfig:
"""First-class used to trace requests launched via ClientSession objects."""
def __init__(
self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace
) -> None:
self._on_request_start: Signal[
_SignalCallback[TraceRequestStartParams]
] = S... | class TraceConfig:
"""First-class used to trace requests launched via ClientSession objects."""
def __init__(
self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace
) -> None:
self._on_request_start: Signal[
_SignalCallback[TraceRequestStartParams]
] = S... | return self._on_request_headers_sent
| return self._on_request_headers_sent
| 2 | 1,856 | 17 | 1,873 | from types import SimpleNamespace
from typing import TYPE_CHECKING, Awaitable, Optional, Type, TypeVar
import attr
from aiosignal import Signal
from multidict import CIMultiDict
from yarl import URL
from .client_reqrep import ClientResponse
if TYPE_CHECKING: # pragma: no cover
from .client import ClientSession
... | from types import SimpleNamespace
from typing import TYPE_CHECKING, Awaitable, Optional, Type, TypeVar
import attr
from aiosignal import Signal
from multidict import CIMultiDict
from yarl import URL
from .client_reqrep import ClientResponse
if TYPE_CHECKING: # pragma: no cover
from .client import ClientSession
... |
35,909 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_app.py | 542,543 | 531,558 | _on_cleanup | CleanupContext | 543,558 | 543,558 | class CleanupContext(_CleanupContextBase):
def __init__(self) -> None:
super().__init__()
self._exits: List[AsyncIterator[None]] = []
async def _on_startup(self, app: Application) -> None:
for cb in self:
it = cb(app).__aiter__()
await it.__anext__()
... | class CleanupContext(_CleanupContextBase):
def __init__(self) -> None:
super().__init__()
self._exits: List[AsyncIterator[None]] = []
async def _on_startup(self, app: Application) -> None:
for cb in self:
it = cb(app).__aiter__()
await it.__anext__()
... | errors = []
for it in reversed(self._exits):
try:
await it.__anext__()
except StopAsyncIteration:
pass
except Exception as exc:
errors.append(exc)
else:
errors.append(RuntimeError(f"{it!r} has... | errors = []
for it in reversed(self._exits):
try:
await it.__anext__()
except StopAsyncIteration:
pass
except Exception as exc:
errors.append(exc)
else:
errors.append(RuntimeError(f"{it!r} has... | 41 | 139 | 144 | 283 | import asyncio
import logging
import warnings
from functools import partial, update_wrapper
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
... | import asyncio
import logging
import warnings
from functools import partial, update_wrapper
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
... |
35,910 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_app.py | 520,522 | 519,525 | exceptions | CleanupError | 522,525 | 522,525 | class CleanupError(RuntimeError):
@property
def exceptions(self) -> List[BaseException]:
FILL_FUNC_BODY | class CleanupError(RuntimeError):
@property
def exceptions(self) -> List[BaseException]:
FILL_FUNC_BODY | return cast(List[BaseException], self.args[1])
| return cast(List[BaseException], self.args[1])
| 3 | 37 | 21 | 58 | import asyncio
import logging
import warnings
from functools import partial, update_wrapper
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
... | import asyncio
import logging
import warnings
from functools import partial, update_wrapper
from typing import (
TYPE_CHECKING,
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
Iterable,
Iterator,
List,
Mapping,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
... |
35,913 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_middlewares.py | 41,48 | 1,120 | normalize_path_middleware | 76,113 | 48,113 | import re
from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar
from .typedefs import Handler
from .web_exceptions import HTTPPermanentRedirect, _HTTPMove
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middlew... | import re
from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar
from .typedefs import Handler
from .web_exceptions import HTTPPermanentRedirect, _HTTPMove
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middlew... | correct_configuration = not (append_slash and remove_slash)
assert correct_configuration, "Cannot both remove and append slash"
@middleware
async def impl(request: Request, handler: Handler) -> StreamResponse:
if isinstance(request.match_info.route, SystemRoute):
paths_to_check = []... | """Factory for producing a middleware that normalizes the path of a request.
Normalizing means:
- Add or remove a trailing slash to the path.
- Double slashes are replaced by one.
The middleware returns as soon as it finds a path that resolves
correctly. The order if both merge and app... | 116 | 781 | 464 | 1,245 | import re
from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar
from .typedefs import Handler
from .web_exceptions import HTTPPermanentRedirect, _HTTPMove
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middlew... | import re
from typing import TYPE_CHECKING, Awaitable, Callable, Tuple, Type, TypeVar
from .typedefs import Handler
from .web_exceptions import HTTPPermanentRedirect, _HTTPMove
from .web_request import Request
from .web_response import StreamResponse
from .web_urldispatcher import SystemRoute
__all__ = (
"middlew... | |
35,919 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_routedef.py | 50,52 | 49,55 | register | AbstractRouteDef | 52,55 | 52,55 | class AbstractRouteDef(abc.ABC):
@abc.abstractmethod
def register(self, router: UrlDispatcher) -> List[AbstractRoute]:
FILL_FUNC_BODY | class AbstractRouteDef(abc.ABC):
@abc.abstractmethod
def register(self, router: UrlDispatcher) -> List[AbstractRoute]:
FILL_FUNC_BODY | pass # pragma: no cover
| pass # pragma: no cover
| 5 | 50 | 15 | 65 | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... |
35,920 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_routedef.py | 73,74 | 58,83 | register | RouteDef | 74,83 | 74,83 | @attr.s(auto_attribs=True, frozen=True, repr=False, slots=True)
class RouteDef(AbstractRouteDef):
method: str
path: str
handler: _HandlerType
kwargs: Dict[str, Any]
def __repr__(self) -> str:
info = []
for name, value in sorted(self.kwargs.items()):
info.append(f", {name... | @attr.s(auto_attribs=True, frozen=True, repr=False, slots=True)
class RouteDef(AbstractRouteDef):
method: str
path: str
handler: _HandlerType
kwargs: Dict[str, Any]
def __repr__(self) -> str:
info = []
for name, value in sorted(self.kwargs.items()):
info.append(f", {name... | if self.method in hdrs.METH_ALL:
reg = getattr(router, "add_" + self.method.lower())
return [reg(self.path, self.handler, **self.kwargs)]
else:
return [
router.add_route(self.method, self.path, self.handler, **self.kwargs)
]
| if self.method in hdrs.METH_ALL:
reg = getattr(router, "add_" + self.method.lower())
return [reg(self.path, self.handler, **self.kwargs)]
else:
return [
router.add_route(self.method, self.path, self.handler, **self.kwargs)
]
| 22 | 213 | 101 | 314 | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... |
35,921 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_routedef.py | 185,186 | 155,217 | inner | RouteTableDef | 186,189 | 186,189 | class RouteTableDef(Sequence[AbstractRouteDef]):
"""Route definition table"""
def __init__(self) -> None:
self._items: List[AbstractRouteDef] = []
def __repr__(self) -> str:
return f"<RouteTableDef count={len(self._items)}>"
@overload
def __getitem__(self, index: int) -> AbstractR... | class RouteTableDef(Sequence[AbstractRouteDef]):
"""Route definition table"""
def __init__(self) -> None:
self._items: List[AbstractRouteDef] = []
def __repr__(self) -> str:
return f"<RouteTableDef count={len(self._items)}>"
@overload
def __getitem__(self, index: int) -> AbstractR... | self._items.append(RouteDef(method, path, handler, kwargs))
return handler
| self._items.append(RouteDef(method, path, handler, kwargs))
return handler
| 6 | 698 | 29 | 727 | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... |
35,922 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_routedef.py | 97,98 | 83,103 | register | StaticDef | 98,103 | 98,103 | @attr.s(auto_attribs=True, frozen=True, repr=False, slots=True)
class StaticDef(AbstractRouteDef):
prefix: str
path: PathLike
kwargs: Dict[str, Any]
def __repr__(self) -> str:
info = []
for name, value in sorted(self.kwargs.items()):
info.append(f", {name}={value!r}")
... | @attr.s(auto_attribs=True, frozen=True, repr=False, slots=True)
class StaticDef(AbstractRouteDef):
prefix: str
path: PathLike
kwargs: Dict[str, Any]
def __repr__(self) -> str:
info = []
for name, value in sorted(self.kwargs.items()):
info.append(f", {name}={value!r}")
... | resource = router.add_static(self.prefix, self.path, **self.kwargs)
routes = resource.get_info().get("routes", {})
return list(routes.values())
| resource = router.add_static(self.prefix, self.path, **self.kwargs)
routes = resource.get_info().get("routes", {})
return list(routes.values())
| 11 | 194 | 57 | 251 | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... | import abc
import os # noqa
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterator,
List,
Optional,
Sequence,
Type,
Union,
overload,
)
import attr
from . import hdrs
from .abc import AbstractView
from .typedefs import Handler, PathLike
if TYPE_CHECKING: # prag... |
35,924 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 364,366 | 348,382 | app | AppRunner | 366,368 | 366,368 | class AppRunner(BaseRunner):
"""Web Application runner"""
__slots__ = ("_app",)
def __init__(
self, app: Application, *, handle_signals: bool = False, **kwargs: Any
) -> None:
super().__init__(handle_signals=handle_signals, **kwargs)
if not isinstance(app, Application):
... | class AppRunner(BaseRunner):
"""Web Application runner"""
__slots__ = ("_app",)
def __init__(
self, app: Application, *, handle_signals: bool = False, **kwargs: Any
) -> None:
super().__init__(handle_signals=handle_signals, **kwargs)
if not isinstance(app, Application):
... | return self._app
| return self._app
| 2 | 309 | 9 | 318 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,925 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 312,313 | 239,327 | _reg_site | BaseRunner | 313,317 | 313,317 | class BaseRunner(ABC):
__slots__ = ("_handle_signals", "_kwargs", "_server", "_sites")
def __init__(self, *, handle_signals: bool = False, **kwargs: Any) -> None:
self._handle_signals = handle_signals
self._kwargs = kwargs
self._server: Optional[Server] = None
self._sites: List[... | class BaseRunner(ABC):
__slots__ = ("_handle_signals", "_kwargs", "_server", "_sites")
def __init__(self, *, handle_signals: bool = False, **kwargs: Any) -> None:
self._handle_signals = handle_signals
self._kwargs = kwargs
self._server: Optional[Server] = None
self._sites: List[... | if site in self._sites:
raise RuntimeError(f"Site {site} is already registered in runner {self}")
self._sites.append(site)
| if site in self._sites:
raise RuntimeError(f"Site {site} is already registered in runner {self}")
self._sites.append(site)
| 14 | 832 | 47 | 879 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,926 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 63,65 | 39,82 | start | BaseSite | 65,67 | 65,67 | class BaseSite(ABC):
__slots__ = ("_runner", "_shutdown_timeout", "_ssl_context", "_backlog", "_server")
def __init__(
self,
runner: "BaseRunner",
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
... | class BaseSite(ABC):
__slots__ = ("_runner", "_shutdown_timeout", "_ssl_context", "_backlog", "_server")
def __init__(
self,
runner: "BaseRunner",
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
... | self._runner._reg_site(self)
| self._runner._reg_site(self)
| 1 | 401 | 15 | 416 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,927 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 187,188 | 167,198 | start | NamedPipeSite | 188,198 | 188,198 | class NamedPipeSite(BaseSite):
__slots__ = ("_path",)
def __init__(
self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0
) -> None:
loop = asyncio.get_event_loop()
if not isinstance(
loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
... | class NamedPipeSite(BaseSite):
__slots__ = ("_path",)
def __init__(
self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0
) -> None:
loop = asyncio.get_event_loop()
if not isinstance(
loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
... | await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
_server = await loop.start_serving_pipe( # type: ignore[attr-defined]
server, self._path
)
self._server = _server[0]
| await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
_server = await loop.start_serving_pipe( # type: ignore[attr-defined]
server, self._path
)
self._server = _server[0]
| 26 | 204 | 94 | 298 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,928 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 341,342 | 327,348 | _make_server | ServerRunner | 342,344 | 342,344 | class ServerRunner(BaseRunner):
"""Low-level web server runner"""
__slots__ = ("_web_server",)
def __init__(
self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any
) -> None:
super().__init__(handle_signals=handle_signals, **kwargs)
self._web_server = web_serv... | class ServerRunner(BaseRunner):
"""Low-level web server runner"""
__slots__ = ("_web_server",)
def __init__(
self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any
) -> None:
super().__init__(handle_signals=handle_signals, **kwargs)
self._web_server = web_serv... | return self._web_server
| return self._web_server
| 2 | 166 | 11 | 177 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,929 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 229,230 | 198,239 | start | SockSite | 230,239 | 230,239 | class SockSite(BaseSite):
__slots__ = ("_sock", "_name")
def __init__(
self,
runner: "BaseRunner",
sock: socket.socket,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
super().__init_... | class SockSite(BaseSite):
__slots__ = ("_sock", "_name")
def __init__(
self,
runner: "BaseRunner",
sock: socket.socket,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
super().__init_... | await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
self._server = await loop.create_server(
server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog
)
| await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
self._server = await loop.create_server(
server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog
)
| 22 | 316 | 91 | 407 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,930 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 110,112 | 82,132 | name | TCPSite | 112,116 | 112,116 | class TCPSite(BaseSite):
__slots__ = ("_host", "_port", "_reuse_address", "_reuse_port")
def __init__(
self,
runner: "BaseRunner",
host: Optional[str] = None,
port: Optional[int] = None,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext]... | class TCPSite(BaseSite):
__slots__ = ("_host", "_port", "_reuse_address", "_reuse_port")
def __init__(
self,
runner: "BaseRunner",
host: Optional[str] = None,
port: Optional[int] = None,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext]... | scheme = "https" if self._ssl_context else "http"
host = "0.0.0.0" if self._host is None else self._host
return str(URL.build(scheme=scheme, host=host, port=self._port))
| scheme = "https" if self._ssl_context else "http"
host = "0.0.0.0" if self._host is None else self._host
return str(URL.build(scheme=scheme, host=host, port=self._port))
| 20 | 423 | 68 | 491 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,931 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_runner.py | 157,158 | 132,167 | start | UnixSite | 158,167 | 158,167 | class UnixSite(BaseSite):
__slots__ = ("_path",)
def __init__(
self,
runner: "BaseRunner",
path: str,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
super().__init__(
run... | class UnixSite(BaseSite):
__slots__ = ("_path",)
def __init__(
self,
runner: "BaseRunner",
path: str,
*,
shutdown_timeout: float = 60.0,
ssl_context: Optional[SSLContext] = None,
backlog: int = 128,
) -> None:
super().__init__(
run... | await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
self._server = await loop.create_unix_server(
server, self._path, ssl=self._ssl_context, backlog=self._backlog
)
| await super().start()
loop = asyncio.get_event_loop()
server = self._runner.server
assert server is not None
self._server = await loop.create_unix_server(
server, self._path, ssl=self._ssl_context, backlog=self._backlog
)
| 22 | 221 | 90 | 311 | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... | import asyncio
import signal
import socket
from abc import ABC, abstractmethod
from typing import Any, List, Optional, Set
from yarl import URL
from .web_app import Application
from .web_server import Server
try:
from ssl import SSLContext
except ImportError:
SSLContext = object # type: ignore[misc,assignme... |
35,932 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/aiohttp/web_server.py | 56,57 | 15,63 | shutdown | Server | 57,61 | 57,61 | class Server:
def __init__(
self,
handler: _RequestHandler,
*,
request_factory: Optional[_RequestFactory] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any
) -> None:
self._loop = get_running_loop(loop)
self._connections: Dict... | class Server:
def __init__(
self,
handler: _RequestHandler,
*,
request_factory: Optional[_RequestFactory] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any
) -> None:
self._loop = get_running_loop(loop)
self._connections: Dict... | coros = [conn.shutdown(timeout) for conn in self._connections]
await asyncio.gather(*coros)
self._connections.clear()
| coros = [conn.shutdown(timeout) for conn in self._connections]
await asyncio.gather(*coros)
self._connections.clear()
| 10 | 422 | 46 | 468 | """Low level HTTP server."""
import asyncio
from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa
from .abc import AbstractStreamWriter
from .helpers import get_running_loop
from .http_parser import RawRequestMessage
from .streams import StreamReader
from .web_protocol import RequestHandler, _Reque... | """Low level HTTP server."""
import asyncio
from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa
from .abc import AbstractStreamWriter
from .helpers import get_running_loop
from .http_parser import RawRequestMessage
from .streams import StreamReader
from .web_protocol import RequestHandler, _Reque... |
35,934 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_cmp.py | 118,119 | 1,156 | _make_operator | 122,141 | 119,141 | # SPDX-License-Identifier: MIT
import functools
import types
from ._make import _make_ne
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
""... | # SPDX-License-Identifier: MIT
import functools
import types
from ._make import _make_ne
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
""... |
def method(self, other):
if not self._is_comparable_to(other):
return NotImplemented
result = func(self.value, other.value)
if result is NotImplemented:
return NotImplemented
return result
method.__name__ = f"__{name}__"
method.__doc__ = (
... | """
Create operator method.
"""
def method(self, other):
if not self._is_comparable_to(other):
return NotImplemented
result = func(self.value, other.value)
if result is NotImplemented:
return NotImplemented
return result
method.__name__ = f... | 36 | 1,161 | 145 | 1,306 | # SPDX-License-Identifier: MIT
import functools
import types
from ._make import _make_ne
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
""... | # SPDX-License-Identifier: MIT
import functools
import types
from ._make import _make_ne
_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
def cmp_using(
eq=None,
lt=None,
le=None,
gt=None,
ge=None,
require_same_type=True,
class_name="Comparable",
):
""... | |
35,935 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_cmp.pyi | 5,13 | 1,14 | cmp_using | 13,14 | 13,14 | from typing import Any, Callable, Optional, Type
_CompareWithType = Callable[[Any, Any], bool]
def cmp_using(
eq: Optional[_CompareWithType] = ...,
lt: Optional[_CompareWithType] = ...,
le: Optional[_CompareWithType] = ...,
gt: Optional[_CompareWithType] = ...,
ge: Optional[_CompareWithType] = ...... | from typing import Any, Callable, Optional, Type
_CompareWithType = Callable[[Any, Any], bool]
def cmp_using(
eq: Optional[_CompareWithType] = ...,
lt: Optional[_CompareWithType] = ...,
le: Optional[_CompareWithType] = ...,
gt: Optional[_CompareWithType] = ...,
ge: Optional[_CompareWithType] = ...... | ) -> Type: ...
| ) -> Type: ...
| 4 | 140 | 8 | 148 | from typing import Any, Callable, Optional, Type
_CompareWithType = Callable[[Any, Any], bool]
def cmp_using(
eq: Optional[_CompareWithType] = ...,
lt: Optional[_CompareWithType] = ...,
le: Optional[_CompareWithType] = ...,
gt: Optional[_CompareWithType] = ...,
ge: Optional[_CompareWithType] = ...... | from typing import Any, Callable, Optional, Type
_CompareWithType = Callable[[Any, Any], bool]
def cmp_using(
eq: Optional[_CompareWithType] = ...,
lt: Optional[_CompareWithType] = ...,
le: Optional[_CompareWithType] = ...,
gt: Optional[_CompareWithType] = ...,
ge: Optional[_CompareWithType] = ...... | |
35,936 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_config.py | 9,10 | 1,32 | set_run_validators | 17,23 | 10,23 | # SPDX-License-Identifier: MIT
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
FILL_FUNC_BODYdef get_run_validators():
"""
Return whether or not validators are run.
.. deprecated:: 21.3.0 It will not be removed, but it also will not be
... | # SPDX-License-Identifier: MIT
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
"""
Set whether or not validators are run. By default, they are run.
.. deprecated:: 21.3.0 It will not be removed, but it also will not be
moved to new ``... | if not isinstance(run, bool):
raise TypeError("'run' must be bool.")
global _run_validators
_run_validators = run
| """
Set whether or not validators are run. By default, they are run.
.. deprecated:: 21.3.0 It will not be removed, but it also will not be
moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()`
instead.
"""
if not isinstance(run, bool):
raise TypeError("'r... | 14 | 233 | 49 | 282 | # SPDX-License-Identifier: MIT
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
FILL_FUNC_BODYdef get_run_validators():
"""
Return whether or not validators are run.
.. deprecated:: 21.3.0 It will not be removed, but it also will not be
... | # SPDX-License-Identifier: MIT
__all__ = ["set_run_validators", "get_run_validators"]
_run_validators = True
def set_run_validators(run):
"""
Set whether or not validators are run. By default, they are run.
.. deprecated:: 21.3.0 It will not be removed, but it also will not be
moved to new ``... | |
35,938 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_next_gen.py | 162,178 | 1,227 | field | 184,201 | 178,201 | # SPDX-License-Identifier: MIT
"""
These are keyword-only APIs that call `attr.s` and `attr.ib` with different
default values.
"""
from functools import partial
from . import setters
from ._funcs import asdict as _asdict
from ._funcs import astuple as _astuple
from ._make import (
NOTHING,
_frozen_setattrs,... | # SPDX-License-Identifier: MIT
"""
These are keyword-only APIs that call `attr.s` and `attr.ib` with different
default values.
"""
from functools import partial
from . import setters
from ._funcs import asdict as _asdict
from ._funcs import astuple as _astuple
from ._make import (
NOTHING,
_frozen_setattrs,... | return attrib(
default=default,
validator=validator,
repr=repr,
hash=hash,
init=init,
metadata=metadata,
converter=converter,
factory=factory,
kw_only=kw_only,
eq=eq,
order=order,
on_setattr=on_setattr,
alias=ali... | """
Identical to `attr.ib`, except keyword-only and with some arguments
removed.
.. versionadded:: 20.1.0
"""
return attrib(
default=default,
validator=validator,
repr=repr,
hash=hash,
init=init,
metadata=metadata,
converter=converter,
... | 16 | 1,844 | 122 | 1,966 | # SPDX-License-Identifier: MIT
"""
These are keyword-only APIs that call `attr.s` and `attr.ib` with different
default values.
"""
from functools import partial
from . import setters
from ._funcs import asdict as _asdict
from ._funcs import astuple as _astuple
from ._make import (
NOTHING,
_frozen_setattrs,... | # SPDX-License-Identifier: MIT
"""
These are keyword-only APIs that call `attr.s` and `attr.ib` with different
default values.
"""
from functools import partial
from . import setters
from ._funcs import asdict as _asdict
from ._funcs import astuple as _astuple
from ._make import (
NOTHING,
_frozen_setattrs,... | |
35,939 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_version_info.py | 38,40 | 10,87 | _from_version_string | VersionInfo | 43,51 | 40,51 | @total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo:
"""
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") < (19, 1, 1)
True
>>> vi = attr.Versi... | @total_ordering
@attrs(eq=False, order=False, slots=True, frozen=True)
class VersionInfo:
"""
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") < (19, 1, 1)
True
>>> vi = attr.Versi... | v = s.split(".")
if len(v) == 3:
v.append("final")
return cls(
year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]
)
| """
Parse *s* and return a _VersionInfo.
"""
v = s.split(".")
if len(v) == 3:
v.append("final")
return cls(
year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3]
)
| 15 | 606 | 82 | 688 | # SPDX-License-Identifier: MIT
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:
"""
A version object that can be compared to tuple of length 1--4:
>>> attr.Version... | # SPDX-License-Identifier: MIT
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:
"""
A version object that can be compared to tuple of length 1--4:
>>> attr.Version... |
35,940 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/_version_info.pyi | 2,3 | 1,10 | year | VersionInfo | 3,4 | 3,4 | class VersionInfo:
@property
FILL_FUNC_BODY @property
def minor(self) -> int: ...
@property
def micro(self) -> int: ...
@property
def releaselevel(self) -> str: ...
| class VersionInfo:
@property
FILL_FUNC_BODY @property
def minor(self) -> int: ...
@property
def micro(self) -> int: ...
@property
def releaselevel(self) -> str: ...
| def year(self) -> int: ...
| def year(self) -> int: ...
| 5 | 68 | 13 | 81 | class VersionInfo:
@property
FILL_FUNC_BODY @property
def minor(self) -> int: ...
@property
def micro(self) -> int: ...
@property
def releaselevel(self) -> str: ...
| class VersionInfo:
@property
FILL_FUNC_BODY @property
def minor(self) -> int: ...
@property
def micro(self) -> int: ...
@property
def releaselevel(self) -> str: ...
|
35,941 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/converters.py | 22,23 | 1,145 | optional | 35,54 | 23,54 | # SPDX-License-Identifier: MIT
"""
Commonly useful converters.
"""
import typing
from ._compat import _AnnotationExtractor
from ._make import NOTHING, Factory, pipe
__all__ = [
"default_if_none",
"optional",
"pipe",
"to_bool",
]
def optional(converter):
FILL_FUNC_BODYdef default_if_none(default=... | # SPDX-License-Identifier: MIT
"""
Commonly useful converters.
"""
import typing
from ._compat import _AnnotationExtractor
from ._make import NOTHING, Factory, pipe
__all__ = [
"default_if_none",
"optional",
"pipe",
"to_bool",
]
def optional(converter):
"""
A converter that allows an att... |
def optional_converter(val):
if val is None:
return None
return converter(val)
xtr = _AnnotationExtractor(converter)
t = xtr.get_first_param_type()
if t:
optional_converter.__annotations__["val"] = typing.Optional[t]
rt = xtr.get_return_type()
if rt:
... | """
A converter that allows an attribute to be optional. An optional attribute
is one which can be set to ``None``.
Type annotations will be inferred from the wrapped converter's, if it
has any.
:param callable converter: the converter that is used for non-``None``
values.
.. vers... | 31 | 1,052 | 157 | 1,209 | # SPDX-License-Identifier: MIT
"""
Commonly useful converters.
"""
import typing
from ._compat import _AnnotationExtractor
from ._make import NOTHING, Factory, pipe
__all__ = [
"default_if_none",
"optional",
"pipe",
"to_bool",
]
def optional(converter):
FILL_FUNC_BODYdef default_if_none(default=... | # SPDX-License-Identifier: MIT
"""
Commonly useful converters.
"""
import typing
from ._compat import _AnnotationExtractor
from ._make import NOTHING, Factory, pipe
__all__ = [
"default_if_none",
"optional",
"pipe",
"to_bool",
]
def optional(converter):
"""
A converter that allows an att... | |
35,942 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/converters.pyi | 13,13 | 1,14 | to_bool | 13,14 | 13,14 | from typing import Callable, TypeVar, overload
from . import _ConverterType
_T = TypeVar("_T")
def pipe(*validators: _ConverterType) -> _ConverterType: ...
def optional(converter: _ConverterType) -> _ConverterType: ...
@overload
def default_if_none(default: _T) -> _ConverterType: ...
@overload
def default_if_none(*,... | from typing import Callable, TypeVar, overload
from . import _ConverterType
_T = TypeVar("_T")
def pipe(*validators: _ConverterType) -> _ConverterType: ...
def optional(converter: _ConverterType) -> _ConverterType: ...
@overload
def default_if_none(default: _T) -> _ConverterType: ...
@overload
def default_if_none(*,... | def to_bool(val: str) -> bool: ...
| def to_bool(val: str) -> bool: ...
| 6 | 131 | 16 | 147 | from typing import Callable, TypeVar, overload
from . import _ConverterType
_T = TypeVar("_T")
def pipe(*validators: _ConverterType) -> _ConverterType: ...
def optional(converter: _ConverterType) -> _ConverterType: ...
@overload
def default_if_none(default: _T) -> _ConverterType: ...
@overload
def default_if_none(*,... | from typing import Callable, TypeVar, overload
from . import _ConverterType
_T = TypeVar("_T")
def pipe(*validators: _ConverterType) -> _ConverterType: ...
def optional(converter: _ConverterType) -> _ConverterType: ...
@overload
def default_if_none(default: _T) -> _ConverterType: ...
@overload
def default_if_none(*,... | |
35,943 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/filters.py | 20,21 | 1,52 | include | 29,37 | 21,37 | # SPDX-License-Identifier: MIT
"""
Commonly useful filters for `attr.asdict`.
"""
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isinstance(cls, type)),
frozenset(cls for... | # SPDX-License-Identifier: MIT
"""
Commonly useful filters for `attr.asdict`.
"""
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isinstance(cls, type)),
frozenset(cls for... | cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_
| """
Include *what*.
:param what: What to include.
:type what: `list` of `type` or `attrs.Attribute`\\ s
:rtype: `callable`
"""
cls, attrs = _split_what(what)
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs
return include_
| 17 | 306 | 56 | 362 | # SPDX-License-Identifier: MIT
"""
Commonly useful filters for `attr.asdict`.
"""
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isinstance(cls, type)),
frozenset(cls for... | # SPDX-License-Identifier: MIT
"""
Commonly useful filters for `attr.asdict`.
"""
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isinstance(cls, type)),
frozenset(cls for... | |
35,944 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/filters.pyi | 5,5 | 1,7 | include | 5,6 | 5,6 | from typing import Any, Union
from . import Attribute, _FilterType
FILL_FUNC_BODYdef exclude(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| from typing import Any, Union
from . import Attribute, _FilterType
FILL_FUNC_BODYdef exclude(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| def include(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| def include(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| 7 | 54 | 26 | 80 | from typing import Any, Union
from . import Attribute, _FilterType
FILL_FUNC_BODYdef exclude(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| from typing import Any, Union
from . import Attribute, _FilterType
FILL_FUNC_BODYdef exclude(*what: Union[type, Attribute[Any]]) -> _FilterType[Any]: ...
| |
35,945 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/setters.py | 39,40 | 1,74 | validate | 45,57 | 40,57 | # SPDX-License-Identifier: MIT
"""
Commonly used hooks for on_setattr.
"""
from . import _config
from .exceptions import FrozenAttributeError
def pipe(*setters):
"""
Run all *setters* and return the return value of the last one.
.. versionadded:: 20.1.0
"""
def wrapped_pipe(instance, attrib, ... | # SPDX-License-Identifier: MIT
"""
Commonly used hooks for on_setattr.
"""
from . import _config
from .exceptions import FrozenAttributeError
def pipe(*setters):
"""
Run all *setters* and return the return value of the last one.
.. versionadded:: 20.1.0
"""
def wrapped_pipe(instance, attrib, ... | if _config._run_validators is False:
return new_value
v = attrib.validator
if not v:
return new_value
v(instance, attrib, new_value)
return new_value
| """
Run *attrib*'s validator on *new_value* if it has one.
.. versionadded:: 20.1.0
"""
if _config._run_validators is False:
return new_value
v = attrib.validator
if not v:
return new_value
v(instance, attrib, new_value)
return new_value
| 19 | 420 | 76 | 496 | # SPDX-License-Identifier: MIT
"""
Commonly used hooks for on_setattr.
"""
from . import _config
from .exceptions import FrozenAttributeError
def pipe(*setters):
"""
Run all *setters* and return the return value of the last one.
.. versionadded:: 20.1.0
"""
def wrapped_pipe(instance, attrib, ... | # SPDX-License-Identifier: MIT
"""
Commonly used hooks for on_setattr.
"""
from . import _config
from .exceptions import FrozenAttributeError
def pipe(*setters):
"""
Run all *setters* and return the return value of the last one.
.. versionadded:: 20.1.0
"""
def wrapped_pipe(instance, attrib, ... | |
35,946 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/setters.pyi | 11,11 | 1,20 | validate | 11,12 | 11,12 | from typing import Any, NewType, NoReturn, TypeVar
from . import Attribute, _OnSetAttrType
_T = TypeVar("_T")
def frozen(
instance: Any, attribute: Attribute[Any], new_value: Any
) -> NoReturn: ...
def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ...
FILL_FUNC_BODY
# convert is allowed to return Any, becaus... | from typing import Any, NewType, NoReturn, TypeVar
from . import Attribute, _OnSetAttrType
_T = TypeVar("_T")
def frozen(
instance: Any, attribute: Attribute[Any], new_value: Any
) -> NoReturn: ...
def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ...
FILL_FUNC_BODY
# convert is allowed to return Any, becaus... | def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ...
| def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ...
| 10 | 175 | 30 | 205 | from typing import Any, NewType, NoReturn, TypeVar
from . import Attribute, _OnSetAttrType
_T = TypeVar("_T")
def frozen(
instance: Any, attribute: Attribute[Any], new_value: Any
) -> NoReturn: ...
def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ...
FILL_FUNC_BODY
# convert is allowed to return Any, becaus... | from typing import Any, NewType, NoReturn, TypeVar
from . import Attribute, _OnSetAttrType
_T = TypeVar("_T")
def frozen(
instance: Any, attribute: Attribute[Any], new_value: Any
) -> NoReturn: ...
def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ...
FILL_FUNC_BODY
# convert is allowed to return Any, becaus... | |
35,948 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/attr/validators.pyi | 76,76 | 1,87 | le | 76,77 | 76,77 | from typing import (
Any,
AnyStr,
Callable,
Container,
ContextManager,
Iterable,
List,
Mapping,
Match,
Optional,
Pattern,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from . import _ValidatorType
from . import _ValidatorArgType
_T = TypeVar("_T")
_T1 = TypeV... | from typing import (
Any,
AnyStr,
Callable,
Container,
ContextManager,
Iterable,
List,
Mapping,
Match,
Optional,
Pattern,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from . import _ValidatorType
from . import _ValidatorArgType
_T = TypeVar("_T")
_T1 = TypeV... | def le(val: _T) -> _ValidatorType[_T]: ...
| def le(val: _T) -> _ValidatorType[_T]: ...
| 6 | 954 | 20 | 974 | from typing import (
Any,
AnyStr,
Callable,
Container,
ContextManager,
Iterable,
List,
Mapping,
Match,
Optional,
Pattern,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from . import _ValidatorType
from . import _ValidatorArgType
_T = TypeVar("_T")
_T1 = TypeV... | from typing import (
Any,
AnyStr,
Callable,
Container,
ContextManager,
Iterable,
List,
Mapping,
Match,
Optional,
Pattern,
Tuple,
Type,
TypeVar,
Union,
overload,
)
from . import _ValidatorType
from . import _ValidatorArgType
_T = TypeVar("_T")
_T1 = TypeV... | |
35,952 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/legacy.py | 8,11 | 1,55 | detect | 22,55 | 11,55 | from typing import Any, Dict, Optional, Union
from warnings import warn
from .api import from_bytes
from .constant import CHARDET_CORRESPONDENCE
def detect(
byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
) -> Dict[str, Optional[Union[str, float]]]:
FILL_FUNC_BODY | from typing import Any, Dict, Optional, Union
from warnings import warn
from .api import from_bytes
from .constant import CHARDET_CORRESPONDENCE
def detect(
byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
) -> Dict[str, Optional[Union[str, float]]]:
"""
chardet legacy method
Detect... | if len(kwargs):
warn(
f"charset-normalizer disregard arguments '{','.join(list(kwargs.keys()))}' in legacy function detect()"
)
if not isinstance(byte_str, (bytearray, bytes)):
raise TypeError( # pragma: nocover
"Expected object of type bytes or bytearray, got: ... | """
chardet legacy method
Detect the encoding of the given byte string. It should be mostly backward-compatible.
Encoding name will match Chardet own writing whenever possible. (Not on encoding name unsupported by it)
This function is deprecated and should be used to migrate your project easily, con... | 141 | 237 | 405 | 642 | from typing import Any, Dict, Optional, Union
from warnings import warn
from .api import from_bytes
from .constant import CHARDET_CORRESPONDENCE
def detect(
byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
) -> Dict[str, Optional[Union[str, float]]]:
FILL_FUNC_BODY | from typing import Any, Dict, Optional, Union
from warnings import warn
from .api import from_bytes
from .constant import CHARDET_CORRESPONDENCE
def detect(
byte_str: bytes, should_rename_legacy: bool = False, **kwargs: Any
) -> Dict[str, Optional[Union[str, float]]]:
"""
chardet legacy method
Detect... | |
35,954 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 388,389 | 371,447 | feed | ArchaicUpperLowerPlugin | 389,430 | 389,430 | class ArchaicUpperLowerPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._buf: bool = False
self._character_count_since_last_sep: int = 0
self._successive_upper_lower_count: int = 0
self._successive_upper_lower_count_final: int = 0
self._character_count: int = 0... | class ArchaicUpperLowerPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._buf: bool = False
self._character_count_since_last_sep: int = 0
self._successive_upper_lower_count: int = 0
self._successive_upper_lower_count_final: int = 0
self._character_count: int = 0... | is_concerned = character.isalpha() and is_case_variable(character)
chunk_sep = is_concerned is False
if chunk_sep and self._character_count_since_last_sep > 0:
if (
self._character_count_since_last_sep <= 64
and character.isdigit() is False
... | is_concerned = character.isalpha() and is_case_variable(character)
chunk_sep = is_concerned is False
if chunk_sep and self._character_count_since_last_sep > 0:
if (
self._character_count_since_last_sep <= 64
and character.isdigit() is False
... | 107 | 341 | 442 | 783 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,955 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 353,354 | 340,371 | feed | CjkInvalidStopPlugin | 354,360 | 354,360 | class CjkInvalidStopPlugin(MessDetectorPlugin):
"""
GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and
can be easily detected. Searching for the overuse of '丅' and '丄'.
"""
def __init__(self) -> None:
self._wrong_stop_count: int = 0
self._... | class CjkInvalidStopPlugin(MessDetectorPlugin):
"""
GB(Chinese) based encoding often render the stop incorrectly when the content does not fit and
can be easily detected. Searching for the overuse of '丅' and '丄'.
"""
def __init__(self) -> None:
self._wrong_stop_count: int = 0
self._... | if character in {"丅", "丄"}:
self._wrong_stop_count += 1
return
if is_cjk(character):
self._cjk_character_count += 1
| if character in {"丅", "丄"}:
self._wrong_stop_count += 1
return
if is_cjk(character):
self._cjk_character_count += 1
| 14 | 254 | 58 | 312 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,956 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 36,37 | 30,64 | eligible | MessDetectorPlugin | 40,42 | 37,42 | class MessDetectorPlugin:
"""
Base abstract class used for mess detection plugins.
All detectors MUST extend and implement given methods.
"""
def eligible(self, character: str) -> bool:
FILL_FUNC_BODY def feed(self, character: str) -> None:
"""
The main routine to be executed upo... | class MessDetectorPlugin:
"""
Base abstract class used for mess detection plugins.
All detectors MUST extend and implement given methods.
"""
def eligible(self, character: str) -> bool:
"""
Determine if given character should be fed in.
"""
FILL_FUNC_BODY def feed(self, c... | raise NotImplementedError # pragma: nocover
| """
Determine if given character should be fed in.
"""
raise NotImplementedError # pragma: nocover
| 5 | 266 | 19 | 285 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,957 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 268,269 | 250,340 | feed | SuperWeirdWordPlugin | 269,322 | 269,322 | class SuperWeirdWordPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._word_count: int = 0
self._bad_word_count: int = 0
self._foreign_long_count: int = 0
self._is_current_word_bad: bool = False
self._foreign_long_watch: bool = False
self._character_count... | class SuperWeirdWordPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._word_count: int = 0
self._bad_word_count: int = 0
self._foreign_long_count: int = 0
self._is_current_word_bad: bool = False
self._foreign_long_watch: bool = False
self._character_count... | if character.isalpha():
self._buffer += character
if is_accentuated(character):
self._buffer_accent_count += 1
if (
self._foreign_long_watch is False
and (is_latin(character) is False or is_accentuated(character))
... | if character.isalpha():
self._buffer += character
if is_accentuated(character):
self._buffer_accent_count += 1
if (
self._foreign_long_watch is False
and (is_latin(character) is False or is_accentuated(character))
... | 176 | 356 | 633 | 989 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,958 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 171,172 | 161,198 | feed | SuspiciousDuplicateAccentPlugin | 172,185 | 172,185 | class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._successive_count: int = 0
self._character_count: int = 0
self._last_latin_character: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isalpha() and is_l... | class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._successive_count: int = 0
self._character_count: int = 0
self._last_latin_character: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isalpha() and is_l... | self._character_count += 1
if (
self._last_latin_character is not None
and is_accentuated(character)
and is_accentuated(self._last_latin_character)
):
if character.isupper() and self._last_latin_character.isupper():
self._successive... | self._character_count += 1
if (
self._last_latin_character is not None
and is_accentuated(character)
and is_accentuated(self._last_latin_character)
):
if character.isupper() and self._last_latin_character.isupper():
self._successive... | 42 | 234 | 169 | 403 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,959 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 207,208 | 198,250 | feed | SuspiciousRange | 208,230 | 208,230 | class SuspiciousRange(MessDetectorPlugin):
def __init__(self) -> None:
self._suspicious_successive_range_count: int = 0
self._character_count: int = 0
self._last_printable_seen: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isprintable()
... | class SuspiciousRange(MessDetectorPlugin):
def __init__(self) -> None:
self._suspicious_successive_range_count: int = 0
self._character_count: int = 0
self._last_printable_seen: Optional[str] = None
def eligible(self, character: str) -> bool:
return character.isprintable()
... | self._character_count += 1
if (
character.isspace()
or is_punctuation(character)
or character in COMMON_SAFE_ASCII_CHARACTERS
):
self._last_printable_seen = None
return
if self._last_printable_seen is None:
self._l... | self._character_count += 1
if (
character.isspace()
or is_punctuation(character)
or character in COMMON_SAFE_ASCII_CHARACTERS
):
self._last_printable_seen = None
return
if self._last_printable_seen is None:
self._l... | 42 | 299 | 231 | 530 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,960 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 129,131 | 111,137 | ratio | TooManyAccentuatedPlugin | 131,137 | 131,137 | class TooManyAccentuatedPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._character_count: int = 0
self._accentuated_count: int = 0
def eligible(self, character: str) -> bool:
return character.isalpha()
def feed(self, character: str) -> None:
self._character_cou... | class TooManyAccentuatedPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._character_count: int = 0
self._accentuated_count: int = 0
def eligible(self, character: str) -> bool:
return character.isalpha()
def feed(self, character: str) -> None:
self._character_cou... | if self._character_count == 0 or self._character_count < 8:
return 0.0
ratio_of_accentuation: float = self._accentuated_count / self._character_count
return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
| if self._character_count == 0 or self._character_count < 8:
return 0.0
ratio_of_accentuation: float = self._accentuated_count / self._character_count
return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0
| 24 | 193 | 88 | 281 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,961 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 99,101 | 64,111 | ratio | TooManySymbolOrPunctuationPlugin | 101,111 | 101,111 | class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._punctuation_count: int = 0
self._symbol_count: int = 0
self._character_count: int = 0
self._last_printable_char: Optional[str] = None
self._frenzy_symbol_in_word: bool = False
... | class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._punctuation_count: int = 0
self._symbol_count: int = 0
self._character_count: int = 0
self._last_printable_char: Optional[str] = None
self._frenzy_symbol_in_word: bool = False
... | if self._character_count == 0:
return 0.0
ratio_of_punctuation: float = (
self._punctuation_count + self._symbol_count
) / self._character_count
return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
| if self._character_count == 0:
return 0.0
ratio_of_punctuation: float = (
self._punctuation_count + self._symbol_count
) / self._character_count
return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0
| 24 | 348 | 96 | 444 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,962 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/md.py | 145,146 | 137,161 | feed | UnprintablePlugin | 146,150 | 146,150 | class UnprintablePlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._unprintable_count: int = 0
self._character_count: int = 0
def eligible(self, character: str) -> bool:
return True
def feed(self, character: str) -> None:
FILL_FUNC_BODY def reset(self) -> None: # pra... | class UnprintablePlugin(MessDetectorPlugin):
def __init__(self) -> None:
self._unprintable_count: int = 0
self._character_count: int = 0
def eligible(self, character: str) -> bool:
return True
def feed(self, character: str) -> None:
FILL_FUNC_BODY def reset(self) -> None: # pra... | if is_unprintable(character):
self._unprintable_count += 1
self._character_count += 1
| if is_unprintable(character):
self._unprintable_count += 1
self._character_count += 1
| 8 | 182 | 36 | 218 | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... | from functools import lru_cache
from logging import getLogger
from typing import List, Optional
from .constant import (
COMMON_SAFE_ASCII_CHARACTERS,
TRACE,
UNICODE_SECONDARY_RANGE_KEYWORD,
)
from .utils import (
is_accentuated,
is_ascii,
is_case_variable,
is_cjk,
is_emoticon,
is_ha... |
35,964 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/models.py | 254,255 | 222,289 | append | CharsetMatches | 259,274 | 255,274 | class CharsetMatches:
"""
Container with every CharsetMatch items ordered by default from most probable to the less one.
Act like a list(iterable) but does not implements all related methods.
"""
def __init__(self, results: Optional[List[CharsetMatch]] = None):
self._results: List[CharsetMa... | class CharsetMatches:
"""
Container with every CharsetMatch items ordered by default from most probable to the less one.
Act like a list(iterable) but does not implements all related methods.
"""
def __init__(self, results: Optional[List[CharsetMatch]] = None):
self._results: List[CharsetMa... | if not isinstance(item, CharsetMatch):
raise ValueError(
"Cannot append instance '{}' to CharsetMatches".format(
str(item.__class__)
)
)
# We should disable the submatch factoring when the input file is too heavy (conserve RAM u... | """
Insert a single match. Will be inserted accordingly to preserve sort.
Can be inserted as a submatch.
"""
if not isinstance(item, CharsetMatch):
raise ValueError(
"Cannot append instance '{}' to CharsetMatches".format(
str(item._... | 54 | 478 | 180 | 658 | from encodings.aliases import aliases
from hashlib import sha256
from json import dumps
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from .constant import TOO_BIG_SEQUENCE
from .utils import iana_name, is_multi_byte_encoding, unicode_range
class CharsetMatch:
def __init__(
self,
... | from encodings.aliases import aliases
from hashlib import sha256
from json import dumps
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from .constant import TOO_BIG_SEQUENCE
from .utils import iana_name, is_multi_byte_encoding, unicode_range
class CharsetMatch:
def __init__(
self,
... |
35,965 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/charset_normalizer/models.py | 336,337 | 293,338 | to_json | CliDetectionResult | 337,338 | 337,338 | class CliDetectionResult:
def __init__(
self,
path: str,
encoding: Optional[str],
encoding_aliases: List[str],
alternative_encodings: List[str],
language: str,
alphabets: List[str],
has_sig_or_bom: bool,
chaos: float,
coherence: float,
... | class CliDetectionResult:
def __init__(
self,
path: str,
encoding: Optional[str],
encoding_aliases: List[str],
alternative_encodings: List[str],
language: str,
alphabets: List[str],
has_sig_or_bom: bool,
chaos: float,
coherence: float,
... | return dumps(self.__dict__, ensure_ascii=True, indent=4)
| return dumps(self.__dict__, ensure_ascii=True, indent=4)
| 4 | 494 | 25 | 519 | from encodings.aliases import aliases
from hashlib import sha256
from json import dumps
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from .constant import TOO_BIG_SEQUENCE
from .utils import iana_name, is_multi_byte_encoding, unicode_range
class CharsetMatch:
def __init__(
self,
... | from encodings.aliases import aliases
from hashlib import sha256
from json import dumps
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from .constant import TOO_BIG_SEQUENCE
from .utils import iana_name, is_multi_byte_encoding, unicode_range
class CharsetMatch:
def __init__(
self,
... |
35,967 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/colorama/ansi.py | 18,19 | 1,103 | clear_screen | 19,21 | 19,21 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... | return CSI + str(mode) + 'J'
| return CSI + str(mode) + 'J'
| 6 | 953 | 17 | 970 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... | |
35,968 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/colorama/ansi.py | 37,38 | 36,49 | UP | AnsiCursor | 38,39 | 38,39 | class AnsiCursor(object):
def UP(self, n=1):
FILL_FUNC_BODY def DOWN(self, n=1):
return CSI + str(n) + 'B'
def FORWARD(self, n=1):
return CSI + str(n) + 'C'
def BACK(self, n=1):
return CSI + str(n) + 'D'
def POS(self, x=1, y=1):
return CSI + str(y) + ';' + str(x) + 'H'... | class AnsiCursor(object):
def UP(self, n=1):
FILL_FUNC_BODY def DOWN(self, n=1):
return CSI + str(n) + 'B'
def FORWARD(self, n=1):
return CSI + str(n) + 'C'
def BACK(self, n=1):
return CSI + str(n) + 'D'
def POS(self, x=1, y=1):
return CSI + str(y) + ';' + str(x) + 'H'... | return CSI + str(n) + 'A'
| return CSI + str(n) + 'A'
| 6 | 149 | 15 | 164 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
OSC = '\033]'
BEL = '\a'
def code_to_chars(code):
return CSI + str(code) + 'm'
def set_t... |
35,970 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/colorama/ansitowin32.py | 49,50 | 16,72 | isatty | StreamWrapper | 50,61 | 50,61 | class StreamWrapper(object):
'''
Wraps a stream (such as stdout), acting as a transparent proxy for all
attribute access apart from method 'write()', which is delegated to our
Converter instance.
'''
def __init__(self, wrapped, converter):
# double-underscore everything to prevent clashe... | class StreamWrapper(object):
'''
Wraps a stream (such as stdout), acting as a transparent proxy for all
attribute access apart from method 'write()', which is delegated to our
Converter instance.
'''
def __init__(self, wrapped, converter):
# double-underscore everything to prevent clashe... | stream = self.__wrapped
if 'PYCHARM_HOSTED' in os.environ:
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
return True
try:
stream_isatty = stream.isatty
except AttributeError:
return False
else... | stream = self.__wrapped
if 'PYCHARM_HOSTED' in os.environ:
if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):
return True
try:
stream_isatty = stream.isatty
except AttributeError:
return False
else... | 33 | 429 | 108 | 537 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import re
import sys
import os
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
from .win32 import windll, winapi_test
winterm = None
if windll is not None:
... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import re
import sys
import os
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL
from .winterm import enable_vt_processing, WinTerm, WinColor, WinStyle
from .win32 import windll, winapi_test
winterm = None
if windll is not None:
... |
35,971 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/colorama/initialise.py | 37,38 | 1,122 | init | 38,65 | 38,65 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
def _wipe_internal_state_for_tests():
global orig_stdout, orig_stderr
orig_stdout = None
orig_stderr = None
global wrapped_stdout, wrapped_stderr... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
def _wipe_internal_state_for_tests():
global orig_stdout, orig_stderr
orig_stdout = None
orig_stderr = None
global wrapped_stdout, wrapped_stderr... |
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
global orig_stdout, orig_stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
if sys.stdout is None:
wrapped_stdout = N... |
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
global orig_stdout, orig_stderr
orig_stdout = sys.stdout
orig_stderr = sys.stderr
if sys.stdout is None:
wrapped_stdout = N... | 71 | 843 | 261 | 1,104 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
def _wipe_internal_state_for_tests():
global orig_stdout, orig_stderr
orig_stdout = None
orig_stderr = None
global wrapped_stdout, wrapped_stderr... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
def _wipe_internal_state_for_tests():
global orig_stdout, orig_stderr
orig_stdout = None
orig_stderr = None
global wrapped_stdout, wrapped_stderr... | |
35,973 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/colorama/winterm.py | 117,118 | 28,178 | erase_screen | WinTerm | 118,149 | 118,149 | class WinTerm(object):
def __init__(self):
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
self.set_attrs(self._default)
self._default_fore = self._fore
self._default_back = self._back
self._default_style = self._style
# In order to emulate... | class WinTerm(object):
def __init__(self):
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
self.set_attrs(self._default)
self._default_fore = self._fore
self._default_back = self._back
self._default_style = self._style
# In order to emulate... | # 0 should clear from the cursor to the end of the screen.
# 1 should clear from the cursor to the beginning of the screen.
# 2 should clear the entire screen, and move cursor to (1,1)
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
csbi = win32.GetC... | # 0 should clear from the cursor to the end of the screen.
# 1 should clear from the cursor to the beginning of the screen.
# 2 should clear the entire screen, and move cursor to (1,1)
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
csbi = win32.GetC... | 157 | 1,417 | 473 | 1,890 | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
try:
from msvcrt import get_osfhandle
except ImportError:
def get_osfhandle(_):
raise OSError("This isn't windows!")
from . import win32
# from wincon.h
class WinColor(object):
BLACK = 0
BLUE = 1
GREEN = 2
... | # Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
try:
from msvcrt import get_osfhandle
except ImportError:
def get_osfhandle(_):
raise OSError("This isn't windows!")
from . import win32
# from wincon.h
class WinColor(object):
BLACK = 0
BLUE = 1
GREEN = 2
... |
35,974 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/codec.py | 102,103 | 1,113 | getregentry | 103,113 | 103,113 | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | # Compatibility as a search_function for codecs.register()
return codecs.CodecInfo(
name='idna',
encode=Codec().encode, # type: ignore
decode=Codec().decode, # type: ignore
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwrite... | # Compatibility as a search_function for codecs.register()
return codecs.CodecInfo(
name='idna',
encode=Codec().encode, # type: ignore
decode=Codec().decode, # type: ignore
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamwrite... | 23 | 889 | 121 | 1,010 | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | |
35,975 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/codec.py | 19,20 | 8,28 | decode | Codec | 20,28 | 20,28 | class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return b"", 0
return encode(data), len(data)
def decode... | class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return b"", 0
return encode(data), len(data)
def decode... | if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return '', 0
return decode(data), len(data)
| if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return '', 0
return decode(data), len(data)
| 18 | 134 | 64 | 198 | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... |
35,976 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/codec.py | 62,63 | 61,94 | _buffer_decode | IncrementalDecoder | 63,94 | 63,94 | class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
FILL_FUNC_BODY | class IncrementalDecoder(codecs.BufferedIncrementalDecoder):
def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
FILL_FUNC_BODY | if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return ('', 0)
labels = _unicode_dots_re.split(data)
trailing_dot = ''
if labels:
if not labels[-1]:
trailing_dot = '.'
... | if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return ('', 0)
labels = _unicode_dots_re.split(data)
trailing_dot = ''
if labels:
if not labels[-1]:
trailing_dot = '.'
... | 80 | 66 | 257 | 323 | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... |
35,977 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/codec.py | 29,30 | 28,61 | _buffer_encode | IncrementalEncoder | 30,61 | 30,61 | class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
FILL_FUNC_BODY | class IncrementalEncoder(codecs.BufferedIncrementalEncoder):
def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]: # type: ignore
FILL_FUNC_BODY | if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return "", 0
labels = _unicode_dots_re.split(data)
trailing_dot = ''
if labels:
if not labels[-1]:
trailing_dot = '.'
... | if errors != 'strict':
raise IDNAError('Unsupported error handling \"{}\"'.format(errors))
if not data:
return "", 0
labels = _unicode_dots_re.split(data)
trailing_dot = ''
if labels:
if not labels[-1]:
trailing_dot = '.'
... | 87 | 66 | 268 | 334 | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... | from .core import encode, decode, alabel, ulabel, IDNAError
import codecs
import re
from typing import Tuple, Optional
_unicode_dots_re = re.compile('[\u002e\u3002\uff0e\uff61]')
class Codec(codecs.Codec):
def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:
if errors != 'strict':
... |
35,978 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/compat.py | 11,12 | 1,14 | nameprep | 12,14 | 12,14 | from .core import *
from .codec import *
from typing import Any, Union
def ToASCII(label: str) -> bytes:
return encode(label)
def ToUnicode(label: Union[bytes, bytearray]) -> str:
return decode(label)
def nameprep(s: Any) -> None:
FILL_FUNC_BODY | from .core import *
from .codec import *
from typing import Any, Union
def ToASCII(label: str) -> bytes:
return encode(label)
def ToUnicode(label: Union[bytes, bytearray]) -> str:
return decode(label)
def nameprep(s: Any) -> None:
FILL_FUNC_BODY | raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')
| raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')
| 8 | 94 | 27 | 121 | from .core import *
from .codec import *
from typing import Any, Union
def ToASCII(label: str) -> bytes:
return encode(label)
def ToUnicode(label: Union[bytes, bytearray]) -> str:
return decode(label)
def nameprep(s: Any) -> None:
FILL_FUNC_BODY | from .core import *
from .codec import *
from typing import Any, Union
def ToASCII(label: str) -> bytes:
return encode(label)
def ToUnicode(label: Union[bytes, bytearray]) -> str:
return decode(label)
def nameprep(s: Any) -> None:
FILL_FUNC_BODY | |
35,980 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/idna/intranges.py | 39,40 | 1,55 | intranges_contain | 41,55 | 40,55 | """
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
from typing import List, Tuple
d... | """
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
from typing import List, Tuple
d... | tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
# we could be immediately ahead of a tuple (start, end)
# with start < int_ <= end
if pos > 0:
left, right = _decode_range(ranges[pos-1])
if left <= int_ < right:
return True
# or we could be imm... | """Determine if `int_` falls into one of the ranges in `ranges`."""
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
# we could be immediately ahead of a tuple (start, end)
# with start < int_ <= end
if pos > 0:
left, right = _decode_range(ranges[pos-1])
i... | 69 | 474 | 168 | 642 | """
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
from typing import List, Tuple
d... | """
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
from typing import List, Tuple
d... | |
35,982 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/multidict/_abc.py | 28,30 | 23,33 | getone | MultiMapping | 30,33 | 30,33 | class MultiMapping(Mapping, metaclass=_TypingMeta):
@abc.abstractmethod
def getall(self, key, default=None):
raise KeyError
@abc.abstractmethod
def getone(self, key, default=None):
FILL_FUNC_BODY | class MultiMapping(Mapping, metaclass=_TypingMeta):
@abc.abstractmethod
def getall(self, key, default=None):
raise KeyError
@abc.abstractmethod
def getone(self, key, default=None):
FILL_FUNC_BODY | raise KeyError
| raise KeyError
| 2 | 76 | 10 | 86 | import abc
import sys
import types
from collections.abc import Mapping, MutableMapping
class _TypingMeta(abc.ABCMeta):
# A fake metaclass to satisfy typing deps in runtime
# basically MultiMapping[str] and other generic-like type instantiations
# are emulated.
# Note: real type hints are provided by _... | import abc
import sys
import types
from collections.abc import Mapping, MutableMapping
class _TypingMeta(abc.ABCMeta):
# A fake metaclass to satisfy typing deps in runtime
# basically MultiMapping[str] and other generic-like type instantiations
# are emulated.
# Note: real type hints are provided by _... |
35,983 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/multidict/_abc.py | 46,48 | 33,49 | popall | MutableMultiMapping | 48,49 | 48,49 | class MutableMultiMapping(MultiMapping, MutableMapping):
@abc.abstractmethod
def add(self, key, value):
raise NotImplementedError
@abc.abstractmethod
def extend(self, *args, **kwargs):
raise NotImplementedError
@abc.abstractmethod
def popone(self, key, default=None):
ra... | class MutableMultiMapping(MultiMapping, MutableMapping):
@abc.abstractmethod
def add(self, key, value):
raise NotImplementedError
@abc.abstractmethod
def extend(self, *args, **kwargs):
raise NotImplementedError
@abc.abstractmethod
def popone(self, key, default=None):
ra... | raise KeyError
| raise KeyError
| 2 | 132 | 6 | 138 | import abc
import sys
import types
from collections.abc import Mapping, MutableMapping
class _TypingMeta(abc.ABCMeta):
# A fake metaclass to satisfy typing deps in runtime
# basically MultiMapping[str] and other generic-like type instantiations
# are emulated.
# Note: real type hints are provided by _... | import abc
import sys
import types
from collections.abc import Mapping, MutableMapping
class _TypingMeta(abc.ABCMeta):
# A fake metaclass to satisfy typing deps in runtime
# basically MultiMapping[str] and other generic-like type instantiations
# are emulated.
# Note: real type hints are provided by _... |
35,984 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/multidict/_multidict_base.py | 75,76 | 1,145 | _viewbaseset_sub | 76,87 | 76,87 | from collections.abc import ItemsView, Iterable, KeysView, Set, ValuesView
def _abc_itemsview_register(view_cls):
ItemsView.register(view_cls)
def _abc_keysview_register(view_cls):
KeysView.register(view_cls)
def _abc_valuesview_register(view_cls):
ValuesView.register(view_cls)
def _viewbaseset_rich... | from collections.abc import ItemsView, Iterable, KeysView, Set, ValuesView
def _abc_itemsview_register(view_cls):
ItemsView.register(view_cls)
def _abc_keysview_register(view_cls):
KeysView.register(view_cls)
def _abc_valuesview_register(view_cls):
ValuesView.register(view_cls)
def _viewbaseset_rich... | if not isinstance(other, Iterable):
return NotImplemented
if isinstance(view, Set):
view = set(iter(view))
if isinstance(other, Set):
other = set(iter(other))
if not isinstance(other, Set):
other = set(iter(other))
return view - other
| if not isinstance(other, Iterable):
return NotImplemented
if isinstance(view, Set):
view = set(iter(view))
if isinstance(other, Set):
other = set(iter(other))
if not isinstance(other, Set):
other = set(iter(other))
return view - other
| 29 | 1,156 | 99 | 1,255 | from collections.abc import ItemsView, Iterable, KeysView, Set, ValuesView
def _abc_itemsview_register(view_cls):
ItemsView.register(view_cls)
def _abc_keysview_register(view_cls):
KeysView.register(view_cls)
def _abc_valuesview_register(view_cls):
ValuesView.register(view_cls)
def _viewbaseset_rich... | from collections.abc import ItemsView, Iterable, KeysView, Set, ValuesView
def _abc_itemsview_register(view_cls):
ItemsView.register(view_cls)
def _abc_keysview_register(view_cls):
KeysView.register(view_cls)
def _abc_valuesview_register(view_cls):
ValuesView.register(view_cls)
def _viewbaseset_rich... | |
35,985 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/_openai_scripts.py | 16,17 | 1,75 | main | 17,73 | 17,73 | #!/usr/bin/env python
import argparse
import logging
import sys
import openai
from openai.cli import api_register, display_error, tools_register, wandb_register
logger = logging.getLogger()
formatter = logging.Formatter("[%(asctime)s] %(message)s")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(form... | #!/usr/bin/env python
import argparse
import logging
import sys
import openai
from openai.cli import api_register, display_error, tools_register, wandb_register
logger = logging.getLogger()
formatter = logging.Formatter("[%(asctime)s] %(message)s")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(form... | parser = argparse.ArgumentParser(description=None)
parser.add_argument(
"-v",
"--verbose",
action="count",
dest="verbosity",
default=0,
help="Set verbosity.",
)
parser.add_argument("-b", "--api-base", help="What API base url to use.")
parser.add_argume... | parser = argparse.ArgumentParser(description=None)
parser.add_argument(
"-v",
"--verbose",
action="count",
dest="verbosity",
default=0,
help="Set verbosity.",
)
parser.add_argument("-b", "--api-base", help="What API base url to use.")
parser.add_argume... | 132 | 145 | 589 | 734 | #!/usr/bin/env python
import argparse
import logging
import sys
import openai
from openai.cli import api_register, display_error, tools_register, wandb_register
logger = logging.getLogger()
formatter = logging.Formatter("[%(asctime)s] %(message)s")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(form... | #!/usr/bin/env python
import argparse
import logging
import sys
import openai
from openai.cli import api_register, display_error, tools_register, wandb_register
logger = logging.getLogger()
formatter = logging.Formatter("[%(asctime)s] %(message)s")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(form... | |
35,986 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/abstract/createable_api_resource.py | 38,49 | 6,99 | create | CreateableAPIResource | 49,69 | 49,69 | class CreateableAPIResource(APIResource):
plain_old_data = False
@classmethod
def __prepare_create_requestor(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
):
requestor = api_requestor.APIRequestor(
... | class CreateableAPIResource(APIResource):
plain_old_data = False
@classmethod
def __prepare_create_requestor(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
):
requestor = api_requestor.APIRequestor(
... | requestor, url = cls.__prepare_create_requestor(
api_key,
api_base,
api_type,
api_version,
organization,
)
response, _, api_key = requestor.request(
"post", url, params, request_id=request_id
)
return util.... | requestor, url = cls.__prepare_create_requestor(
api_key,
api_base,
api_type,
api_version,
organization,
)
response, _, api_key = requestor.request(
"post", url, params, request_id=request_id
)
return util.... | 28 | 605 | 157 | 762 | from openai import api_requestor, util, error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class CreateableAPIResource(APIResource):
plain_old_data = False
@classmethod
def __prepare_create_requestor(
cls,
api_key=None,
api_bas... | from openai import api_requestor, util, error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class CreateableAPIResource(APIResource):
plain_old_data = False
@classmethod
def __prepare_create_requestor(
cls,
api_key=None,
api_bas... |
35,987 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/abstract/deletable_api_resource.py | 10,12 | 9,49 | __prepare_delete | DeletableAPIResource | 12,34 | 12,34 | class DeletableAPIResource(APIResource):
@classmethod
def __prepare_delete(cls, sid, api_type=None, api_version=None):
FILL_FUNC_BODY @classmethod
def delete(cls, sid, api_type=None, api_version=None, **params):
url = cls.__prepare_delete(sid, api_type, api_version)
return cls._static_re... | class DeletableAPIResource(APIResource):
@classmethod
def __prepare_delete(cls, sid, api_type=None, api_version=None):
FILL_FUNC_BODY @classmethod
def delete(cls, sid, api_type=None, api_version=None, **params):
url = cls.__prepare_delete(sid, api_type, api_version)
return cls._static_re... | if isinstance(cls, APIResource):
raise ValueError(".delete may only be called as a class method now.")
base = cls.class_url()
extn = quote_plus(sid)
typed_api_type, api_version = cls._get_api_type_and_version(
api_type, api_version
)
if typed_api... | if isinstance(cls, APIResource):
raise ValueError(".delete may only be called as a class method now.")
base = cls.class_url()
extn = quote_plus(sid)
typed_api_type, api_version = cls._get_api_type_and_version(
api_type, api_version
)
if typed_api... | 62 | 242 | 256 | 498 | from urllib.parse import quote_plus
from typing import Awaitable
from openai import error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class DeletableAPIResource(APIResource):
@classmethod
def __prepare_delete(cls, sid, api_type=None, api_version=None):
F... | from urllib.parse import quote_plus
from typing import Awaitable
from openai import error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class DeletableAPIResource(APIResource):
@classmethod
def __prepare_delete(cls, sid, api_type=None, api_version=None):
F... |
35,988 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/abstract/listable_api_resource.py | 69,80 | 6,96 | alist | ListableAPIResource | 80,96 | 80,96 | class ListableAPIResource(APIResource):
@classmethod
def auto_paging_iter(cls, *args, **params):
return cls.list(*args, **params).auto_paging_iter()
@classmethod
def __prepare_list_requestor(
cls,
api_key=None,
api_version=None,
organization=None,
api_bas... | class ListableAPIResource(APIResource):
@classmethod
def auto_paging_iter(cls, *args, **params):
return cls.list(*args, **params).auto_paging_iter()
@classmethod
def __prepare_list_requestor(
cls,
api_key=None,
api_version=None,
organization=None,
api_bas... | requestor, url = cls.__prepare_list_requestor(
api_key,
api_version,
organization,
api_base,
api_type,
)
response, _, api_key = await requestor.arequest(
"get", url, params, request_id=request_id
)
openai_ob... | requestor, url = cls.__prepare_list_requestor(
api_key,
api_version,
organization,
api_base,
api_type,
)
response, _, api_key = await requestor.arequest(
"get", url, params, request_id=request_id
)
openai_ob... | 34 | 646 | 154 | 800 | from openai import api_requestor, util, error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class ListableAPIResource(APIResource):
@classmethod
def auto_paging_iter(cls, *args, **params):
return cls.list(*args, **params).auto_paging_iter()
@cl... | from openai import api_requestor, util, error
from openai.api_resources.abstract.api_resource import APIResource
from openai.util import ApiType
class ListableAPIResource(APIResource):
@classmethod
def auto_paging_iter(cls, *args, **params):
return cls.list(*args, **params).auto_paging_iter()
@cl... |
35,989 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/abstract/nested_resource_class_methods.py | 6,13 | 1,155 | _nested_resource_class_methods | 13,135 | 13,135 | from urllib.parse import quote_plus
from openai import api_requestor, util
def _nested_resource_class_methods(
resource,
path=None,
operations=None,
resource_plural=None,
async_=False,
):
FILL_FUNC_BODYdef nested_resource_class_methods(
resource,
path=None,
operations=None,
resour... | from urllib.parse import quote_plus
from openai import api_requestor, util
def _nested_resource_class_methods(
resource,
path=None,
operations=None,
resource_plural=None,
async_=False,
):
FILL_FUNC_BODYdef nested_resource_class_methods(
resource,
path=None,
operations=None,
resour... | if resource_plural is None:
resource_plural = "%ss" % resource
if path is None:
path = resource_plural
if operations is None:
raise ValueError("operations list required")
def wrapper(cls):
def nested_resource_url(cls, id, nested_id=None):
url = "%s/%s/%s" % (... | if resource_plural is None:
resource_plural = "%ss" % resource
if path is None:
path = resource_plural
if operations is None:
raise ValueError("operations list required")
def wrapper(cls):
def nested_resource_url(cls, id, nested_id=None):
url = "%s/%s/%s" % (... | 293 | 224 | 1,278 | 1,502 | from urllib.parse import quote_plus
from openai import api_requestor, util
def _nested_resource_class_methods(
resource,
path=None,
operations=None,
resource_plural=None,
async_=False,
):
FILL_FUNC_BODYdef nested_resource_class_methods(
resource,
path=None,
operations=None,
resour... | from urllib.parse import quote_plus
from openai import api_requestor, util
def _nested_resource_class_methods(
resource,
path=None,
operations=None,
resource_plural=None,
async_=False,
):
FILL_FUNC_BODYdef nested_resource_class_methods(
resource,
path=None,
operations=None,
resour... | |
35,990 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/abstract/updateable_api_resource.py | 8,10 | 7,17 | modify | UpdateableAPIResource | 10,13 | 10,13 | class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid, **params):
FILL_FUNC_BODY @classmethod
def amodify(cls, sid, **params) -> Awaitable:
url = "%s/%s" % (cls.class_url(), quote_plus(sid))
return cls._astatic_request("patch", url, **params)
| class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid, **params):
FILL_FUNC_BODY @classmethod
def amodify(cls, sid, **params) -> Awaitable:
url = "%s/%s" % (cls.class_url(), quote_plus(sid))
return cls._astatic_request("patch", url, **params)
| url = "%s/%s" % (cls.class_url(), quote_plus(sid))
return cls._static_request("post", url, **params)
| url = "%s/%s" % (cls.class_url(), quote_plus(sid))
return cls._static_request("post", url, **params)
| 10 | 107 | 46 | 153 | from urllib.parse import quote_plus
from typing import Awaitable
from openai.api_resources.abstract.api_resource import APIResource
class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid, **params):
FILL_FUNC_BODY @classmethod
def amodify(cls, sid, **params) -> Awaitable:
u... | from urllib.parse import quote_plus
from typing import Awaitable
from openai.api_resources.abstract.api_resource import APIResource
class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid, **params):
FILL_FUNC_BODY @classmethod
def amodify(cls, sid, **params) -> Awaitable:
u... |
35,991 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/audio.py | 185,198 | 8,206 | atranslate_raw | Audio | 198,206 | 198,206 | class Audio(APIResource):
OBJECT_NAME = "audio"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def _prepare_request(
cls,
file,
filename,
model,
api_key=None,
api_base=None,
api_type=None,
... | class Audio(APIResource):
OBJECT_NAME = "audio"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def _prepare_request(
cls,
file,
filename,
model,
api_key=None,
api_base=None,
api_type=None,
... | requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("translations")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_k... | requestor, files, data = cls._prepare_request(file, filename, model, **params)
url = cls._get_url("translations")
response, _, api_key = await requestor.arequest(
"post", url, files=files, params=data
)
return util.convert_to_openai_object(
response, api_k... | 29 | 1,578 | 111 | 1,689 | from typing import Any, List
import openai
from openai import api_requestor, util
from openai.api_resources.abstract import APIResource
class Audio(APIResource):
OBJECT_NAME = "audio"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def _prepare... | from typing import Any, List
import openai
from openai import api_requestor, util
from openai.api_resources.abstract import APIResource
class Audio(APIResource):
OBJECT_NAME = "audio"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def _prepare... |
35,992 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/chat_completion.py | 32,34 | 8,51 | acreate | ChatCompletion | 40,51 | 34,51 | class ChatCompletion(EngineAPIResource):
engine_required = False
OBJECT_NAME = "chat.completions"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new chat completion for the provided messages and parameters.
See https://platform.openai.com/docs/api-reference/chat-c... | class ChatCompletion(EngineAPIResource):
engine_required = False
OBJECT_NAME = "chat.completions"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new chat completion for the provided messages and parameters.
See https://platform.openai.com/docs/api-reference/chat-c... | start = time.time()
timeout = kwargs.pop("timeout", None)
while True:
try:
return await super().acreate(*args, **kwargs)
except TryAgain as e:
if timeout is not None and time.time() > start + timeout:
raise
... | """
Creates a new chat completion for the provided messages and parameters.
See https://platform.openai.com/docs/api-reference/chat-completions/create
for a list of valid parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
while Tru... | 37 | 287 | 106 | 393 | import time
from openai import util
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class ChatCompletion(EngineAPIResource):
engine_required = False
OBJECT_NAME = "chat.completions"
@classmethod
def create(cls, *args, **kwargs):
... | import time
from openai import util
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class ChatCompletion(EngineAPIResource):
engine_required = False
OBJECT_NAME = "chat.completions"
@classmethod
def create(cls, *args, **kwargs):
... |
35,993 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/completion.py | 12,14 | 9,51 | create | Completion | 20,32 | 14,32 | class Completion(EngineAPIResource):
OBJECT_NAME = "completions"
@classmethod
def create(cls, *args, **kwargs):
FILL_FUNC_BODY @classmethod
async def acreate(cls, *args, **kwargs):
"""
Creates a new completion for the provided prompt and parameters.
See https://platform.open... | class Completion(EngineAPIResource):
OBJECT_NAME = "completions"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new completion for the provided prompt and parameters.
See https://platform.openai.com/docs/api-reference/completions/create for a list
of valid par... | start = time.time()
timeout = kwargs.pop("timeout", None)
while True:
try:
return super().create(*args, **kwargs)
except TryAgain as e:
if timeout is not None and time.time() > start + timeout:
raise
ut... | """
Creates a new completion for the provided prompt and parameters.
See https://platform.openai.com/docs/api-reference/completions/create for a list
of valid parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
while True:
... | 36 | 272 | 106 | 378 | import time
from openai import util
from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class Completion(EngineAPIResource):
OBJECT_NAME = "completions"
@classmet... | import time
from openai import util
from openai.api_resources.abstract import DeletableAPIResource, ListableAPIResource
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class Completion(EngineAPIResource):
OBJECT_NAME = "completions"
@classmet... |
35,994 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/customer.py | 14,16 | 4,18 | acreate | Customer | 16,18 | 16,18 | class Customer(OpenAIObject):
@classmethod
def get_url(cls, customer, endpoint):
return f"/customer/{customer}/{endpoint}"
@classmethod
def create(cls, customer, endpoint, **params):
instance = cls()
return instance.request("post", cls.get_url(customer, endpoint), params)
@... | class Customer(OpenAIObject):
@classmethod
def get_url(cls, customer, endpoint):
return f"/customer/{customer}/{endpoint}"
@classmethod
def create(cls, customer, endpoint, **params):
instance = cls()
return instance.request("post", cls.get_url(customer, endpoint), params)
@... | instance = cls()
return instance.arequest("post", cls.get_url(customer, endpoint), params)
| instance = cls()
return instance.arequest("post", cls.get_url(customer, endpoint), params)
| 8 | 119 | 32 | 151 | from openai.openai_object import OpenAIObject
class Customer(OpenAIObject):
@classmethod
def get_url(cls, customer, endpoint):
return f"/customer/{customer}/{endpoint}"
@classmethod
def create(cls, customer, endpoint, **params):
instance = cls()
return instance.request("post",... | from openai.openai_object import OpenAIObject
class Customer(OpenAIObject):
@classmethod
def get_url(cls, customer, endpoint):
return f"/customer/{customer}/{endpoint}"
@classmethod
def create(cls, customer, endpoint, **params):
instance = cls()
return instance.request("post",... |
35,995 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/deployment.py | 13,15 | 10,120 | _check_create | Deployment | 15,45 | 15,45 | class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource):
OBJECT_NAME = "deployments"
@classmethod
def _check_create(cls, *args, **kwargs):
FILL_FUNC_BODY @classmethod
def create(cls, *args, **kwargs):
"""
Creates a new deployment for the provided prompt and... | class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource):
OBJECT_NAME = "deployments"
@classmethod
def _check_create(cls, *args, **kwargs):
FILL_FUNC_BODY @classmethod
def create(cls, *args, **kwargs):
"""
Creates a new deployment for the provided prompt and... | typed_api_type, _ = cls._get_api_type_and_version(
kwargs.get("api_type", None), None
)
if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD):
raise APIError(
"Deployment operations are only available for the Azure API type."
)
... | typed_api_type, _ = cls._get_api_type_and_version(
kwargs.get("api_type", None), None
)
if typed_api_type not in (util.ApiType.AZURE, util.ApiType.AZURE_AD):
raise APIError(
"Deployment operations are only available for the Azure API type."
)
... | 94 | 832 | 326 | 1,158 | from openai import util
from openai.api_resources.abstract import (
DeletableAPIResource,
ListableAPIResource,
CreateableAPIResource,
)
from openai.error import InvalidRequestError, APIError
class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource):
OBJECT_NAME = "deployments"... | from openai import util
from openai.api_resources.abstract import (
DeletableAPIResource,
ListableAPIResource,
CreateableAPIResource,
)
from openai.error import InvalidRequestError, APIError
class Deployment(CreateableAPIResource, ListableAPIResource, DeletableAPIResource):
OBJECT_NAME = "deployments"... |
35,996 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/edit.py | 35,37 | 8,58 | acreate | Edit | 40,58 | 37,58 | class Edit(EngineAPIResource):
OBJECT_NAME = "edits"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new edit for the provided input, instruction, and parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
api_type = kwargs.po... | class Edit(EngineAPIResource):
OBJECT_NAME = "edits"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new edit for the provided input, instruction, and parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
api_type = kwargs.po... | start = time.time()
timeout = kwargs.pop("timeout", None)
api_type = kwargs.pop("api_type", None)
typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0]
if typed_api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD):
raise error.InvalidAPIType(
... | """
Creates a new edit for the provided input, instruction, and parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
api_type = kwargs.pop("api_type", None)
typed_api_type = cls._get_api_type_and_version(api_type=api_type)[0]
if typed... | 63 | 317 | 221 | 538 | import time
from openai import util, error
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class Edit(EngineAPIResource):
OBJECT_NAME = "edits"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new edit for the ... | import time
from openai import util, error
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.error import TryAgain
class Edit(EngineAPIResource):
OBJECT_NAME = "edits"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new edit for the ... |
35,997 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/embedding.py | 14,16 | 11,92 | create | Embedding | 22,54 | 16,54 | class Embedding(EngineAPIResource):
OBJECT_NAME = "embeddings"
@classmethod
def create(cls, *args, **kwargs):
FILL_FUNC_BODY @classmethod
async def acreate(cls, *args, **kwargs):
"""
Creates a new embedding for the provided input and parameters.
See https://platform.openai.c... | class Embedding(EngineAPIResource):
OBJECT_NAME = "embeddings"
@classmethod
def create(cls, *args, **kwargs):
"""
Creates a new embedding for the provided input and parameters.
See https://platform.openai.com/docs/api-reference/embeddings for a list
of valid parameters.
... | start = time.time()
timeout = kwargs.pop("timeout", None)
user_provided_encoding_format = kwargs.get("encoding_format", None)
# If encoding format was not explicitly specified, we opaquely use base64 for performance
if not user_provided_encoding_format:
kwargs["enco... | """
Creates a new embedding for the provided input and parameters.
See https://platform.openai.com/docs/api-reference/embeddings for a list
of valid parameters.
"""
start = time.time()
timeout = kwargs.pop("timeout", None)
user_provided_encoding_format =... | 112 | 478 | 349 | 827 | import base64
import time
from openai import util
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.datalib import numpy as np, assert_has_numpy
from openai.error import TryAgain
class Embedding(EngineAPIResource):
OBJECT_NAME = "embeddings"
@classmethod
def cr... | import base64
import time
from openai import util
from openai.api_resources.abstract.engine_api_resource import EngineAPIResource
from openai.datalib import numpy as np, assert_has_numpy
from openai.error import TryAgain
class Embedding(EngineAPIResource):
OBJECT_NAME = "embeddings"
@classmethod
def cr... |
35,998 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/engine.py | 46,47 | 9,51 | embeddings | Engine | 47,51 | 47,51 | class Engine(ListableAPIResource, UpdateableAPIResource):
OBJECT_NAME = "engines"
def generate(self, timeout=None, **params):
start = time.time()
while True:
try:
return self.request(
"post",
self.instance_url() + "/generate",
... | class Engine(ListableAPIResource, UpdateableAPIResource):
OBJECT_NAME = "engines"
def generate(self, timeout=None, **params):
start = time.time()
while True:
try:
return self.request(
"post",
self.instance_url() + "/generate",
... | warnings.warn(
"Engine.embeddings is deprecated, use Embedding.create", DeprecationWarning
)
return self.request("post", self.instance_url() + "/embeddings", params)
| warnings.warn(
"Engine.embeddings is deprecated, use Embedding.create", DeprecationWarning
)
return self.request("post", self.instance_url() + "/embeddings", params)
| 14 | 317 | 56 | 373 | import time
import warnings
from openai import util
from openai.api_resources.abstract import ListableAPIResource, UpdateableAPIResource
from openai.error import TryAgain
class Engine(ListableAPIResource, UpdateableAPIResource):
OBJECT_NAME = "engines"
def generate(self, timeout=None, **params):
sta... | import time
import warnings
from openai import util
from openai.api_resources.abstract import ListableAPIResource, UpdateableAPIResource
from openai.error import TryAgain
class Engine(ListableAPIResource, UpdateableAPIResource):
OBJECT_NAME = "engines"
def generate(self, timeout=None, **params):
sta... |
35,999 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/error_object.py | 8,17 | 7,29 | refresh_from | ErrorObject | 17,29 | 17,29 | class ErrorObject(OpenAIObject):
def refresh_from(
self,
values,
api_key=None,
api_version=None,
api_type=None,
organization=None,
response_ms: Optional[int] = None,
):
FILL_FUNC_BODY | class ErrorObject(OpenAIObject):
def refresh_from(
self,
values,
api_key=None,
api_version=None,
api_type=None,
organization=None,
response_ms: Optional[int] = None,
):
FILL_FUNC_BODY | # Unlike most other API resources, the API will omit attributes in
# error objects when they have a null value. We manually set default
# values here to facilitate generic error handling.
values = merge_dicts({"message": None, "type": None}, values)
return super(ErrorObject, self... | # Unlike most other API resources, the API will omit attributes in
# error objects when they have a null value. We manually set default
# values here to facilitate generic error handling.
values = merge_dicts({"message": None, "type": None}, values)
return super(ErrorObject, self... | 50 | 81 | 146 | 227 | from typing import Optional
from openai.openai_object import OpenAIObject
from openai.util import merge_dicts
class ErrorObject(OpenAIObject):
def refresh_from(
self,
values,
api_key=None,
api_version=None,
api_type=None,
organization=None,
response_ms: Opt... | from typing import Optional
from openai.openai_object import OpenAIObject
from openai.util import merge_dicts
class ErrorObject(OpenAIObject):
def refresh_from(
self,
values,
api_key=None,
api_version=None,
api_type=None,
organization=None,
response_ms: Opt... |
36,000 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/image.py | 73,84 | 9,243 | _prepare_create_variation | Image | 84,101 | 84,101 | class Image(APIResource):
OBJECT_NAME = "images"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def create(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
... | class Image(APIResource):
OBJECT_NAME = "images"
@classmethod
def _get_url(cls, action):
return cls.class_url() + f"/{action}"
@classmethod
def create(
cls,
api_key=None,
api_base=None,
api_type=None,
api_version=None,
organization=None,
... | requestor = api_requestor.APIRequestor(
api_key,
api_base=api_base or openai.api_base,
api_type=api_type,
api_version=api_version,
organization=organization,
)
_, api_version = cls._get_api_type_and_version(api_type, api_version)
... | requestor = api_requestor.APIRequestor(
api_key,
api_base=api_base or openai.api_base,
api_type=api_type,
api_version=api_version,
organization=organization,
)
_, api_version = cls._get_api_type_and_version(api_type, api_version)
... | 39 | 1,629 | 195 | 1,824 | # WARNING: This interface is considered experimental and may changed in the future without warning.
from typing import Any, List
import openai
from openai import api_requestor, util
from openai.api_resources.abstract import APIResource
class Image(APIResource):
OBJECT_NAME = "images"
@classmethod
def _g... | # WARNING: This interface is considered experimental and may changed in the future without warning.
from typing import Any, List
import openai
from openai import api_requestor, util
from openai.api_resources.abstract import APIResource
class Image(APIResource):
OBJECT_NAME = "images"
@classmethod
def _g... |
36,001 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/api_resources/moderation.py | 13,15 | 6,46 | _prepare_create | Moderation | 15,27 | 15,27 | class Moderation(OpenAIObject):
VALID_MODEL_NAMES: List[str] = ["text-moderation-stable", "text-moderation-latest"]
@classmethod
def get_url(cls):
return "/moderations"
@classmethod
def _prepare_create(cls, input, model, api_key):
FILL_FUNC_BODY @classmethod
def create(
cls,... | class Moderation(OpenAIObject):
VALID_MODEL_NAMES: List[str] = ["text-moderation-stable", "text-moderation-latest"]
@classmethod
def get_url(cls):
return "/moderations"
@classmethod
def _prepare_create(cls, input, model, api_key):
FILL_FUNC_BODY @classmethod
def create(
cls,... | if model is not None and model not in cls.VALID_MODEL_NAMES:
raise ValueError(
f"The parameter model should be chosen from {cls.VALID_MODEL_NAMES} "
f"and it is default to be None."
)
instance = cls(api_key=api_key)
params = {"input": inpu... | if model is not None and model not in cls.VALID_MODEL_NAMES:
raise ValueError(
f"The parameter model should be chosen from {cls.VALID_MODEL_NAMES} "
f"and it is default to be None."
)
instance = cls(api_key=api_key)
params = {"input": inpu... | 47 | 294 | 126 | 420 | from typing import List, Optional, Union
from openai.openai_object import OpenAIObject
class Moderation(OpenAIObject):
VALID_MODEL_NAMES: List[str] = ["text-moderation-stable", "text-moderation-latest"]
@classmethod
def get_url(cls):
return "/moderations"
@classmethod
def _prepare_creat... | from typing import List, Optional, Union
from openai.openai_object import OpenAIObject
class Moderation(OpenAIObject):
VALID_MODEL_NAMES: List[str] = ["text-moderation-stable", "text-moderation-latest"]
@classmethod
def get_url(cls):
return "/moderations"
@classmethod
def _prepare_creat... |
36,003 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 315,317 | 296,333 | translate | Audio | 317,333 | 317,333 | class Audio:
@classmethod
def transcribe(cls, args):
with open(args.file, "rb") as r:
file_reader = BufferReader(r.read(), desc="Upload progress")
resp = openai.Audio.transcribe_raw(
# Required
model=args.model,
file=file_reader,
filen... | class Audio:
@classmethod
def transcribe(cls, args):
with open(args.file, "rb") as r:
file_reader = BufferReader(r.read(), desc="Upload progress")
resp = openai.Audio.transcribe_raw(
# Required
model=args.model,
file=file_reader,
filen... | with open(args.file, "rb") as r:
file_reader = BufferReader(r.read(), desc="Upload progress")
resp = openai.Audio.translate_raw(
# Required
model=args.model,
file=file_reader,
filename=args.file,
# Optional
response_form... | with open(args.file, "rb") as r:
file_reader = BufferReader(r.read(), desc="Upload progress")
resp = openai.Audio.translate_raw(
# Required
model=args.model,
file=file_reader,
filename=args.file,
# Optional
response_form... | 26 | 174 | 145 | 319 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,004 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 112,114 | 111,149 | create | ChatCompletion | 114,149 | 114,149 | class ChatCompletion:
@classmethod
def create(cls, args):
FILL_FUNC_BODY | class ChatCompletion:
@classmethod
def create(cls, args):
FILL_FUNC_BODY | if args.n is not None and args.n > 1 and args.stream:
raise ValueError(
"Can't stream chat completions with n>1 with the current CLI"
)
messages = [
{"role": role, "content": content} for role, content in args.message
]
resp = openai.... | if args.n is not None and args.n > 1 and args.stream:
raise ValueError(
"Can't stream chat completions with n>1 with the current CLI"
)
messages = [
{"role": role, "content": content} for role, content in args.message
]
resp = openai.... | 90 | 30 | 356 | 386 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,005 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 150,152 | 149,187 | create | Completion | 152,187 | 152,187 | class Completion:
@classmethod
def create(cls, args):
FILL_FUNC_BODY | class Completion:
@classmethod
def create(cls, args):
FILL_FUNC_BODY | if args.n is not None and args.n > 1 and args.stream:
raise ValueError("Can't stream completions with n>1 with the current CLI")
if args.engine and args.model:
warnings.warn(
"In most cases, you should not be specifying both engine and model."
)
... | if args.n is not None and args.n > 1 and args.stream:
raise ValueError("Can't stream completions with n>1 with the current CLI")
if args.engine and args.model:
warnings.warn(
"In most cases, you should not be specifying both engine and model."
)
... | 90 | 29 | 377 | 406 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,006 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 203,205 | 187,209 | create | Deployment | 205,209 | 205,209 | class Deployment:
@classmethod
def get(cls, args):
resp = openai.Deployment.retrieve(id=args.id)
print(resp)
@classmethod
def delete(cls, args):
model = openai.Deployment.delete(args.id)
print(model)
@classmethod
def list(cls, args):
models = openai.Depl... | class Deployment:
@classmethod
def get(cls, args):
resp = openai.Deployment.retrieve(id=args.id)
print(resp)
@classmethod
def delete(cls, args):
model = openai.Deployment.delete(args.id)
print(model)
@classmethod
def list(cls, args):
models = openai.Depl... | models = openai.Deployment.create(model=args.model, scale_settings={"scale_type": args.scale_type})
print(models)
| models = openai.Deployment.create(model=args.model, scale_settings={"scale_type": args.scale_type})
print(models)
| 6 | 139 | 45 | 184 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,007 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 70,72 | 59,111 | generate | Engine | 72,105 | 72,105 | class Engine:
@classmethod
def get(cls, args):
engine = openai.Engine.retrieve(id=args.id)
display(engine)
@classmethod
def update(cls, args):
engine = openai.Engine.modify(args.id, replicas=args.replicas)
display(engine)
@classmethod
def generate(cls, args):
FI... | class Engine:
@classmethod
def get(cls, args):
engine = openai.Engine.retrieve(id=args.id)
display(engine)
@classmethod
def update(cls, args):
engine = openai.Engine.modify(args.id, replicas=args.replicas)
display(engine)
@classmethod
def generate(cls, args):
FI... | warnings.warn(
"Engine.generate is deprecated, use Completion.create", DeprecationWarning
)
if args.completions and args.completions > 1 and args.stream:
raise ValueError("Can't stream multiple completions with openai CLI")
kwargs = {}
if args.model is no... | warnings.warn(
"Engine.generate is deprecated, use Completion.create", DeprecationWarning
)
if args.completions and args.completions > 1 and args.stream:
raise ValueError("Can't stream multiple completions with openai CLI")
kwargs = {}
if args.model is no... | 81 | 147 | 363 | 510 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,008 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 248,250 | 226,254 | list | File | 250,254 | 250,254 | class File:
@classmethod
def create(cls, args):
with open(args.file, "rb") as file_reader:
buffer_reader = BufferReader(file_reader.read(), desc="Upload progress")
resp = openai.File.create(
file=buffer_reader,
purpose=args.purpose,
user_provided_f... | class File:
@classmethod
def create(cls, args):
with open(args.file, "rb") as file_reader:
buffer_reader = BufferReader(file_reader.read(), desc="Upload progress")
resp = openai.File.create(
file=buffer_reader,
purpose=args.purpose,
user_provided_f... | file = openai.File.list()
print(file)
| file = openai.File.list()
print(file)
| 4 | 206 | 23 | 229 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,010 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 265,267 | 254,296 | create_variation | Image | 267,277 | 267,277 | class Image:
@classmethod
def create(cls, args):
resp = openai.Image.create(
prompt=args.prompt,
size=args.size,
n=args.num_images,
response_format=args.response_format,
)
print(resp)
@classmethod
def create_variation(cls, args):
F... | class Image:
@classmethod
def create(cls, args):
resp = openai.Image.create(
prompt=args.prompt,
size=args.size,
n=args.num_images,
response_format=args.response_format,
)
print(resp)
@classmethod
def create_variation(cls, args):
F... | with open(args.image, "rb") as file_reader:
buffer_reader = BufferReader(file_reader.read(), desc="Upload progress")
resp = openai.Image.create_variation(
image=buffer_reader,
size=args.size,
n=args.num_images,
response_format=args.response_for... | with open(args.image, "rb") as file_reader:
buffer_reader = BufferReader(file_reader.read(), desc="Upload progress")
resp = openai.Image.create_variation(
image=buffer_reader,
size=args.size,
n=args.num_images,
response_format=args.response_for... | 19 | 295 | 111 | 406 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,011 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 220,222 | 209,226 | list | Model | 222,226 | 222,226 | class Model:
@classmethod
def get(cls, args):
resp = openai.Model.retrieve(id=args.id)
print(resp)
@classmethod
def delete(cls, args):
model = openai.Model.delete(args.id)
print(model)
@classmethod
def list(cls, args):
FILL_FUNC_BODY | class Model:
@classmethod
def get(cls, args):
resp = openai.Model.retrieve(id=args.id)
print(resp)
@classmethod
def delete(cls, args):
model = openai.Model.delete(args.id)
print(model)
@classmethod
def list(cls, args):
FILL_FUNC_BODY | models = openai.Model.list()
print(models)
| models = openai.Model.list()
print(models)
| 4 | 103 | 23 | 126 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,012 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/cli.py | 602,604 | 601,616 | sync | WandbLogger | 604,616 | 604,616 | class WandbLogger:
@classmethod
def sync(cls, args):
FILL_FUNC_BODY | class WandbLogger:
@classmethod
def sync(cls, args):
FILL_FUNC_BODY | import openai.wandb_logger
resp = openai.wandb_logger.WandbLogger.sync(
id=args.id,
n_fine_tunes=args.n_fine_tunes,
project=args.project,
entity=args.entity,
force=args.force,
)
print(resp)
| import openai.wandb_logger
resp = openai.wandb_logger.WandbLogger.sync(
id=args.id,
n_fine_tunes=args.n_fine_tunes,
project=args.project,
entity=args.entity,
force=args.force,
)
print(resp)
| 12 | 31 | 107 | 138 | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... | import datetime
import os
import signal
import sys
import warnings
from typing import Optional
import requests
import openai
from openai.upload_progress import BufferReader
from openai.validators import (
apply_necessary_remediation,
apply_validators,
get_validators,
read_any_format,
write_out_fil... |
36,013 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/datalib.py | 54,55 | 1,57 | assert_has_pandas | 55,57 | 55,57 | """
This module helps make data libraries like `numpy` and `pandas` optional dependencies.
The libraries add up to 130MB+, which makes it challenging to deploy applications
using this library in environments with code size constraints, like AWS Lambda.
This module serves as an import proxy and provides a few utilitie... | """
This module helps make data libraries like `numpy` and `pandas` optional dependencies.
The libraries add up to 130MB+, which makes it challenging to deploy applications
using this library in environments with code size constraints, like AWS Lambda.
This module serves as an import proxy and provides a few utilitie... | if not HAS_PANDAS:
raise MissingDependencyError(PANDAS_INSTRUCTIONS)
| if not HAS_PANDAS:
raise MissingDependencyError(PANDAS_INSTRUCTIONS)
| 5 | 407 | 31 | 438 | """
This module helps make data libraries like `numpy` and `pandas` optional dependencies.
The libraries add up to 130MB+, which makes it challenging to deploy applications
using this library in environments with code size constraints, like AWS Lambda.
This module serves as an import proxy and provides a few utilitie... | """
This module helps make data libraries like `numpy` and `pandas` optional dependencies.
The libraries add up to 130MB+, which makes it challenging to deploy applications
using this library in environments with code size constraints, like AWS Lambda.
This module serves as an import proxy and provides a few utilitie... | |
36,014 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/error.py | 58,59 | 4,71 | construct_error_object | OpenAIError | 59,71 | 59,71 | class OpenAIError(Exception):
def __init__(
self,
message=None,
http_body=None,
http_status=None,
json_body=None,
headers=None,
code=None,
):
super(OpenAIError, self).__init__(message)
if http_body and hasattr(http_body, "decode"):
... | class OpenAIError(Exception):
def __init__(
self,
message=None,
http_body=None,
http_status=None,
json_body=None,
headers=None,
code=None,
):
super(OpenAIError, self).__init__(message)
if http_body and hasattr(http_body, "decode"):
... | if (
self.json_body is None
or "error" not in self.json_body
or not isinstance(self.json_body["error"], dict)
):
return None
return openai.api_resources.error_object.ErrorObject.construct_from(
self.json_body["error"]
)
| if (
self.json_body is None
or "error" not in self.json_body
or not isinstance(self.json_body["error"], dict)
):
return None
return openai.api_resources.error_object.ErrorObject.construct_from(
self.json_body["error"]
)
| 21 | 529 | 100 | 629 | import openai
class OpenAIError(Exception):
def __init__(
self,
message=None,
http_body=None,
http_status=None,
json_body=None,
headers=None,
code=None,
):
super(OpenAIError, self).__init__(message)
if http_body and hasattr(http_body, "d... | import openai
class OpenAIError(Exception):
def __init__(
self,
message=None,
http_body=None,
http_status=None,
json_body=None,
headers=None,
code=None,
):
super(OpenAIError, self).__init__(message)
if http_body and hasattr(http_body, "d... |
36,016 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/openai_response.py | 13,15 | 4,21 | organization | OpenAIResponse | 15,17 | 15,17 | class OpenAIResponse:
def __init__(self, data, headers):
self._headers = headers
self.data = data
@property
def request_id(self) -> Optional[str]:
return self._headers.get("request-id")
@property
def organization(self) -> Optional[str]:
FILL_FUNC_BODY @property
def r... | class OpenAIResponse:
def __init__(self, data, headers):
self._headers = headers
self.data = data
@property
def request_id(self) -> Optional[str]:
return self._headers.get("request-id")
@property
def organization(self) -> Optional[str]:
FILL_FUNC_BODY @property
def r... | return self._headers.get("OpenAI-Organization")
| return self._headers.get("OpenAI-Organization")
| 2 | 145 | 18 | 163 | from typing import Optional
class OpenAIResponse:
def __init__(self, data, headers):
self._headers = headers
self.data = data
@property
def request_id(self) -> Optional[str]:
return self._headers.get("request-id")
@property
def organization(self) -> Optional[str]:
FILL_FU... | from typing import Optional
class OpenAIResponse:
def __init__(self, data, headers):
self._headers = headers
self.data = data
@property
def request_id(self) -> Optional[str]:
return self._headers.get("request-id")
@property
def organization(self) -> Optional[str]:
FILL_FU... |
36,017 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/upload_progress.py | 36,37 | 1,53 | progress | 37,51 | 37,51 | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... | import tqdm # type: ignore
meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc)
def incr(progress):
meter.n = progress
if progress == total:
meter.close()
else:
meter.refresh()
return incr
| import tqdm # type: ignore
meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc)
def incr(progress):
meter.n = progress
if progress == total:
meter.close()
else:
meter.refresh()
return incr
| 24 | 298 | 100 | 398 | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... | |
36,018 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/upload_progress.py | 25,26 | 15,36 | read | BufferReader | 26,36 | 26,36 | class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
io.BytesIO.__init__(self, buf)
self._progress = 0
self._callback = progress(len(buf), desc=desc)
def __len__(self):
return self._len
def read(self, n=-1):
FILL_FUNC_BODY | class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
io.BytesIO.__init__(self, buf)
self._progress = 0
self._callback = progress(len(buf), desc=desc)
def __len__(self):
return self._len
def read(self, n=-1):
FILL_FUNC_BODY | chunk = io.BytesIO.read(self, n)
self._progress += len(chunk)
if self._callback:
try:
self._callback(self._progress)
except Exception as e: # catches exception from the callback
raise CancelledError("The upload was cancelled: {}".format(e)... | chunk = io.BytesIO.read(self, n)
self._progress += len(chunk)
if self._callback:
try:
self._callback(self._progress)
except Exception as e: # catches exception from the callback
raise CancelledError("The upload was cancelled: {}".format(e)... | 29 | 112 | 98 | 210 | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... | import io
class CancelledError(Exception):
def __init__(self, msg):
self.msg = msg
Exception.__init__(self, msg)
def __str__(self):
return self.msg
__repr__ = __str__
class BufferReader(io.BytesIO):
def __init__(self, buf=b"", desc=None):
self._len = len(buf)
... |
36,019 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/util.py | 176,177 | 1,189 | default_api_key | 177,189 | 177,189 | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... | if openai.api_key_path:
with open(openai.api_key_path, "rt") as k:
api_key = k.read().strip()
if not api_key.startswith("sk-"):
raise ValueError(f"Malformed API key in {openai.api_key_path}.")
return api_key
elif openai.api_key is not None:
ret... | if openai.api_key_path:
with open(openai.api_key_path, "rt") as k:
api_key = k.read().strip()
if not api_key.startswith("sk-"):
raise ValueError(f"Malformed API key in {openai.api_key_path}.")
return api_key
elif openai.api_key is not None:
ret... | 99 | 1,497 | 266 | 1,763 | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... | |
36,020 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/openai/util.py | 33,35 | 28,47 | from_str | ApiType | 35,47 | 35,47 | class ApiType(Enum):
AZURE = 1
OPEN_AI = 2
AZURE_AD = 3
@staticmethod
def from_str(label):
FILL_FUNC_BODY | class ApiType(Enum):
AZURE = 1
OPEN_AI = 2
AZURE_AD = 3
@staticmethod
def from_str(label):
FILL_FUNC_BODY | if label.lower() == "azure":
return ApiType.AZURE
elif label.lower() in ("azure_ad", "azuread"):
return ApiType.AZURE_AD
elif label.lower() in ("open_ai", "openai"):
return ApiType.OPEN_AI
else:
raise openai.error.InvalidAPIType(
... | if label.lower() == "azure":
return ApiType.AZURE
elif label.lower() in ("azure_ad", "azuread"):
return ApiType.AZURE_AD
elif label.lower() in ("open_ai", "openai"):
return ApiType.OPEN_AI
else:
raise openai.error.InvalidAPIType(
... | 41 | 57 | 150 | 207 | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... | import logging
import os
import re
import sys
from enum import Enum
from typing import Optional
import openai
OPENAI_LOG = os.environ.get("OPENAI_LOG")
logger = logging.getLogger("openai")
__all__ = [
"log_info",
"log_debug",
"log_warn",
"logfmt",
]
api_key_to_header = (
lambda api, key: {"Auth... |
36,021 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/requests/_internal_utils.py | 23,24 | 1,49 | to_native_string | 28,36 | 24,36 | """
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
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.c... | """
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
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.c... | if isinstance(string, builtin_str):
out = string
else:
out = string.decode(encoding)
return out
| """Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, builtin_str):
out = string
else:
out = string.decode(encodin... | 12 | 458 | 47 | 505 | """
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
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.c... | """
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
_VALID_HEADER_NAME_RE_BYTE = re.compile(rb"^[^:\s][^:\r\n]*$")
_VALID_HEADER_NAME_RE_STR = re.c... | |
36,022 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/requests/adapters.py | 77,80 | 71,101 | send | BaseAdapter | 94,96 | 80,96 | class BaseAdapter:
"""The Base Transport Adapter"""
def __init__(self):
super().__init__()
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
FILL_FUNC_BODY def close(self):
"""Cleans up adapter specific items."""
raise NotIm... | class BaseAdapter:
"""The Base Transport Adapter"""
def __init__(self):
super().__init__()
def send(
self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:... | raise NotImplementedError
| """Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data befor... | 2 | 315 | 11 | 326 | """
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket # noqa: F401
from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from url... | """
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket # noqa: F401
from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from url... |
36,024 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/requests/api.py | 88,89 | 1,158 | head | 89,103 | 89,103 | """
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the ... | """
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the ... | r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes. If
`allow_redirects` is not provided, it will be set to `False` (as
opposed to the default :meth:`request` behavior).
:return: :class:`Response <R... | r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes. If
`allow_redirects` is not provided, it will be set to `False` (as
opposed to the default :meth:`request` behavior).
:return: :class:`Response <R... | 50 | 1,767 | 158 | 1,925 | """
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the ... | """
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the ... | |
36,028 | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT | /home/hieuvd/dung_repo/raw/stars_02/gd3kr_BlenderGPT/BlenderGPT/lib/requests/cookies.py | 49,50 | 23,103 | get_full_url | MockRequest | 50,69 | 50,69 | class MockRequest:
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request o... | class MockRequest:
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request o... | # Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get("Host"):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers["Host"], encoding="utf-8")
... | # Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get("Host"):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers["Host"], encoding="utf-8")
... | 59 | 550 | 181 | 731 | """
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import calendar
import copy
import time
from ._internal_utils import to_native_string
from .compat import Morsel, MutableMapping, cookieli... | """
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import calendar
import copy
import time
from ._internal_utils import to_native_string
from .compat import Morsel, MutableMapping, cookieli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.