prompt_id
int64
0
941
project
stringclasses
24 values
module
stringlengths
7
49
class
stringlengths
0
32
method
stringlengths
2
37
focal_method_txt
stringlengths
43
41.5k
focal_method_lines
listlengths
2
2
in_stack
bool
2 classes
globals
listlengths
0
16
type_context
stringlengths
79
41.9k
has_branch
bool
2 classes
total_branches
int64
0
3
745
tornado
tornado.simple_httpclient
_HTTPConnection
on_connection_close
def on_connection_close(self) -> None: if self.final_callback is not None: message = "Connection closed" if self.stream.error: raise self.stream.error try: raise HTTPStreamClosedError(message) except HTTPStreamClosedError: ...
[ 577, 585 ]
false
[]
from tornado.escape import _unicode from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy, HTTPRequest, ) from tornado import httputil from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters from tor...
true
2
746
tornado
tornado.simple_httpclient
_HTTPConnection
headers_received
async def headers_received( self, first_line: Union[httputil.ResponseStartLine, httputil.RequestStartLine], headers: httputil.HTTPHeaders, ) -> None: assert isinstance(first_line, httputil.ResponseStartLine) if self.request.expect_100_continue and first_line.code == 100: ...
[ 587, 608 ]
false
[]
from tornado.escape import _unicode from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy, HTTPRequest, ) from tornado import httputil from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters from tor...
true
2
747
tornado
tornado.simple_httpclient
_HTTPConnection
finish
def finish(self) -> None: assert self.code is not None data = b"".join(self.chunks) self._remove_timeout() original_request = getattr(self.request, "original_request", self.request) if self._should_follow_redirect(): assert isinstance(self.request, _RequestProxy) ...
[ 621, 681 ]
false
[]
from tornado.escape import _unicode from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy, HTTPRequest, ) from tornado import httputil from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters from tor...
true
2
748
tornado
tornado.simple_httpclient
_HTTPConnection
data_received
def data_received(self, chunk: bytes) -> None: if self._should_follow_redirect(): # We're going to follow a redirect so just discard the body. return if self.request.streaming_callback is not None: self.request.streaming_callback(chunk) else: s...
[ 686, 693 ]
false
[]
from tornado.escape import _unicode from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy, HTTPRequest, ) from tornado import httputil from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters from tor...
true
2
749
tornado
tornado.tcpclient
_Connector
__init__
def __init__( self, addrinfo: List[Tuple], connect: Callable[ [socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"] ], ) -> None: self.io_loop = IOLoop.current() self.connect = connect self.future = ( Future() ...
[ 54, 72 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
false
0
750
tornado
tornado.tcpclient
_Connector
split
@staticmethod def split( addrinfo: List[Tuple], ) -> Tuple[ List[Tuple[socket.AddressFamily, Tuple]], List[Tuple[socket.AddressFamily, Tuple]], ]: """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry fr...
[ 75, 97 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
751
tornado
tornado.tcpclient
_Connector
start
def start( self, timeout: float = _INITIAL_CONNECT_TIMEOUT, connect_timeout: Optional[Union[float, datetime.timedelta]] = None, ) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]": self.try_connect(iter(self.primary_addrs)) self.set_timeout(timeout) if conne...
[ 99, 108 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
752
tornado
tornado.tcpclient
_Connector
try_connect
def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None: try: af, addr = next(addrs) except StopIteration: # We've reached the end of our queue, but the other queue # might still be working. Send a final error on the future ...
[ 110, 124 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
753
tornado
tornado.tcpclient
_Connector
on_connect_done
def on_connect_done( self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]], af: socket.AddressFamily, addr: Tuple, future: "Future[IOStream]", ) -> None: self.remaining -= 1 try: stream = future.result() except Exception as e: ...
[ 128, 158 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
754
tornado
tornado.tcpclient
_Connector
set_timeout
def set_timeout(self, timeout: float) -> None: self.timeout = self.io_loop.add_timeout( self.io_loop.time() + timeout, self.on_timeout )
[ 160, 161 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
false
0
755
tornado
tornado.tcpclient
_Connector
on_timeout
def on_timeout(self) -> None: self.timeout = None if not self.future.done(): self.try_connect(iter(self.secondary_addrs))
[ 165, 168 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
756
tornado
tornado.tcpclient
_Connector
clear_timeout
def clear_timeout(self) -> None: if self.timeout is not None: self.io_loop.remove_timeout(self.timeout)
[ 170, 172 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
757
tornado
tornado.tcpclient
_Connector
set_connect_timeout
def set_connect_timeout( self, connect_timeout: Union[float, datetime.timedelta] ) -> None: self.connect_timeout = self.io_loop.add_timeout( connect_timeout, self.on_connect_timeout )
[ 174, 177 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
false
0
758
tornado
tornado.tcpclient
_Connector
on_connect_timeout
def on_connect_timeout(self) -> None: if not self.future.done(): self.future.set_exception(TimeoutError()) self.close_streams()
[ 181, 184 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
759
tornado
tornado.tcpclient
_Connector
clear_timeouts
def clear_timeouts(self) -> None: if self.timeout is not None: self.io_loop.remove_timeout(self.timeout) if self.connect_timeout is not None: self.io_loop.remove_timeout(self.connect_timeout)
[ 186, 190 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
760
tornado
tornado.tcpclient
_Connector
close_streams
def close_streams(self) -> None: for stream in self.streams: stream.close()
[ 192, 194 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
761
tornado
tornado.tcpclient
TCPClient
connect
async def connect( self, host: str, port: int, af: socket.AddressFamily = socket.AF_UNSPEC, ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None, max_buffer_size: Optional[int] = None, source_ip: Optional[str] = None, source_port: Option...
[ 216, 290 ]
false
[ "_INITIAL_CONNECT_TIMEOUT" ]
import functools import socket import numbers import datetime import ssl from tornado.concurrent import Future, future_add_done_callback from tornado.ioloop import IOLoop from tornado.iostream import IOStream from tornado import gen from tornado.netutil import Resolver from tornado.gen import TimeoutError from typing i...
true
2
762
tornado
tornado.util
import_object
def import_object(name: str) -> Any: """Imports an object by name. ``import_object('x')`` is equivalent to ``import x``. ``import_object('x.y.z')`` is equivalent to ``from x.y import z``. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object...
[ 130, 156 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
763
tornado
tornado.util
raise_exc_info
def raise_exc_info( exc_info, # type: Tuple[Optional[type], Optional[BaseException], Optional[TracebackType]] ): # type: (...) -> typing.NoReturn # # This function's type annotation must use comments instead of # real annotations because typing.NoReturn does not exist in # python 3.5's typing m...
[ 169, 186 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
764
tornado
tornado.util
errno_from_exception
def errno_from_exception(e: BaseException) -> Optional[int]: """Provides the errno from an Exception object. There are cases that the errno attribute was not set so we pull the errno out of the args but if someone instantiates an Exception without any args you will get a tuple error. So this function ...
[ 189, 204 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
765
tornado
tornado.util
ObjectDict
__getattr__
def __getattr__(self, name: str) -> Any: try: return self[name] except KeyError: raise AttributeError(name)
[ 79, 83 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
false
0
766
tornado
tornado.util
Configurable
__new__
def __new__(cls, *args: Any, **kwargs: Any) -> Any: base = cls.configurable_base() init_kwargs = {} # type: Dict[str, Any] if cls is base: impl = cls.configured_class() if base.__impl_kwargs: init_kwargs.update(base.__impl_kwargs) else: ...
[ 270, 288 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
767
tornado
tornado.util
ArgReplacer
__init__
def __init__(self, func: Callable, name: str) -> None: self.name = name try: self.arg_pos = self._getargnames(func).index(name) # type: Optional[int] except ValueError: # Not a positional parameter self.arg_pos = None
[ 375, 381 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
false
0
768
tornado
tornado.util
ArgReplacer
get_old_value
def get_old_value( self, args: Sequence[Any], kwargs: Dict[str, Any], default: Any = None ) -> Any: """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self.arg_pos is not None and len(args) > se...
[ 398, 408 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
769
tornado
tornado.util
ArgReplacer
replace
def replace( self, new_value: Any, args: Sequence[Any], kwargs: Dict[str, Any] ) -> Tuple[Any, Sequence[Any], Dict[str, Any]]: """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objec...
[ 410, 431 ]
false
[ "bytes_type", "unicode_type", "basestring_type", "_alphanum", "_re_unescape_pattern" ]
import array import atexit from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) bytes_type = bytes unicode_type = str basestring_type = str _alphanum = ...
true
2
770
tqdm
tqdm._tqdm_pandas
tqdm_pandas
def tqdm_pandas(tclass, **tqdm_kwargs): """ Registers the given `tqdm` instance with `pandas.core.groupby.DataFrameGroupBy.progress_apply`. """ from tqdm import TqdmDeprecationWarning if isinstance(tclass, type) or (getattr(tclass, '__name__', '').startswith( 'tqdm_')): # delayed a...
[ 6, 23 ]
false
[ "__author__", "__all__" ]
import sys __author__ = "github.com/casperdcl" __all__ = ['tqdm_pandas'] def tqdm_pandas(tclass, **tqdm_kwargs): """ Registers the given `tqdm` instance with `pandas.core.groupby.DataFrameGroupBy.progress_apply`. """ from tqdm import TqdmDeprecationWarning if isinstance(tclass, type) or (geta...
true
2
771
tqdm
tqdm.contrib.itertools
product
def product(*iterables, **tqdm_kwargs): """ Equivalent of `itertools.product`. Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ kwargs = tqdm_kwargs.copy() tqdm_class = kwargs.pop("tqdm_class", tqdm_auto) try: lens = list(map(len, iterables)) except Typ...
[ 13, 35 ]
false
[ "__author__", "__all__" ]
import itertools from ..auto import tqdm as tqdm_auto __author__ = {"github.com/": ["casperdcl"]} __all__ = ['product'] def product(*iterables, **tqdm_kwargs): """ Equivalent of `itertools.product`. Parameters ---------- tqdm_class : [default: tqdm.auto.tqdm]. """ kwargs = tqdm_kwargs.co...
true
2
772
tqdm
tqdm.contrib.logging
_TqdmLoggingHandler
emit
def emit(self, record): try: msg = self.format(record) self.tqdm_class.write(msg, file=self.stream) self.flush() except (KeyboardInterrupt, SystemExit): raise except: # noqa pylint: disable=bare-except self.handleError(record)
[ 25, 33 ]
false
[]
import logging import sys from contextlib import contextmanager from ..std import tqdm as std_tqdm class _TqdmLoggingHandler(logging.StreamHandler): def __init__( self, tqdm_class=std_tqdm # type: Type[std_tqdm] ): super(_TqdmLoggingHandler, self).__init__() self.tqdm_class ...
false
0
773
tqdm
tqdm.contrib.telegram
TelegramIO
write
def write(self, s): """Replaces internal `message_id`'s text with `s`.""" if not s: s = "..." s = s.replace('\r', '').strip() if s == self.text: return # avoid duplicate message Bot error message_id = self.message_id if message_id is None: ...
[ 58, 77 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
true
2
774
tqdm
tqdm.contrib.telegram
TelegramIO
delete
def delete(self): """Deletes internal `message_id`.""" try: future = self.submit( self.session.post, self.API + '%s/deleteMessage' % self.token, data={'chat_id': self.chat_id, 'message_id': self.message_id}) except Exception as e: tqdm_...
[ 79, 88 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
false
0
775
tqdm
tqdm.contrib.telegram
tqdm_telegram
__init__
def __init__(self, *args, **kwargs): """ Parameters ---------- token : str, required. Telegram token [default: ${TQDM_TELEGRAM_TOKEN}]. chat_id : str, required. Telegram chat ID [default: ${TQDM_TELEGRAM_CHAT_ID}]. See `tqdm.auto.tqdm.__init...
[ 107, 123 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
true
2
776
tqdm
tqdm.contrib.telegram
tqdm_telegram
display
def display(self, **kwargs): super(tqdm_telegram, self).display(**kwargs) fmt = self.format_dict if fmt.get('bar_format', None): fmt['bar_format'] = fmt['bar_format'].replace( '<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}') else: fmt['bar_...
[ 125, 133 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
true
2
777
tqdm
tqdm.contrib.telegram
tqdm_telegram
clear
def clear(self, *args, **kwargs): super(tqdm_telegram, self).clear(*args, **kwargs) if not self.disable: self.tgio.write("")
[ 135, 138 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
true
2
778
tqdm
tqdm.contrib.telegram
tqdm_telegram
close
def close(self): if self.disable: return super(tqdm_telegram, self).close() if not (self.leave or (self.leave is None and self.pos == 0)): self.tgio.delete()
[ 140, 145 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from os import getenv from warnings import warn from requests import Session from ..auto import tqdm as tqdm_auto from ..std import TqdmWarning from ..utils import _range from .utils_worker import MonoWorker __author__ = {"github.com/": ["casperdcl"]} __all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'tran...
true
2
779
tqdm
tqdm.contrib.utils_worker
MonoWorker
submit
def submit(self, func, *args, **kwargs): """`func(*args, **kwargs)` may replace currently waiting task.""" futures = self.futures if len(futures) == futures.maxlen: running = futures.popleft() if not running.done(): if len(futures): # clear waiting ...
[ 23, 39 ]
false
[ "__author__", "__all__" ]
from collections import deque from concurrent.futures import ThreadPoolExecutor from ..auto import tqdm as tqdm_auto __author__ = {"github.com/": ["casperdcl"]} __all__ = ['MonoWorker'] class MonoWorker(object): def __init__(self): self.pool = ThreadPoolExecutor(max_workers=1) self.futures = dequ...
true
2
780
tqdm
tqdm.gui
tqdm_gui
__init__
def __init__(self, *args, **kwargs): from collections import deque import matplotlib as mpl import matplotlib.pyplot as plt kwargs = kwargs.copy() kwargs['gui'] = True colour = kwargs.pop('colour', 'g') super(tqdm_gui, self).__init__(*args, **kwargs) ...
[ 28, 87 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re from warnings import warn from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl", "lrq3000"]} __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange'] tqdm = tqdm_gui trange = tgrange class tqdm_gui(std_tqdm): # pragma: no c...
false
0
781
tqdm
tqdm.gui
tqdm_gui
close
def close(self): if self.disable: return self.disable = True with self.get_lock(): self._instances.remove(self) # Restore toolbars self.mpl.rcParams['toolbar'] = self.toolbar # Return to non-interactive mode if not self.wasion: ...
[ 89, 106 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re from warnings import warn from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl", "lrq3000"]} __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange'] tqdm = tqdm_gui trange = tgrange class tqdm_gui(std_tqdm): # pragma: no c...
false
0
782
tqdm
tqdm.gui
tqdm_gui
clear
def clear(self, *_, **__): pass
[ 108, 109 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re from warnings import warn from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl", "lrq3000"]} __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange'] tqdm = tqdm_gui trange = tgrange class tqdm_gui(std_tqdm): # pragma: no c...
false
0
783
tqdm
tqdm.gui
tqdm_gui
display
def display(self, *_, **__): n = self.n cur_t = self._time() elapsed = cur_t - self.start_t delta_it = n - self.last_print_n delta_t = cur_t - self.last_print_t # Inline due to multiple calls total = self.total xdata = self.xdata ydata = self....
[ 111, 177 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re from warnings import warn from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl", "lrq3000"]} __all__ = ['tqdm_gui', 'tgrange', 'tqdm', 'trange'] tqdm = tqdm_gui trange = tgrange class tqdm_gui(std_tqdm): # pragma: no c...
false
0
784
tqdm
tqdm.notebook
TqdmHBox
__repr__
def __repr__(self, pretty=False): pbar = getattr(self, 'pbar', None) if pbar is None: return super(TqdmHBox, self).__repr__() return pbar.format_meter(**self._repr_json_(pretty))
[ 86, 90 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class TqdmHBox(HBox): def __repr__(self,...
true
2
785
tqdm
tqdm.notebook
tqdm_notebook
status_printer
@staticmethod def status_printer(_, total=None, desc=None, ncols=None): """ Manage the printing of an IPython/Jupyter Notebook progress bar widget. """ # Fallback to text bar if there's no total # DEPRECATED: replaced with an 'info' style bar # if not total: ...
[ 101, 146 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
786
tqdm
tqdm.notebook
tqdm_notebook
display
def display(self, msg=None, pos=None, # additional signals close=False, bar_style=None, check_delay=True): # Note: contrary to native tqdm, msg='' does NOT clear bar # goal is to keep all infos if error happens so user knows # at which iteration the loop faile...
[ 148, 197 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
787
tqdm
tqdm.notebook
tqdm_notebook
__init__
def __init__(self, *args, **kwargs): """ Supports the usual `tqdm.tqdm` parameters as well as those listed below. Parameters ---------- display : Whether to call `display(self.container)` immediately [default: True]. """ kwargs = kwargs.copy() ...
[ 209, 252 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
788
tqdm
tqdm.notebook
tqdm_notebook
__iter__
def __iter__(self): try: for obj in super(tqdm_notebook, self).__iter__(): # return super(tqdm...) will not catch exception yield obj # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt except: # NOQA self.disp(bar_style=...
[ 254, 262 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
789
tqdm
tqdm.notebook
tqdm_notebook
update
def update(self, n=1): try: return super(tqdm_notebook, self).update(n=n) # NB: except ... [ as ...] breaks IPython async KeyboardInterrupt except: # NOQA # cannot catch KeyboardInterrupt when using manual tqdm # as the interrupt will most likely happen o...
[ 266, 274 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
false
0
790
tqdm
tqdm.notebook
tqdm_notebook
close
def close(self): if self.disable: return super(tqdm_notebook, self).close() # Try to detect if there was an error or KeyboardInterrupt # in manual mode: if n < total, things probably got wrong if self.total and self.n < self.total: self.disp(bar_style=...
[ 278, 290 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
791
tqdm
tqdm.notebook
tqdm_notebook
clear
def clear(self, *_, **__): pass
[ 292, 293 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
false
0
792
tqdm
tqdm.notebook
tqdm_notebook
reset
def reset(self, total=None): """ Resets to 0 iterations for repeated use. Consider combining with `leave=True`. Parameters ---------- total : int or float, optional. Total to use for the new bar. """ if self.disable: return super(tqdm_no...
[ 295, 313 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
import re import sys from weakref import proxy from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["lrq3000", "casperdcl", "alexanderkuk"]} __all__ = ['tqdm_notebook', 'tnrange', 'tqdm', 'trange'] tqdm = tqdm_notebook trange = tnrange class tqdm_notebook(std_tqdm): def __ini...
true
2
793
tqdm
tqdm.rich
FractionColumn
render
def render(self, task): """Calculate common unit for completed and total.""" completed = int(task.completed) total = int(task.total) if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( total, ["", "K", "M", "G", "T", "P", "E",...
[ 30, 43 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
true
2
794
tqdm
tqdm.rich
RateColumn
render
def render(self, task): """Show data transfer speed.""" speed = task.speed if speed is None: return Text(f"? {self.unit}/s", style="progress.data.speed") if self.unit_scale: unit, suffix = filesize.pick_unit_and_suffix( speed, [...
[ 56, 70 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
true
2
795
tqdm
tqdm.rich
tqdm_rich
__init__
def __init__(self, *args, **kwargs): """ This class accepts the following parameters *in addition* to the parameters accepted by `tqdm`. Parameters ---------- progress : tuple, optional arguments for `rich.progress.Progress()`. """ kwargs...
[ 77, 112 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
false
0
796
tqdm
tqdm.rich
tqdm_rich
close
def close(self): if self.disable: return super(tqdm_rich, self).close() self._prog.__exit__(None, None, None)
[ 114, 118 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
false
0
797
tqdm
tqdm.rich
tqdm_rich
clear
def clear(self, *_, **__): pass
[ 120, 121 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
false
0
798
tqdm
tqdm.rich
tqdm_rich
display
def display(self, *_, **__): if not hasattr(self, '_prog'): return self._prog.update(self._task_id, completed=self.n, description=self.desc)
[ 123, 126 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
false
0
799
tqdm
tqdm.rich
tqdm_rich
reset
def reset(self, total=None): """ Resets to 0 iterations for repeated use. Parameters ---------- total : int or float, optional. Total to use for the new bar. """ if hasattr(self, '_prog'): self._prog.reset(total=total) super(tqdm_rich, se...
[ 128, 138 ]
false
[ "__author__", "__all__", "tqdm", "trange" ]
from warnings import warn from rich.progress import ( BarColumn, Progress, ProgressColumn, Text, TimeElapsedColumn, TimeRemainingColumn, filesize) from .std import TqdmExperimentalWarning from .std import tqdm as std_tqdm from .utils import _range __author__ = {"github.com/": ["casperdcl"]} __all__ = ['tqdm_rich',...
false
0
800
typesystem
typesystem.base
Position
__eq__
def __eq__(self, other: typing.Any) -> bool: return ( isinstance(other, Position) and self.line_no == other.line_no and self.column_no == other.column_no and self.char_index == other.char_index )
[ 10, 11 ]
false
[]
import typing from collections.abc import Mapping class Position: def __init__(self, line_no: int, column_no: int, char_index: int): self.line_no = line_no self.column_no = column_no self.char_index = char_index def __eq__(self, other: typing.Any) -> bool: return ( ...
false
0
801
typesystem
typesystem.base
Message
__eq__
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, Message) and ( self.text == other.text and self.code == other.code and self.index == other.index and self.start_position == other.start_position and self.end_position == other.en...
[ 71, 72 ]
false
[]
import typing from collections.abc import Mapping class Message: def __init__( self, *, text: str, code: str = None, key: typing.Union[int, str] = None, index: typing.List[typing.Union[int, str]] = None, position: Position = None, start_position: P...
false
0
802
typesystem
typesystem.base
BaseError
__init__
def __init__( self, *, text: str = None, code: str = None, key: typing.Union[int, str] = None, position: Position = None, messages: typing.List[Message] = None, ): """ Either instantiated with a single message, like so: text - The ...
[ 111, 154 ]
false
[]
import typing from collections.abc import Mapping class Position: def __init__(self, line_no: int, column_no: int, char_index: int): self.line_no = line_no self.column_no = column_no self.char_index = char_index class Message: def __init__( self, *, text: st...
true
2
803
typesystem
typesystem.base
BaseError
__eq__
def __eq__(self, other: typing.Any) -> bool: return isinstance(other, ValidationError) and self._messages == other._messages
[ 186, 187 ]
false
[]
import typing from collections.abc import Mapping class BaseError(Mapping, Exception): def __init__( self, *, text: str = None, code: str = None, key: typing.Union[int, str] = None, position: Position = None, messages: typing.List[Message] = None, ): ...
false
0
804
typesystem
typesystem.base
BaseError
__repr__
def __repr__(self) -> str: class_name = self.__class__.__name__ if len(self._messages) == 1 and not self._messages[0].index: message = self._messages[0] return f"{class_name}(text={message.text!r}, code={message.code!r})" return f"{class_name}({self._messages!r})"
[ 193, 198 ]
false
[]
import typing from collections.abc import Mapping class BaseError(Mapping, Exception): def __init__( self, *, text: str = None, code: str = None, key: typing.Union[int, str] = None, position: Position = None, messages: typing.List[Message] = None, ): ...
true
2
805
typesystem
typesystem.base
BaseError
__str__
def __str__(self) -> str: if len(self._messages) == 1 and not self._messages[0].index: return self._messages[0].text return str(dict(self))
[ 200, 203 ]
false
[]
import typing from collections.abc import Mapping class BaseError(Mapping, Exception): def __init__( self, *, text: str = None, code: str = None, key: typing.Union[int, str] = None, position: Position = None, messages: typing.List[Message] = None, ): ...
true
2
806
typesystem
typesystem.base
ValidationResult
__iter__
def __iter__(self) -> typing.Iterator: yield self.value yield self.error
[ 242, 244 ]
false
[]
import typing from collections.abc import Mapping class ValidationResult: def __init__( self, *, value: typing.Any = None, error: ValidationError = None ) -> None: """ Either: value - The validated data. Or: error - The validation error. """ ...
false
0
807
typesystem
typesystem.composites
NeverMatch
__init__
def __init__(self, **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs)
[ 14, 16 ]
false
[]
import typing from typesystem.fields import Any, Field class NeverMatch(Field): errors = {"never": "This never validates."} def __init__(self, **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs)
false
0
808
typesystem
typesystem.composites
OneOf
__init__
def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.one_of = one_of
[ 35, 38 ]
false
[]
import typing from typesystem.fields import Any, Field class OneOf(Field): errors = { "no_match": "Did not match any valid type.", "multiple_matches": "Matched more than one type.", } def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None: assert "allow_nul...
false
0
809
typesystem
typesystem.composites
OneOf
validate
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any: candidate = None match_count = 0 for child in self.one_of: validated, error = child.validate_or_error(value, strict=strict) if error is None: match_count += 1 ca...
[ 40, 53 ]
false
[]
import typing from typesystem.fields import Any, Field class OneOf(Field): errors = { "no_match": "Did not match any valid type.", "multiple_matches": "Matched more than one type.", } def __init__(self, one_of: typing.List[Field], **kwargs: typing.Any) -> None: assert "allow_nul...
true
2
810
typesystem
typesystem.composites
AllOf
__init__
def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.all_of = all_of
[ 64, 67 ]
false
[]
import typing from typesystem.fields import Any, Field class AllOf(Field): def __init__(self, all_of: typing.List[Field], **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.all_of = all_of
false
0
811
typesystem
typesystem.composites
Not
__init__
def __init__(self, negated: Field, **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.negated = negated
[ 84, 87 ]
false
[]
import typing from typesystem.fields import Any, Field class Not(Field): errors = {"negated": "Must not match."} def __init__(self, negated: Field, **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.negated = negated
false
0
812
typesystem
typesystem.composites
Not
validate
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any: _, error = self.negated.validate_or_error(value, strict=strict) if error: return value raise self.validation_error("negated")
[ 89, 93 ]
false
[]
import typing from typesystem.fields import Any, Field class Not(Field): errors = {"negated": "Must not match."} def __init__(self, negated: Field, **kwargs: typing.Any) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.negated = negated def validate(se...
true
2
813
typesystem
typesystem.composites
IfThenElse
__init__
def __init__( self, if_clause: Field, then_clause: Field = None, else_clause: Field = None, **kwargs: typing.Any ) -> None: assert "allow_null" not in kwargs super().__init__(**kwargs) self.if_clause = if_clause self.then_clause = Any() if ...
[ 103, 114 ]
false
[]
import typing from typesystem.fields import Any, Field class IfThenElse(Field): def __init__( self, if_clause: Field, then_clause: Field = None, else_clause: Field = None, **kwargs: typing.Any ) -> None: assert "allow_null" not in kwargs super().__init...
false
0
814
typesystem
typesystem.composites
IfThenElse
validate
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any: _, error = self.if_clause.validate_or_error(value, strict=strict) if error is None: return self.then_clause.validate(value, strict=strict) else: return self.else_clause.validate(value, strict=s...
[ 116, 121 ]
false
[]
import typing from typesystem.fields import Any, Field class IfThenElse(Field): def __init__( self, if_clause: Field, then_clause: Field = None, else_clause: Field = None, **kwargs: typing.Any ) -> None: assert "allow_null" not in kwargs super().__init...
true
2
815
typesystem
typesystem.fields
Field
validate_or_error
def validate_or_error( self, value: typing.Any, *, strict: bool = False ) -> ValidationResult: try: value = self.validate(value, strict=strict) except ValidationError as error: return ValidationResult(value=None, error=error) return ValidationResult(value=...
[ 52, 59 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
false
0
816
typesystem
typesystem.fields
Field
get_default_value
def get_default_value(self) -> typing.Any: default = getattr(self, "default", None) if callable(default): return default() return default
[ 67, 71 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
817
typesystem
typesystem.fields
Field
__or__
def __or__(self, other: "Field") -> "Union": if isinstance(self, Union): any_of = self.any_of else: any_of = [self] if isinstance(other, Union): any_of += other.any_of else: any_of += [other] return Union(any_of=any_of)
[ 80, 91 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
818
typesystem
typesystem.fields
String
__init__
def __init__( self, *, allow_blank: bool = False, trim_whitespace: bool = True, max_length: int = None, min_length: int = None, pattern: typing.Union[str, typing.Pattern] = None, format: str = None, **kwargs: typing.Any, ) -> None: ...
[ 105, 140 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
819
typesystem
typesystem.fields
String
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None and self.allow_blank and not strict: # Leniently cast nulls to empty strings if allow_blank. return "" elif v...
[ 142, 183 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
820
typesystem
typesystem.fields
String
serialize
def serialize(self, obj: typing.Any) -> typing.Any: if self.format in FORMATS: return FORMATS[self.format].serialize(obj) return obj
[ 185, 188 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
821
typesystem
typesystem.fields
Number
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value == "" and self.allow_null and not strict: return None elif value is None: raise self.validation_error("null") ...
[ 237, 297 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
822
typesystem
typesystem.fields
Boolean
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") elif not isinstance(value, bool): if strict: raise sel...
[ 330, 352 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
823
typesystem
typesystem.fields
Choice
__init__
def __init__( self, *, choices: typing.Sequence[typing.Union[str, typing.Tuple[str, str]]] = None, **kwargs: typing.Any, ) -> None: super().__init__(**kwargs) self.choices = [ (choice if isinstance(choice, (tuple, list)) else (choice, choice)) ...
[ 362, 373 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
false
0
824
typesystem
typesystem.fields
Choice
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") elif value not in Uniqueness([key for key, value in self.choices]): if v...
[ 375, 386 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
825
typesystem
typesystem.fields
Object
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") elif not isinstance(value, (dict, typing.Mapping)): raise self.validatio...
[ 445, 546 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
826
typesystem
typesystem.fields
Array
__init__
def __init__( self, items: typing.Union[Field, typing.Sequence[Field]] = None, additional_items: typing.Union[Field, bool] = False, min_items: int = None, max_items: int = None, exact_items: int = None, unique_items: bool = False, **kwargs: typing.Any,...
[ 561, 599 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
827
typesystem
typesystem.fields
Array
validate
def validate(self, value: typing.Any, *, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") elif not isinstance(value, list): raise self.validation_error("type") ...
[ 601, 658 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
828
typesystem
typesystem.fields
Array
serialize
def serialize(self, obj: typing.Any) -> typing.Any: if obj is None: return None if isinstance(self.items, list): return [ serializer.serialize(value) for serializer, value in zip(self.items, obj) ] if self.items is None: ...
[ 660, 673 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
829
typesystem
typesystem.fields
Union
validate
def validate(self, value: typing.Any, strict: bool = False) -> typing.Any: if value is None and self.allow_null: return None elif value is None: raise self.validation_error("null") candidate_errors = [] for child in self.any_of: validated, error =...
[ 706, 732 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
true
2
830
typesystem
typesystem.fields
Const
__init__
def __init__(self, const: typing.Any, **kwargs: typing.Any): assert "allow_null" not in kwargs super().__init__(**kwargs) self.const = const
[ 751, 754 ]
false
[ "NO_DEFAULT", "FORMATS" ]
import decimal import re import typing from math import isfinite from typesystem import formats from typesystem.base import Message, ValidationError, ValidationResult from typesystem.unique import Uniqueness NO_DEFAULT = object() FORMATS = { "date": formats.DateFormat(), "time": formats.TimeFormat(), "date...
false
0
831
typesystem
typesystem.formats
DateFormat
validate
def validate(self, value: typing.Any) -> datetime.date: match = DATE_REGEX.match(value) if not match: raise self.validation_error("format") kwargs = {k: int(v) for k, v in match.groupdict().items()} try: return datetime.date(**kwargs) except ValueErro...
[ 52, 61 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
832
typesystem
typesystem.formats
DateFormat
serialize
def serialize(self, obj: typing.Any) -> typing.Union[str, None]: if obj is None: return None assert isinstance(obj, datetime.date) return obj.isoformat()
[ 63, 69 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
833
typesystem
typesystem.formats
TimeFormat
validate
def validate(self, value: typing.Any) -> datetime.time: match = TIME_REGEX.match(value) if not match: raise self.validation_error("format") groups = match.groupdict() if groups["microsecond"]: groups["microsecond"] = groups["microsecond"].ljust(6, "0") ...
[ 81, 94 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
834
typesystem
typesystem.formats
TimeFormat
serialize
def serialize(self, obj: typing.Any) -> typing.Union[str, None]: if obj is None: return None assert isinstance(obj, datetime.time) return obj.isoformat()
[ 96, 102 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
835
typesystem
typesystem.formats
DateTimeFormat
validate
def validate(self, value: typing.Any) -> datetime.datetime: match = DATETIME_REGEX.match(value) if not match: raise self.validation_error("format") groups = match.groupdict() if groups["microsecond"]: groups["microsecond"] = groups["microsecond"].ljust(6, "0"...
[ 114, 140 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
836
typesystem
typesystem.formats
DateTimeFormat
serialize
def serialize(self, obj: typing.Any) -> typing.Union[str, None]: if obj is None: return None assert isinstance(obj, datetime.datetime) value = obj.isoformat() if value.endswith("+00:00"): value = value[:-6] + "Z" return value
[ 142, 153 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
837
typesystem
typesystem.formats
UUIDFormat
validate
def validate(self, value: typing.Any) -> uuid.UUID: match = UUID_REGEX.match(value) if not match: raise self.validation_error("format") return uuid.UUID(value)
[ 162, 167 ]
false
[ "DATE_REGEX", "TIME_REGEX", "DATETIME_REGEX", "UUID_REGEX" ]
import datetime import re import typing import uuid from typesystem.base import ValidationError DATE_REGEX = re.compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") TIME_REGEX = re.compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:\.(?P<microsecond>\d{1,6})\d{0,6})?)?" )...
true
2
838
typesystem
typesystem.json_schema
from_json_schema
def from_json_schema( data: typing.Union[bool, dict], definitions: SchemaDefinitions = None ) -> Field: if isinstance(data, bool): return {True: Any(), False: NeverMatch()}[data] if definitions is None: definitions = SchemaDefinitions() for key, value in data.get("definitions", {})....
[ 109, 146 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
true
2
839
typesystem
typesystem.json_schema
type_from_json_schema
def type_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: """ Build a typed field or union of typed fields from a JSON schema object. """ type_strings, allow_null = get_valid_types(data) if len(type_strings) > 1: items = [ from_json_schema_type( ...
[ 149, 168 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
true
2
840
typesystem
typesystem.json_schema
get_valid_types
def get_valid_types(data: dict) -> typing.Tuple[typing.Set[str], bool]: """ Returns a two-tuple of `(type_strings, allow_null)`. """ type_strings = data.get("type", []) if isinstance(type_strings, str): type_strings = {type_strings} else: type_strings = set(type_strings) if...
[ 173, 195 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
true
2
841
typesystem
typesystem.json_schema
from_json_schema_type
def from_json_schema_type( data: dict, type_string: str, allow_null: bool, definitions: SchemaDefinitions ) -> Field: """ Build a typed field from a JSON schema object. """ if type_string == "number": kwargs = { "allow_null": allow_null, "minimum": data.get("minimum"...
[ 198, 328 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
true
2
842
typesystem
typesystem.json_schema
ref_from_json_schema
def ref_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: reference_string = data["$ref"] assert reference_string.startswith("#/"), "Unsupported $ref style in document." return Reference(to=reference_string, definitions=definitions)
[ 333, 336 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
843
typesystem
typesystem.json_schema
enum_from_json_schema
def enum_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: choices = [(item, item) for item in data["enum"]] kwargs = {"choices": choices, "default": data.get("default", NO_DEFAULT)} return Choice(**kwargs)
[ 339, 342 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0
844
typesystem
typesystem.json_schema
const_from_json_schema
def const_from_json_schema(data: dict, definitions: SchemaDefinitions) -> Field: const = data["const"] kwargs = {"const": const, "default": data.get("default", NO_DEFAULT)} return Const(**kwargs)
[ 345, 348 ]
false
[ "TYPE_CONSTRAINTS", "definitions", "JSONSchema" ]
import re import typing from typesystem.composites import AllOf, IfThenElse, NeverMatch, Not, OneOf from typesystem.fields import ( NO_DEFAULT, Any, Array, Boolean, Choice, Const, Decimal, Field, Float, Integer, Number, Object, String, Union, ) from typesystem.sch...
false
0