language
stringclasses 1
value | repo
stringclasses 346
values | path
stringlengths 6
201
| class_span
dict | source
stringlengths 21
2.38M
| target
stringlengths 1
96
|
|---|---|---|---|---|---|
python
|
django__django
|
tests/ordering/models.py
|
{
"start": 1579,
"end": 1733
}
|
class ____(models.Model):
article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE)
class Meta:
ordering = ("article",)
|
Reference
|
python
|
gevent__gevent
|
src/greentest/3.11/test_ftplib.py
|
{
"start": 32263,
"end": 33789
}
|
class ____(TestCase):
def setUp(self):
self.server = DummyFTPServer((HOSTv6, 0),
af=socket.AF_INET6,
encoding=DEFAULT_ENCODING)
self.server.start()
self.client = ftplib.FTP(timeout=TIMEOUT, encoding=DEFAULT_ENCODING)
self.client.connect(self.server.host, self.server.port)
def tearDown(self):
self.client.close()
self.server.stop()
# Explicitly clear the attribute to prevent dangling thread
self.server = None
asyncore.close_all(ignore_all=True)
def test_af(self):
self.assertEqual(self.client.af, socket.AF_INET6)
def test_makeport(self):
with self.client.makeport():
self.assertEqual(self.server.handler_instance.last_received_cmd,
'eprt')
def test_makepasv(self):
host, port = self.client.makepasv()
conn = socket.create_connection((host, port), timeout=TIMEOUT)
conn.close()
self.assertEqual(self.server.handler_instance.last_received_cmd, 'epsv')
def test_transfer(self):
def retr():
received = []
self.client.retrbinary('retr', received.append)
self.assertEqual(b''.join(received),
RETR_DATA.encode(self.client.encoding))
self.client.set_pasv(True)
retr()
self.client.set_pasv(False)
retr()
@skipUnless(ssl, "SSL not available")
|
TestIPv6Environment
|
python
|
django-compressor__django-compressor
|
compressor/parser/__init__.py
|
{
"start": 451,
"end": 1149
}
|
class ____(LazyObject):
options = (
# TODO: make lxml.html parser first again
(html.parser.__name__, HtmlParser), # fast and part of the Python stdlib
("lxml.html", LxmlParser), # lxml, extremely fast
)
def __init__(self, content):
self._wrapped = None
self._setup(content)
def __getattr__(self, name):
return getattr(self._wrapped, name)
def _setup(self, content):
for dependency, parser in self.options:
try:
import_module(dependency)
self._wrapped = parser(content)
break
except (ImportError, TypeError):
continue
|
AutoSelectParser
|
python
|
pytorch__pytorch
|
test/profiler/test_memory_profiler.py
|
{
"start": 3399,
"end": 11851
}
|
class ____(TestCase):
def gradient_detected(
self,
prof: torch.profiler.profile,
ctx: _EventType,
grad_tensor: torch.Tensor,
parameter: Optional[torch.Tensor] = None,
) -> None:
# This is not an exhaustive check, but for the purpose of unit testing
# it is sufficient.
def key_matches_tensor(key, tensor) -> bool:
# Vacuous case.
if tensor is None:
return True
if key is None:
return False
return tensor.storage().data_ptr() == key.storage.ptr
tree = prof.profiler.kineto_results.experimental_event_tree()
for node in _utils.traverse_dfs(tree):
for p_key, p_grad_key in _memory_profiler.extract_gradients(node):
if node.tag == ctx and key_matches_tensor(p_grad_key, grad_tensor):
if parameter is None:
return True # Don't need to check parameter; we're done.
elif p_key is not None:
# For a complex workflow a gradient could correspond to
# different parameters at different points in a trace.
# However this will not happen in the relatively simple
# cases tested here, so if `extract_gradients` identifies
# the parameter corresponding to a particular gradient it
# must be the one we expect.
self.assertTrue(key_matches_tensor(p_key, parameter))
return True
return False
def assertGradientDetected(self, name: str, *args, **kwargs) -> None:
self.assertTrue(
self.gradient_detected(*args, **kwargs),
f"Failed to identify gradient `{name}` from profile.",
)
def assertOnlyGradients(
self, prof: torch.profiler.profile, tensors: Iterator[torch.Tensor]
) -> None:
allowed_set = {t.storage().data_ptr() for t in tensors}
tree = prof.profiler.kineto_results.experimental_event_tree()
for node in _utils.traverse_dfs(tree):
for _, p_grad_key in _memory_profiler.extract_gradients(node):
self.assertTrue(
p_grad_key.storage.ptr in allowed_set,
f"Tensor wrongly marked as gradient: {node.name}: {p_grad_key}",
)
def test_extract_gradients_low_level(self) -> None:
x = torch.ones((1,))
w0 = torch.ones((1,), requires_grad=True)
w1 = torch.ones((1,), requires_grad=True)
def check(cold_start: bool):
self.assertEqual(w0.grad is None, cold_start)
self.assertEqual(w1.grad is None, cold_start)
with profile() as prof:
z = x.expand(4) * w0
(z * w1).sum().backward()
# Gradient detection through op inspection does not provide a
# reference to the parameter corresponding to the gradient.
self.assertGradientDetected("w0", prof, _EventType.TorchOp, w0.grad)
self.assertGradientDetected("w1", prof, _EventType.TorchOp, w1.grad)
self.assertOnlyGradients(prof, (w0.grad, w1.grad))
check(cold_start=True)
check(cold_start=False)
def test_extract_gradients_from_module(self) -> None:
model = torch.nn.Sequential(torch.nn.Linear(2, 1), ScaleLayer())
named_parameters = dict(model.named_parameters())
self.assertEqual(len(named_parameters), 3)
def assert_only_gradients(prof: torch.profiler.profile):
gradients = tuple(i.grad for i in named_parameters.values())
self.assertFalse(any(i is None for i in gradients))
self.assertOnlyGradients(prof, gradients)
def check(cold_start: bool):
x = torch.ones((2, 2))
with profile() as prof:
model(x).sum().backward()
for name, p in named_parameters.items():
# The first time we run a module none of the `.grad` fields
# have been initialized. This is fine; in that case we can
# detect everything we need in the profiled section.
self.assertNotEqual(
self.gradient_detected(prof, _EventType.PyCall, p.grad, p),
cold_start,
name,
)
# Op based detection should still identify the gradients.
self.assertGradientDetected(name, prof, _EventType.TorchOp, p.grad)
assert_only_gradients(prof)
# We can detect gradients even when `.backward()` is not called.
with profile() as prof:
model(torch.ones((2, 2)))
for name, p in named_parameters.items():
self.assertGradientDetected(name, prof, _EventType.PyCall, p.grad, p)
self.assertFalse(
self.gradient_detected(prof, _EventType.TorchOp, p.grad), name
)
assert_only_gradients(prof)
check(cold_start=True)
check(cold_start=False)
def _test_extract_gradients_from_optimizer(self, set_to_none: bool) -> None:
x = torch.ones((1,))
w0 = torch.ones((1,), requires_grad=True)
w1 = torch.ones((1,), requires_grad=True)
optimizer = torch.optim.SGD((w0, w1), lr=0.1, momentum=0.9)
def check(cold_start: bool):
self.assertEqual(w0.grad is None, cold_start)
self.assertEqual(w1.grad is None, cold_start)
with profile() as prof:
optimizer.zero_grad(set_to_none=set_to_none)
z = x.expand(4) * w0
(z * w1).sum().backward()
optimizer.step()
# Optimizer instrumentation runs late in the step, so we can detect
# gradients for both cold and warm start.
self.assertGradientDetected("w0", prof, _EventType.PyCall, w0.grad, w0)
self.assertGradientDetected("w1", prof, _EventType.PyCall, w1.grad, w1)
self.assertGradientDetected("w0", prof, _EventType.TorchOp, w0.grad)
self.assertGradientDetected("w1", prof, _EventType.TorchOp, w1.grad)
self.assertOnlyGradients(prof, (w0.grad, w1.grad))
with profile() as prof:
for _ in range(2):
optimizer.zero_grad(set_to_none=set_to_none)
z = x.expand(4) * w0
(z * w1).sum().backward()
optimizer.step()
# Inspected state is cached, so if we replace gradients (as is the
# case for `set_to_none=True`) our python instrumentation will not
# see them.
# TODO(robieta): Should `.step()` be excluded from caching?
self.assertNotEqual(
self.gradient_detected(prof, _EventType.PyCall, w0.grad, w0),
set_to_none,
)
self.assertNotEqual(
self.gradient_detected(prof, _EventType.PyCall, w1.grad, w1),
set_to_none,
)
if set_to_none:
with self.assertRaisesRegex(AssertionError, "Tensor wrongly marked"):
self.assertOnlyGradients(prof, (w0.grad, w1.grad))
check(cold_start=True)
check(cold_start=False)
def test_extract_gradients_from_optimizer(self) -> None:
self._test_extract_gradients_from_optimizer(set_to_none=False)
def test_extract_gradients_from_optimizer_set_to_none(self) -> None:
self._test_extract_gradients_from_optimizer(set_to_none=True)
def test_extract_gradients_from_module_and_optimizer(self) -> None:
# Module and optimizer are thoroughly tested individually and should be
# additive. Thus we can manage with a lightweight check that they don't
# interact adversely.
model = torch.nn.Sequential(torch.nn.Linear(2, 1), ScaleLayer())
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
with profile() as prof:
model(torch.ones((2, 2))).sum().backward()
optimizer.step()
self.assertGradientDetected(
"weight", prof, _EventType.PyCall, model[0].weight.grad, model[0].weight
)
@skipIfTorchDynamo("TorchDynamo removes profiler altogether.")
|
TestIdentifyGradients
|
python
|
pytorch__pytorch
|
test/functorch/test_eager_transforms.py
|
{
"start": 2627,
"end": 3560
}
|
class ____:
def tearDown(self):
# Ensure that in the case of a test failure, the next test won't fail
# because of a previous call to _vmap_increment_nesting that wasn't undone
# i.e. test_vmap_free_tensor fails when PYTORCH_TEST_WITH_DYNAMO=1
# and the call to increment nesting is not undone
if not TEST_WITH_TORCHDYNAMO:
return
warn = False
while ci := torch._C._functorch.peek_interpreter_stack():
if ci.key() == torch._C._functorch.TransformType.Vmap:
warn = True
torch._C._functorch._vmap_decrement_nesting()
else:
break
if warn:
msg = (
"Interpreter stack is not empty. Test should have called "
"'torch._C._functorch._vmap_decrement_nesting()'"
)
warnings.warn(msg)
@markDynamoStrictTest
|
VmapTearDownMixin
|
python
|
celery__celery
|
celery/security/certificate.py
|
{
"start": 1079,
"end": 2765
}
|
class ____:
"""X.509 certificate."""
def __init__(self, cert: str) -> None:
with reraise_errors(
'Invalid certificate: {0!r}', errors=(ValueError,)
):
self._cert = load_pem_x509_certificate(
ensure_bytes(cert), backend=default_backend())
if not isinstance(self._cert.public_key(), rsa.RSAPublicKey):
raise ValueError("Non-RSA certificates are not supported.")
def has_expired(self) -> bool:
"""Check if the certificate has expired."""
return datetime.datetime.now(datetime.timezone.utc) >= self._cert.not_valid_after_utc
def get_pubkey(self) -> (
DSAPublicKey | EllipticCurvePublicKey | Ed448PublicKey | Ed25519PublicKey | RSAPublicKey
):
return self._cert.public_key()
def get_serial_number(self) -> int:
"""Return the serial number in the certificate."""
return self._cert.serial_number
def get_issuer(self) -> str:
"""Return issuer (CA) as a string."""
return ' '.join(x.value for x in self._cert.issuer)
def get_id(self) -> str:
"""Serial number/issuer pair uniquely identifies a certificate."""
return f'{self.get_issuer()} {self.get_serial_number()}'
def verify(self, data: bytes, signature: bytes, digest: HashAlgorithm | Prehashed) -> None:
"""Verify signature for string containing data."""
with reraise_errors('Bad signature: {0!r}'):
pad = padding.PSS(
mgf=padding.MGF1(digest),
salt_length=padding.PSS.MAX_LENGTH)
self.get_pubkey().verify(signature, ensure_bytes(data), pad, digest)
|
Certificate
|
python
|
django__django
|
tests/model_fields/test_mixins.py
|
{
"start": 283,
"end": 1760
}
|
class ____(SimpleTestCase):
def setUp(self):
self.instance = Foo()
self.field = Example()
def test_cache_name_not_implemented(self):
with self.assertRaises(NotImplementedError):
FieldCacheMixin().cache_name
def test_cache_name(self):
result = Example().cache_name
self.assertEqual(result, "example")
def test_get_cached_value_missing(self):
with self.assertRaises(KeyError):
self.field.get_cached_value(self.instance)
def test_get_cached_value_default(self):
default = object()
result = self.field.get_cached_value(self.instance, default=default)
self.assertIs(result, default)
def test_get_cached_value_after_set(self):
value = object()
self.field.set_cached_value(self.instance, value)
result = self.field.get_cached_value(self.instance)
self.assertIs(result, value)
def test_is_cached_false(self):
result = self.field.is_cached(self.instance)
self.assertFalse(result)
def test_is_cached_true(self):
self.field.set_cached_value(self.instance, 1)
result = self.field.is_cached(self.instance)
self.assertTrue(result)
def test_delete_cached_value(self):
self.field.set_cached_value(self.instance, 1)
self.field.delete_cached_value(self.instance)
result = self.field.is_cached(self.instance)
self.assertFalse(result)
|
FieldCacheMixinTests
|
python
|
redis__redis-py
|
redis/connection.py
|
{
"start": 85376,
"end": 101205
}
|
class ____(MaintNotificationsAbstractConnectionPool, ConnectionPoolInterface):
"""
Create a connection pool. ``If max_connections`` is set, then this
object raises :py:class:`~redis.exceptions.ConnectionError` when the pool's
limit is reached.
By default, TCP connections are created unless ``connection_class``
is specified. Use class:`.UnixDomainSocketConnection` for
unix sockets.
:py:class:`~redis.SSLConnection` can be used for SSL enabled connections.
If ``maint_notifications_config`` is provided, the connection pool will support
maintenance notifications.
Maintenance notifications are supported only with RESP3.
If the ``maint_notifications_config`` is not provided but the ``protocol`` is 3,
the maintenance notifications will be enabled by default.
Any additional keyword arguments are passed to the constructor of
``connection_class``.
"""
@classmethod
def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
"""
Return a connection pool configured from the given URL.
For example::
redis://[[username]:[password]]@localhost:6379/0
rediss://[[username]:[password]]@localhost:6379/0
unix://[username@]/path/to/socket.sock?db=0[&password=password]
Three URL schemes are supported:
- `redis://` creates a TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/redis>
- `rediss://` creates a SSL wrapped TCP socket connection. See more at:
<https://www.iana.org/assignments/uri-schemes/prov/rediss>
- ``unix://``: creates a Unix Domain Socket connection.
The username, password, hostname, path and all querystring values
are passed through urllib.parse.unquote in order to replace any
percent-encoded values with their corresponding characters.
There are several ways to specify a database number. The first value
found will be used:
1. A ``db`` querystring option, e.g. redis://localhost?db=0
2. If using the redis:// or rediss:// schemes, the path argument
of the url, e.g. redis://localhost/0
3. A ``db`` keyword argument to this function.
If none of these options are specified, the default db=0 is used.
All querystring options are cast to their appropriate Python types.
Boolean arguments can be specified with string values "True"/"False"
or "Yes"/"No". Values that cannot be properly cast cause a
``ValueError`` to be raised. Once parsed, the querystring arguments
and keyword arguments are passed to the ``ConnectionPool``'s
class initializer. In the case of conflicting arguments, querystring
arguments always win.
"""
url_options = parse_url(url)
if "connection_class" in kwargs:
url_options["connection_class"] = kwargs["connection_class"]
kwargs.update(url_options)
return cls(**kwargs)
def __init__(
self,
connection_class=Connection,
max_connections: Optional[int] = None,
cache_factory: Optional[CacheFactoryInterface] = None,
maint_notifications_config: Optional[MaintNotificationsConfig] = None,
**connection_kwargs,
):
max_connections = max_connections or 2**31
if not isinstance(max_connections, int) or max_connections < 0:
raise ValueError('"max_connections" must be a positive integer')
self.connection_class = connection_class
self._connection_kwargs = connection_kwargs
self.max_connections = max_connections
self.cache = None
self._cache_factory = cache_factory
if connection_kwargs.get("cache_config") or connection_kwargs.get("cache"):
if self._connection_kwargs.get("protocol") not in [3, "3"]:
raise RedisError("Client caching is only supported with RESP version 3")
cache = self._connection_kwargs.get("cache")
if cache is not None:
if not isinstance(cache, CacheInterface):
raise ValueError("Cache must implement CacheInterface")
self.cache = cache
else:
if self._cache_factory is not None:
self.cache = self._cache_factory.get_cache()
else:
self.cache = CacheFactory(
self._connection_kwargs.get("cache_config")
).get_cache()
connection_kwargs.pop("cache", None)
connection_kwargs.pop("cache_config", None)
self._event_dispatcher = self._connection_kwargs.get("event_dispatcher", None)
if self._event_dispatcher is None:
self._event_dispatcher = EventDispatcher()
# a lock to protect the critical section in _checkpid().
# this lock is acquired when the process id changes, such as
# after a fork. during this time, multiple threads in the child
# process could attempt to acquire this lock. the first thread
# to acquire the lock will reset the data structures and lock
# object of this pool. subsequent threads acquiring this lock
# will notice the first thread already did the work and simply
# release the lock.
self._fork_lock = threading.RLock()
self._lock = threading.RLock()
MaintNotificationsAbstractConnectionPool.__init__(
self,
maint_notifications_config=maint_notifications_config,
**connection_kwargs,
)
self.reset()
def __repr__(self) -> str:
conn_kwargs = ",".join([f"{k}={v}" for k, v in self.connection_kwargs.items()])
return (
f"<{self.__class__.__module__}.{self.__class__.__name__}"
f"(<{self.connection_class.__module__}.{self.connection_class.__name__}"
f"({conn_kwargs})>)>"
)
@property
def connection_kwargs(self) -> Dict[str, Any]:
return self._connection_kwargs
@connection_kwargs.setter
def connection_kwargs(self, value: Dict[str, Any]):
self._connection_kwargs = value
def get_protocol(self):
"""
Returns:
The RESP protocol version, or ``None`` if the protocol is not specified,
in which case the server default will be used.
"""
return self.connection_kwargs.get("protocol", None)
def reset(self) -> None:
self._created_connections = 0
self._available_connections = []
self._in_use_connections = set()
# this must be the last operation in this method. while reset() is
# called when holding _fork_lock, other threads in this process
# can call _checkpid() which compares self.pid and os.getpid() without
# holding any lock (for performance reasons). keeping this assignment
# as the last operation ensures that those other threads will also
# notice a pid difference and block waiting for the first thread to
# release _fork_lock. when each of these threads eventually acquire
# _fork_lock, they will notice that another thread already called
# reset() and they will immediately release _fork_lock and continue on.
self.pid = os.getpid()
def _checkpid(self) -> None:
# _checkpid() attempts to keep ConnectionPool fork-safe on modern
# systems. this is called by all ConnectionPool methods that
# manipulate the pool's state such as get_connection() and release().
#
# _checkpid() determines whether the process has forked by comparing
# the current process id to the process id saved on the ConnectionPool
# instance. if these values are the same, _checkpid() simply returns.
#
# when the process ids differ, _checkpid() assumes that the process
# has forked and that we're now running in the child process. the child
# process cannot use the parent's file descriptors (e.g., sockets).
# therefore, when _checkpid() sees the process id change, it calls
# reset() in order to reinitialize the child's ConnectionPool. this
# will cause the child to make all new connection objects.
#
# _checkpid() is protected by self._fork_lock to ensure that multiple
# threads in the child process do not call reset() multiple times.
#
# there is an extremely small chance this could fail in the following
# scenario:
# 1. process A calls _checkpid() for the first time and acquires
# self._fork_lock.
# 2. while holding self._fork_lock, process A forks (the fork()
# could happen in a different thread owned by process A)
# 3. process B (the forked child process) inherits the
# ConnectionPool's state from the parent. that state includes
# a locked _fork_lock. process B will not be notified when
# process A releases the _fork_lock and will thus never be
# able to acquire the _fork_lock.
#
# to mitigate this possible deadlock, _checkpid() will only wait 5
# seconds to acquire _fork_lock. if _fork_lock cannot be acquired in
# that time it is assumed that the child is deadlocked and a
# redis.ChildDeadlockedError error is raised.
if self.pid != os.getpid():
acquired = self._fork_lock.acquire(timeout=5)
if not acquired:
raise ChildDeadlockedError
# reset() the instance for the new process if another thread
# hasn't already done so
try:
if self.pid != os.getpid():
self.reset()
finally:
self._fork_lock.release()
@deprecated_args(
args_to_warn=["*"],
reason="Use get_connection() without args instead",
version="5.3.0",
)
def get_connection(self, command_name=None, *keys, **options) -> "Connection":
"Get a connection from the pool"
self._checkpid()
with self._lock:
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
try:
# ensure this connection is connected to Redis
connection.connect()
# connections that the pool provides should be ready to send
# a command. if not, the connection was either returned to the
# pool before all data has been read or the socket has been
# closed. either way, reconnect and verify everything is good.
try:
if (
connection.can_read()
and self.cache is None
and not self.maint_notifications_enabled()
):
raise ConnectionError("Connection has data")
except (ConnectionError, TimeoutError, OSError):
connection.disconnect()
connection.connect()
if connection.can_read():
raise ConnectionError("Connection not ready")
except BaseException:
# release the connection back to the pool so that we don't
# leak it
self.release(connection)
raise
return connection
def get_encoder(self) -> Encoder:
"Return an encoder based on encoding settings"
kwargs = self.connection_kwargs
return Encoder(
encoding=kwargs.get("encoding", "utf-8"),
encoding_errors=kwargs.get("encoding_errors", "strict"),
decode_responses=kwargs.get("decode_responses", False),
)
def make_connection(self) -> "ConnectionInterface":
"Create a new connection"
if self._created_connections >= self.max_connections:
raise MaxConnectionsError("Too many connections")
self._created_connections += 1
kwargs = dict(self.connection_kwargs)
if self.cache is not None:
return CacheProxyConnection(
self.connection_class(**kwargs), self.cache, self._lock
)
return self.connection_class(**kwargs)
def release(self, connection: "Connection") -> None:
"Releases the connection back to the pool"
self._checkpid()
with self._lock:
try:
self._in_use_connections.remove(connection)
except KeyError:
# Gracefully fail when a connection is returned to this pool
# that the pool doesn't actually own
return
if self.owns_connection(connection):
if connection.should_reconnect():
connection.disconnect()
self._available_connections.append(connection)
self._event_dispatcher.dispatch(
AfterConnectionReleasedEvent(connection)
)
else:
# Pool doesn't own this connection, do not add it back
# to the pool.
# The created connections count should not be changed,
# because the connection was not created by the pool.
connection.disconnect()
return
def owns_connection(self, connection: "Connection") -> int:
return connection.pid == self.pid
def disconnect(self, inuse_connections: bool = True) -> None:
"""
Disconnects connections in the pool
If ``inuse_connections`` is True, disconnect connections that are
currently in use, potentially by other threads. Otherwise only disconnect
connections that are idle in the pool.
"""
self._checkpid()
with self._lock:
if inuse_connections:
connections = chain(
self._available_connections, self._in_use_connections
)
else:
connections = self._available_connections
for connection in connections:
connection.disconnect()
def close(self) -> None:
"""Close the pool, disconnecting all connections"""
self.disconnect()
def set_retry(self, retry: Retry) -> None:
self.connection_kwargs.update({"retry": retry})
for conn in self._available_connections:
conn.retry = retry
for conn in self._in_use_connections:
conn.retry = retry
def re_auth_callback(self, token: TokenInterface):
with self._lock:
for conn in self._available_connections:
conn.retry.call_with_retry(
lambda: conn.send_command(
"AUTH", token.try_get("oid"), token.get_value()
),
lambda error: self._mock(error),
)
conn.retry.call_with_retry(
lambda: conn.read_response(), lambda error: self._mock(error)
)
for conn in self._in_use_connections:
conn.set_re_auth_token(token)
def _get_pool_lock(self):
return self._lock
def _get_free_connections(self):
with self._lock:
return self._available_connections
def _get_in_use_connections(self):
with self._lock:
return self._in_use_connections
async def _mock(self, error: RedisError):
"""
Dummy functions, needs to be passed as error callback to retry object.
:param error:
:return:
"""
pass
|
ConnectionPool
|
python
|
encode__django-rest-framework
|
tests/authentication/test_authentication.py
|
{
"start": 10376,
"end": 14588
}
|
class ____:
"""Token authentication"""
model = None
path = None
header_prefix = 'Token '
def setUp(self):
self.csrf_client = APIClient(enforce_csrf_checks=True)
self.username = 'john'
self.email = 'lennon@thebeatles.com'
self.password = 'password'
self.user = User.objects.create_user(
self.username, self.email, self.password
)
self.key = 'abcd1234'
self.token = self.model.objects.create(key=self.key, user=self.user)
def test_post_form_passing_token_auth(self):
"""
Ensure POSTing json over token auth with correct
credentials passes and does not require CSRF
"""
auth = self.header_prefix + self.key
response = self.csrf_client.post(
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth
)
assert response.status_code == status.HTTP_200_OK
def test_fail_authentication_if_user_is_not_active(self):
user = User.objects.create_user('foo', 'bar', 'baz')
user.is_active = False
user.save()
self.model.objects.create(key='foobar_token', user=user)
response = self.csrf_client.post(
self.path, {'example': 'example'},
HTTP_AUTHORIZATION=self.header_prefix + 'foobar_token'
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_fail_post_form_passing_nonexistent_token_auth(self):
# use a nonexistent token key
auth = self.header_prefix + 'wxyz6789'
response = self.csrf_client.post(
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_fail_post_if_token_is_missing(self):
response = self.csrf_client.post(
self.path, {'example': 'example'},
HTTP_AUTHORIZATION=self.header_prefix)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_fail_post_if_token_contains_spaces(self):
response = self.csrf_client.post(
self.path, {'example': 'example'},
HTTP_AUTHORIZATION=self.header_prefix + 'foo bar'
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_fail_post_form_passing_invalid_token_auth(self):
# add an 'invalid' unicode character
auth = self.header_prefix + self.key + "¸"
response = self.csrf_client.post(
self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_post_json_passing_token_auth(self):
"""
Ensure POSTing form over token auth with correct
credentials passes and does not require CSRF
"""
auth = self.header_prefix + self.key
response = self.csrf_client.post(
self.path, {'example': 'example'},
format='json', HTTP_AUTHORIZATION=auth
)
assert response.status_code == status.HTTP_200_OK
def test_post_json_makes_one_db_query(self):
"""
Ensure that authenticating a user using a
token performs only one DB query
"""
auth = self.header_prefix + self.key
def func_to_test():
return self.csrf_client.post(
self.path, {'example': 'example'},
format='json', HTTP_AUTHORIZATION=auth
)
self.assertNumQueries(1, func_to_test)
def test_post_form_failing_token_auth(self):
"""
Ensure POSTing form over token auth without correct credentials fails
"""
response = self.csrf_client.post(self.path, {'example': 'example'})
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_post_json_failing_token_auth(self):
"""
Ensure POSTing json over token auth without correct credentials fails
"""
response = self.csrf_client.post(
self.path, {'example': 'example'}, format='json'
)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@override_settings(ROOT_URLCONF=__name__)
|
BaseTokenAuthTests
|
python
|
spack__spack
|
lib/spack/spack/vendor/jsonschema/exceptions.py
|
{
"start": 4605,
"end": 5394
}
|
class ____(Exception):
"""
A validator was asked to validate an instance against an unknown type.
"""
def __init__(self, type, instance, schema):
self.type = type
self.instance = instance
self.schema = schema
def __unicode__(self):
pschema = pprint.pformat(self.schema, width=72)
pinstance = pprint.pformat(self.instance, width=72)
return textwrap.dedent("""
Unknown type %r for validator with schema:
%s
While checking instance:
%s
""".rstrip()
) % (self.type, _utils.indent(pschema), _utils.indent(pinstance))
if PY3:
__str__ = __unicode__
else:
def __str__(self):
return unicode(self).encode("utf-8")
|
UnknownType
|
python
|
walkccc__LeetCode
|
solutions/2466. Count Ways To Build Good Strings/2466.py
|
{
"start": 0,
"end": 444
}
|
class ____:
def countGoodStrings(self, low: int, high: int, zero: int, one: int) -> int:
MOD = 1_000_000_007
ans = 0
# dp[i] := the number of good strings with length i
dp = [1] + [0] * high
for i in range(1, high + 1):
if i >= zero:
dp[i] = (dp[i] + dp[i - zero]) % MOD
if i >= one:
dp[i] = (dp[i] + dp[i - one]) % MOD
if i >= low:
ans = (ans + dp[i]) % MOD
return ans
|
Solution
|
python
|
davidhalter__parso
|
parso/utils.py
|
{
"start": 696,
"end": 4628
}
|
class ____(NamedTuple):
major: int
minor: int
micro: int
def split_lines(string: str, keepends: bool = False) -> Sequence[str]:
r"""
Intended for Python code. In contrast to Python's :py:meth:`str.splitlines`,
looks at form feeds and other special characters as normal text. Just
splits ``\n`` and ``\r\n``.
Also different: Returns ``[""]`` for an empty string input.
In Python 2.7 form feeds are used as normal characters when using
str.splitlines. However in Python 3 somewhere there was a decision to split
also on form feeds.
"""
if keepends:
lst = string.splitlines(True)
# We have to merge lines that were broken by form feed characters.
merge = []
for i, line in enumerate(lst):
try:
last_chr = line[-1]
except IndexError:
pass
else:
if last_chr in _NON_LINE_BREAKS:
merge.append(i)
for index in reversed(merge):
try:
lst[index] = lst[index] + lst[index + 1]
del lst[index + 1]
except IndexError:
# index + 1 can be empty and therefore there's no need to
# merge.
pass
# The stdlib's implementation of the end is inconsistent when calling
# it with/without keepends. One time there's an empty string in the
# end, one time there's none.
if string.endswith('\n') or string.endswith('\r') or string == '':
lst.append('')
return lst
else:
return re.split(r'\n|\r\n|\r', string)
def python_bytes_to_unicode(
source: Union[str, bytes], encoding: str = 'utf-8', errors: str = 'strict'
) -> str:
"""
Checks for unicode BOMs and PEP 263 encoding declarations. Then returns a
unicode object like in :py:meth:`bytes.decode`.
:param encoding: See :py:meth:`bytes.decode` documentation.
:param errors: See :py:meth:`bytes.decode` documentation. ``errors`` can be
``'strict'``, ``'replace'`` or ``'ignore'``.
"""
def detect_encoding():
"""
For the implementation of encoding definitions in Python, look at:
- http://www.python.org/dev/peps/pep-0263/
- http://docs.python.org/2/reference/lexical_analysis.html#encoding-declarations
"""
byte_mark = literal_eval(r"b'\xef\xbb\xbf'")
if source.startswith(byte_mark):
# UTF-8 byte-order mark
return 'utf-8'
first_two_lines = re.match(br'(?:[^\r\n]*(?:\r\n|\r|\n)){0,2}', source).group(0)
possible_encoding = re.search(br"coding[=:]\s*([-\w.]+)",
first_two_lines)
if possible_encoding:
e = possible_encoding.group(1)
if not isinstance(e, str):
e = str(e, 'ascii', 'replace')
return e
else:
# the default if nothing else has been set -> PEP 263
return encoding
if isinstance(source, str):
# only cast str/bytes
return source
encoding = detect_encoding()
try:
# Cast to unicode
return str(source, encoding, errors)
except LookupError:
if errors == 'replace':
# This is a weird case that can happen if the given encoding is not
# a valid encoding. This usually shouldn't happen with provided
# encodings, but can happen if somebody uses encoding declarations
# like `# coding: foo-8`.
return str(source, 'utf-8', errors)
raise
def version_info() -> Version:
"""
Returns a namedtuple of parso's version, similar to Python's
``sys.version_info``.
"""
from parso import __version__
tupl = re.findall(r'[a-z]+|\d+', __version__)
return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)])
|
Version
|
python
|
getsentry__sentry
|
tests/sentry/integrations/msteams/test_client.py
|
{
"start": 7378,
"end": 11056
}
|
class ____(TestCase):
def setUp(self) -> None:
self.expires_at = 1594768808
self.organization = self.create_organization(owner=self.user)
self.integration = self.create_integration(
organization=self.organization,
provider="msteams",
external_id="foobar",
name="my_team",
metadata={
"access_token": "my_token",
"expires_at": self.expires_at,
"service_url": "https://smba.trafficmanager.net/amer/",
},
)
access_json = {"expires_in": 86399, "access_token": "my_new_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.GET,
"https://smba.trafficmanager.net/amer/v3/teams/foobar/conversations",
json={},
)
self.control_proxy_response = add_control_silo_proxy_response(
method=responses.GET,
path="v3/teams/foobar/conversations",
json={},
)
@responses.activate
def test_integration_proxy_is_active(self) -> None:
class MsTeamsProxyApiTestClient(MsTeamsClient):
_use_proxy_url_for_tests = True
with override_settings(SILO_MODE=SiloMode.MONOLITH):
client = MsTeamsProxyApiTestClient(self.integration)
client.get_channel_list("foobar")
assert len(responses.calls) == 2
token_request = responses.calls[0].request
# Token request
assert (
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"
== token_request.url
)
# API request to service url
request = responses.calls[1].request
assert (
"https://smba.trafficmanager.net/amer/v3/teams/foobar/conversations" == request.url
)
assert client.base_url in request.url
assert_proxy_request(request, is_proxy=False)
responses.calls.reset()
with override_settings(SILO_MODE=SiloMode.CONTROL):
client = MsTeamsProxyApiTestClient(self.integration)
client.get_channel_list("foobar")
assert len(responses.calls) == 2
token_request = responses.calls[0].request
# Token request
assert (
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token"
== token_request.url
)
# API request to service url
request = responses.calls[1].request
assert (
"https://smba.trafficmanager.net/amer/v3/teams/foobar/conversations" == request.url
)
assert client.base_url in request.url
assert_proxy_request(request, is_proxy=False)
responses.calls.reset()
with override_settings(SILO_MODE=SiloMode.REGION):
client = MsTeamsProxyApiTestClient(self.integration)
client.get_channel_list("foobar")
assert len(responses.calls) == 1
# API request to service url
request = responses.calls[0].request
assert self.control_proxy_response.call_count == 1
assert request.headers[PROXY_PATH] == "v3/teams/foobar/conversations"
assert request.headers[PROXY_BASE_URL_HEADER] == "https://smba.trafficmanager.net/amer"
assert client.base_url not in request.url
assert_proxy_request(request, is_proxy=True)
|
MsTeamsProxyApiClientTest
|
python
|
huggingface__transformers
|
tests/models/sam3_tracker/test_modeling_sam3_tracker.py
|
{
"start": 1505,
"end": 2571
}
|
class ____:
def __init__(
self,
hidden_size=32,
input_image_size=128,
patch_size=16,
mask_input_channels=8,
num_point_embeddings=4,
hidden_act="gelu",
):
self.hidden_size = hidden_size
self.input_image_size = input_image_size
self.patch_size = patch_size
self.mask_input_channels = mask_input_channels
self.num_point_embeddings = num_point_embeddings
self.hidden_act = hidden_act
def get_config(self):
return Sam3TrackerPromptEncoderConfig(
image_size=self.input_image_size,
patch_size=self.patch_size,
mask_input_channels=self.mask_input_channels,
hidden_size=self.hidden_size,
num_point_embeddings=self.num_point_embeddings,
hidden_act=self.hidden_act,
)
def prepare_config_and_inputs(self):
dummy_points = floats_tensor([self.batch_size, 3, 2])
config = self.get_config()
return config, dummy_points
|
Sam3TrackerPromptEncoderTester
|
python
|
scrapy__scrapy
|
tests/mockserver/http_resources.py
|
{
"start": 9182,
"end": 9576
}
|
class ____(resource.Resource):
"""Return a response with headers set from the JSON request body"""
def render(self, request):
body = json.loads(request.content.read().decode())
for header_name, header_value in body.items():
request.responseHeaders.addRawHeader(header_name, header_value)
return json.dumps(body).encode("utf-8")
|
ResponseHeadersResource
|
python
|
kamyu104__LeetCode-Solutions
|
Python/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k.py
|
{
"start": 39,
"end": 524
}
|
class ____(object):
def minOperations(self, k):
"""
:type k: int
:rtype: int
"""
# reference: https://stackoverflow.com/questions/15390807/integer-square-root-in-python
def isqrt(n):
a, b = n, (n+1)//2
while b < a:
a, b = b, (b+n//b)//2
return a
def ceil_divide(a, b):
return (a+b-1)//b
x = isqrt(k)
return (x-1)+(ceil_divide(k, x)-1)
|
Solution
|
python
|
Pylons__pyramid
|
tests/test_view.py
|
{
"start": 32030,
"end": 39721
}
|
class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _makeOne(self, environ=None):
from pyramid.decorator import reify
from pyramid.view import ViewMethodsMixin
if environ is None:
environ = {}
class Request(ViewMethodsMixin):
def __init__(self, environ):
self.environ = environ
@reify
def response(self):
return DummyResponse()
request = Request(environ)
request.registry = self.config.registry
return request
def test_it(self):
def exc_view(exc, request):
self.assertTrue(exc is dummy_exc)
self.assertTrue(request.exception is dummy_exc)
return DummyResponse(b'foo')
self.config.add_view(exc_view, context=RuntimeError)
request = self._makeOne()
dummy_exc = RuntimeError()
try:
raise dummy_exc
except RuntimeError:
response = request.invoke_exception_view()
self.assertEqual(response.app_iter, [b'foo'])
else: # pragma: no cover
self.fail()
def test_it_hides_attrs(self):
def exc_view(exc, request):
self.assertTrue(exc is not orig_exc)
self.assertTrue(request.exception is not orig_exc)
self.assertTrue(request.exc_info is not orig_exc_info)
self.assertTrue(request.response is not orig_response)
request.response.app_iter = [b'bar']
return request.response
self.config.add_view(exc_view, context=RuntimeError)
request = self._makeOne()
orig_exc = request.exception = DummyContext()
orig_exc_info = request.exc_info = DummyContext()
orig_response = request.response = DummyResponse(b'foo')
try:
raise RuntimeError
except RuntimeError as ex:
response = request.invoke_exception_view()
self.assertEqual(response.app_iter, [b'bar'])
self.assertTrue(request.exception is ex)
self.assertTrue(request.exc_info[1] is ex)
self.assertTrue(request.response is orig_response)
else: # pragma: no cover
self.fail()
def test_it_supports_alternate_requests(self):
def exc_view(exc, request):
self.assertTrue(request is other_req)
from pyramid.threadlocal import get_current_request
self.assertTrue(get_current_request() is other_req)
return DummyResponse(b'foo')
self.config.add_view(exc_view, context=RuntimeError)
request = self._makeOne()
other_req = self._makeOne()
try:
raise RuntimeError
except RuntimeError:
response = request.invoke_exception_view(request=other_req)
self.assertEqual(response.app_iter, [b'foo'])
else: # pragma: no cover
self.fail()
def test_it_supports_threadlocal_registry(self):
def exc_view(exc, request):
return DummyResponse(b'foo')
self.config.add_view(exc_view, context=RuntimeError)
request = self._makeOne()
del request.registry
try:
raise RuntimeError
except RuntimeError:
response = request.invoke_exception_view()
self.assertEqual(response.app_iter, [b'foo'])
else: # pragma: no cover
self.fail()
def test_it_raises_if_no_registry(self):
request = self._makeOne()
del request.registry
from pyramid.threadlocal import manager
manager.push({'registry': None, 'request': request})
try:
raise RuntimeError
except RuntimeError:
try:
request.invoke_exception_view()
except RuntimeError as e:
self.assertEqual(e.args[0], "Unable to retrieve registry")
else: # pragma: no cover
self.fail()
finally:
manager.pop()
def test_it_supports_alternate_exc_info(self):
def exc_view(exc, request):
self.assertTrue(request.exc_info is exc_info)
return DummyResponse(b'foo')
self.config.add_view(exc_view, context=RuntimeError)
request = self._makeOne()
try:
raise RuntimeError
except RuntimeError:
exc_info = sys.exc_info()
response = request.invoke_exception_view(exc_info=exc_info)
self.assertEqual(response.app_iter, [b'foo'])
def test_it_rejects_secured_view(self):
from pyramid.exceptions import Forbidden
def exc_view(exc, request): # pragma: no cover
pass
self.config.testing_securitypolicy(permissive=False)
self.config.add_view(exc_view, context=RuntimeError, permission='view')
request = self._makeOne()
try:
raise RuntimeError
except RuntimeError:
self.assertRaises(Forbidden, request.invoke_exception_view)
else: # pragma: no cover
self.fail()
def test_it_allows_secured_view(self):
def exc_view(exc, request):
return DummyResponse(b'foo')
self.config.testing_securitypolicy(permissive=False)
self.config.add_view(exc_view, context=RuntimeError, permission='view')
request = self._makeOne()
try:
raise RuntimeError
except RuntimeError:
response = request.invoke_exception_view(secure=False)
self.assertEqual(response.app_iter, [b'foo'])
else: # pragma: no cover
self.fail()
def test_it_raises_if_not_found(self):
from pyramid.httpexceptions import HTTPNotFound
request = self._makeOne()
dummy_exc = RuntimeError()
try:
raise dummy_exc
except RuntimeError:
self.assertRaises(HTTPNotFound, request.invoke_exception_view)
else: # pragma: no cover
self.fail()
def test_it_reraises_if_not_found(self):
request = self._makeOne()
dummy_exc = RuntimeError()
try:
raise dummy_exc
except RuntimeError:
self.assertRaises(
RuntimeError,
lambda: request.invoke_exception_view(reraise=True),
)
else: # pragma: no cover
self.fail()
def test_it_raises_predicate_mismatch(self):
from pyramid.exceptions import PredicateMismatch
def exc_view(exc, request): # pragma: no cover
pass
self.config.add_view(
exc_view, context=Exception, request_method='POST'
)
request = self._makeOne()
request.method = 'GET'
dummy_exc = RuntimeError()
try:
raise dummy_exc
except RuntimeError:
self.assertRaises(PredicateMismatch, request.invoke_exception_view)
else: # pragma: no cover
self.fail()
def test_it_reraises_after_predicate_mismatch(self):
def exc_view(exc, request): # pragma: no cover
pass
self.config.add_view(
exc_view, context=Exception, request_method='POST'
)
request = self._makeOne()
request.method = 'GET'
dummy_exc = RuntimeError()
try:
raise dummy_exc
except RuntimeError:
self.assertRaises(
RuntimeError,
lambda: request.invoke_exception_view(reraise=True),
)
else: # pragma: no cover
self.fail()
|
TestViewMethodsMixin
|
python
|
airbytehq__airbyte
|
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/up_to_date/steps.py
|
{
"start": 4463,
"end": 8066
}
|
class ____(Step):
SYFT_DOCKER_IMAGE = "anchore/syft:v1.6.0"
context: ConnectorContext
title: str = "Get dependency updates"
def get_syft_container(self) -> dagger.Container:
home_dir = os.path.expanduser("~")
config_path = os.path.join(home_dir, ".docker", "config.json")
config_file = self.dagger_client.host().file(config_path)
return (
self.dagger_client.container()
.from_(self.SYFT_DOCKER_IMAGE)
.with_mounted_file("/config/config.json", config_file)
.with_env_variable("DOCKER_CONFIG", "/config")
# Syft requires access to the docker daemon. We share the host's docker socket with the Syft container.
.with_unix_socket("/var/run/docker.sock", self.dagger_client.host().unix_socket("/var/run/docker.sock"))
)
@property
def latest_connector_docker_image_address(self) -> str:
docker_image_name = self.context.connector.metadata["dockerRepository"]
return f"{docker_image_name}:latest"
async def get_sbom_from_latest_image(self) -> str:
syft_container = self.get_syft_container()
return await syft_container.with_exec([self.latest_connector_docker_image_address, "-o", "syft-json"], use_entrypoint=True).stdout()
async def get_sbom_from_container(self, container: dagger.Container) -> str:
oci_tarball_path = Path(f"/tmp/{self.context.connector.technical_name}-{self.context.connector.version}.tar")
await container.export(str(oci_tarball_path))
syft_container = self.get_syft_container()
container_sbom = await (
syft_container.with_mounted_file("/tmp/oci.tar", self.dagger_client.host().file(str(oci_tarball_path)))
.with_exec(["/tmp/oci.tar", "-o", "syft-json"], use_entrypoint=True)
.stdout()
)
oci_tarball_path.unlink()
return container_sbom
def get_dependency_updates(self, raw_latest_sbom: str, raw_current_sbom: str) -> List[DependencyUpdate]:
latest_sbom = json.loads(raw_latest_sbom)
current_sbom = json.loads(raw_current_sbom)
latest_packages = {(dep["type"], dep["name"]): dep["version"] for dep in latest_sbom["artifacts"]}
current_packages = {(dep["type"], dep["name"]): dep["version"] for dep in current_sbom["artifacts"]}
diff = DeepDiff(latest_packages, current_packages)
dependency_updates = []
diff_type_to_update_type = [
("values_changed", DependencyUpdateType.UPDATED),
("dictionary_item_added", DependencyUpdateType.ADDED),
("dictionary_item_removed", DependencyUpdateType.REMOVED),
]
for diff_type, update_type in diff_type_to_update_type:
for change in diff.tree.get(diff_type, []):
package_type, package_name = change.get_root_key()
previous_version, new_version = change.t1, change.t2
dependency_updates.append(
DependencyUpdate(package_type, package_name, update_type, previous_version=previous_version, new_version=new_version)
)
return dependency_updates
async def _run(self, target_connector_container: dagger.Container) -> StepResult:
latest_sbom = await self.get_sbom_from_latest_image()
current_sbom = await self.get_sbom_from_container(target_connector_container)
dependency_updates = self.get_dependency_updates(latest_sbom, current_sbom)
return StepResult(step=self, status=StepStatus.SUCCESS, output=dependency_updates)
|
GetDependencyUpdates
|
python
|
huggingface__transformers
|
src/transformers/models/dbrx/modeling_dbrx.py
|
{
"start": 2050,
"end": 8392
}
|
class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: DbrxConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[DbrxConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
|
DbrxRotaryEmbedding
|
python
|
kubernetes-client__python
|
kubernetes/client/models/v1_cluster_trust_bundle_projection.py
|
{
"start": 383,
"end": 8041
}
|
class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'label_selector': 'V1LabelSelector',
'name': 'str',
'optional': 'bool',
'path': 'str',
'signer_name': 'str'
}
attribute_map = {
'label_selector': 'labelSelector',
'name': 'name',
'optional': 'optional',
'path': 'path',
'signer_name': 'signerName'
}
def __init__(self, label_selector=None, name=None, optional=None, path=None, signer_name=None, local_vars_configuration=None): # noqa: E501
"""V1ClusterTrustBundleProjection - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._label_selector = None
self._name = None
self._optional = None
self._path = None
self._signer_name = None
self.discriminator = None
if label_selector is not None:
self.label_selector = label_selector
if name is not None:
self.name = name
if optional is not None:
self.optional = optional
self.path = path
if signer_name is not None:
self.signer_name = signer_name
@property
def label_selector(self):
"""Gets the label_selector of this V1ClusterTrustBundleProjection. # noqa: E501
:return: The label_selector of this V1ClusterTrustBundleProjection. # noqa: E501
:rtype: V1LabelSelector
"""
return self._label_selector
@label_selector.setter
def label_selector(self, label_selector):
"""Sets the label_selector of this V1ClusterTrustBundleProjection.
:param label_selector: The label_selector of this V1ClusterTrustBundleProjection. # noqa: E501
:type: V1LabelSelector
"""
self._label_selector = label_selector
@property
def name(self):
"""Gets the name of this V1ClusterTrustBundleProjection. # noqa: E501
Select a single ClusterTrustBundle by object name. Mutually-exclusive with signerName and labelSelector. # noqa: E501
:return: The name of this V1ClusterTrustBundleProjection. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this V1ClusterTrustBundleProjection.
Select a single ClusterTrustBundle by object name. Mutually-exclusive with signerName and labelSelector. # noqa: E501
:param name: The name of this V1ClusterTrustBundleProjection. # noqa: E501
:type: str
"""
self._name = name
@property
def optional(self):
"""Gets the optional of this V1ClusterTrustBundleProjection. # noqa: E501
If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles. # noqa: E501
:return: The optional of this V1ClusterTrustBundleProjection. # noqa: E501
:rtype: bool
"""
return self._optional
@optional.setter
def optional(self, optional):
"""Sets the optional of this V1ClusterTrustBundleProjection.
If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles. # noqa: E501
:param optional: The optional of this V1ClusterTrustBundleProjection. # noqa: E501
:type: bool
"""
self._optional = optional
@property
def path(self):
"""Gets the path of this V1ClusterTrustBundleProjection. # noqa: E501
Relative path from the volume root to write the bundle. # noqa: E501
:return: The path of this V1ClusterTrustBundleProjection. # noqa: E501
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""Sets the path of this V1ClusterTrustBundleProjection.
Relative path from the volume root to write the bundle. # noqa: E501
:param path: The path of this V1ClusterTrustBundleProjection. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and path is None: # noqa: E501
raise ValueError("Invalid value for `path`, must not be `None`") # noqa: E501
self._path = path
@property
def signer_name(self):
"""Gets the signer_name of this V1ClusterTrustBundleProjection. # noqa: E501
Select all ClusterTrustBundles that match this signer name. Mutually-exclusive with name. The contents of all selected ClusterTrustBundles will be unified and deduplicated. # noqa: E501
:return: The signer_name of this V1ClusterTrustBundleProjection. # noqa: E501
:rtype: str
"""
return self._signer_name
@signer_name.setter
def signer_name(self, signer_name):
"""Sets the signer_name of this V1ClusterTrustBundleProjection.
Select all ClusterTrustBundles that match this signer name. Mutually-exclusive with name. The contents of all selected ClusterTrustBundles will be unified and deduplicated. # noqa: E501
:param signer_name: The signer_name of this V1ClusterTrustBundleProjection. # noqa: E501
:type: str
"""
self._signer_name = signer_name
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1ClusterTrustBundleProjection):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1ClusterTrustBundleProjection):
return True
return self.to_dict() != other.to_dict()
|
V1ClusterTrustBundleProjection
|
python
|
pandas-dev__pandas
|
asv_bench/benchmarks/groupby.py
|
{
"start": 9887,
"end": 10739
}
|
class ____:
def setup_cache(self):
N = 10**5
key1 = np.tile(np.arange(100, dtype=object), 1000)
key2 = key1.copy()
np.random.shuffle(key1)
np.random.shuffle(key2)
df = DataFrame(
{
"key1": key1,
"key2": key2,
"data1": np.random.randn(N),
"data2": np.random.randn(N),
}
)
return df
def time_lambda_sum(self, df):
df.groupby(["key1", "key2"]).agg(lambda x: x.values.sum())
def time_cython_sum(self, df):
df.groupby(["key1", "key2"]).sum()
def time_col_select_lambda_sum(self, df):
df.groupby(["key1", "key2"])["data1"].agg(lambda x: x.values.sum())
def time_col_select_str_sum(self, df):
df.groupby(["key1", "key2"])["data1"].agg("sum")
|
MultiColumn
|
python
|
scipy__scipy
|
scipy/interpolate/tests/test_rbfinterp.py
|
{
"start": 3307,
"end": 17159
}
|
class ____:
@pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
def test_scale_invariance_1d(self, kernel, xp):
# Verify that the functions in _SCALE_INVARIANT are insensitive to the
# shape parameter (when smoothing == 0) in 1d.
seq = Halton(1, scramble=False, seed=np.random.RandomState())
x = 3*seq.random(50)
x = xp.asarray(x)
y = _1d_test_function(x, xp)
xitp = 3*seq.random(50)
xitp = xp.asarray(xitp)
yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
xp_assert_close(yitp1, yitp2, atol=1e-8)
@pytest.mark.parametrize('kernel', sorted(_SCALE_INVARIANT))
def test_scale_invariance_2d(self, kernel, xp):
# Verify that the functions in _SCALE_INVARIANT are insensitive to the
# shape parameter (when smoothing == 0) in 2d.
seq = Halton(2, scramble=False, seed=np.random.RandomState())
x = seq.random(100)
x = xp.asarray(x)
y = _2d_test_function(x, xp)
xitp = seq.random(100)
xitp = xp.asarray(xitp)
yitp1 = self.build(x, y, epsilon=1.0, kernel=kernel)(xitp)
yitp2 = self.build(x, y, epsilon=2.0, kernel=kernel)(xitp)
xp_assert_close(yitp1, yitp2, atol=1e-8)
@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
def test_extreme_domains(self, kernel, xp):
# Make sure the interpolant remains numerically stable for very
# large/small domains.
seq = Halton(2, scramble=False, seed=np.random.RandomState())
scale = 1e50
shift = 1e55
x = seq.random(100)
x = xp.asarray(x)
y = _2d_test_function(x, xp)
xitp = seq.random(100)
xitp = xp.asarray(xitp)
if kernel in _SCALE_INVARIANT:
yitp1 = self.build(x, y, kernel=kernel)(xitp)
yitp2 = self.build(
x*scale + shift, y,
kernel=kernel
)(xitp*scale + shift)
else:
yitp1 = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
yitp2 = self.build(
x*scale + shift, y,
epsilon=5.0/scale,
kernel=kernel
)(xitp*scale + shift)
xp_assert_close(yitp1, yitp2, atol=1e-8)
def test_polynomial_reproduction(self, xp):
# If the observed data comes from a polynomial, then the interpolant
# should be able to reproduce the polynomial exactly, provided that
# `degree` is sufficiently high.
rng = np.random.RandomState(0)
seq = Halton(2, scramble=False, seed=rng)
degree = 3
x = seq.random(50)
xitp = seq.random(50)
x = xp.asarray(x)
xitp = xp.asarray(xitp)
P = _vandermonde(x, degree, xp)
Pitp = _vandermonde(xitp, degree, xp)
poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
poly_coeffs = xp.asarray(poly_coeffs)
y = P @ poly_coeffs #y = P.dot(poly_coeffs)
yitp1 = Pitp @ poly_coeffs #yitp1 = Pitp.dot(poly_coeffs)
yitp2 = self.build(x, y, degree=degree)(xitp)
xp_assert_close(yitp1, yitp2, atol=1e-8)
@pytest.mark.slow
def test_chunking(self, monkeypatch, xp):
# If the observed data comes from a polynomial, then the interpolant
# should be able to reproduce the polynomial exactly, provided that
# `degree` is sufficiently high.
rng = np.random.RandomState(0)
seq = Halton(2, scramble=False, seed=rng)
degree = 3
largeN = 1000 + 33
# this is large to check that chunking of the RBFInterpolator is tested
x = seq.random(50)
xitp = seq.random(largeN)
x = xp.asarray(x)
xitp = xp.asarray(xitp)
P = _vandermonde(x, degree, xp)
Pitp = _vandermonde(xitp, degree, xp)
poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
poly_coeffs = xp.asarray(poly_coeffs)
y = P @ poly_coeffs # y = P.dot(poly_coeffs)
yitp1 = Pitp @ poly_coeffs # yitp1 = Pitp.dot(poly_coeffs)
interp = self.build(x, y, degree=degree)
ce_real = interp._chunk_evaluator
def _chunk_evaluator(*args, **kwargs):
kwargs.update(memory_budget=100)
return ce_real(*args, **kwargs)
monkeypatch.setattr(interp, '_chunk_evaluator', _chunk_evaluator)
yitp2 = interp(xitp)
xp_assert_close(yitp1, yitp2, atol=1e-8)
def test_vector_data(self, xp):
# Make sure interpolating a vector field is the same as interpolating
# each component separately.
seq = Halton(2, scramble=False, seed=np.random.RandomState())
x = seq.random(100)
xitp = seq.random(100)
x = xp.asarray(x)
xitp = xp.asarray(xitp)
y = xp.stack([_2d_test_function(x, xp),
_2d_test_function(xp.flip(x, axis=1), xp)]).T
yitp1 = self.build(x, y)(xitp)
yitp2 = self.build(x, y[:, 0])(xitp)
yitp3 = self.build(x, y[:, 1])(xitp)
xp_assert_close(yitp1[:, 0], yitp2)
xp_assert_close(yitp1[:, 1], yitp3)
def test_complex_data(self, xp):
# Interpolating complex input should be the same as interpolating the
# real and complex components.
seq = Halton(2, scramble=False, seed=np.random.RandomState())
x = seq.random(100)
xitp = seq.random(100)
y = _2d_test_function(x, np) + 1j*_2d_test_function(x[:, ::-1], np)
x, xitp, y = map(xp.asarray, (x, xitp, y))
yitp1 = self.build(x, y)(xitp)
yitp2 = self.build(x, y.real)(xitp)
yitp3 = self.build(x, y.imag)(xitp)
xp_assert_close(yitp1.real, yitp2)
xp_assert_close(yitp1.imag, yitp3)
@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
def test_interpolation_misfit_1d(self, kernel, xp):
# Make sure that each kernel, with its default `degree` and an
# appropriate `epsilon`, does a good job at interpolation in 1d.
seq = Halton(1, scramble=False, seed=np.random.RandomState())
x = 3*seq.random(50)
xitp = 3*seq.random(50)
x = xp.asarray(x)
xitp = xp.asarray(xitp)
y = _1d_test_function(x, xp)
ytrue = _1d_test_function(xitp, xp)
yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
mse = xp.mean((yitp - ytrue)**2)
assert mse < 1.0e-4
@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
def test_interpolation_misfit_2d(self, kernel, xp):
# Make sure that each kernel, with its default `degree` and an
# appropriate `epsilon`, does a good job at interpolation in 2d.
seq = Halton(2, scramble=False, seed=np.random.RandomState())
x = seq.random(100)
xitp = seq.random(100)
x = xp.asarray(x)
xitp = xp.asarray(xitp)
y = _2d_test_function(x, xp)
ytrue = _2d_test_function(xitp, xp)
yitp = self.build(x, y, epsilon=5.0, kernel=kernel)(xitp)
mse = xp.mean((yitp - ytrue)**2)
assert mse < 2.0e-4
@pytest.mark.parametrize('kernel', sorted(_AVAILABLE))
def test_smoothing_misfit(self, kernel, xp):
# Make sure we can find a smoothing parameter for each kernel that
# removes a sufficient amount of noise.
rng = np.random.RandomState(0)
seq = Halton(1, scramble=False, seed=rng)
noise = 0.2
rmse_tol = 0.1
smoothing_range = 10**xp.linspace(-4, 1, 20)
x = 3*seq.random(100)
y = _1d_test_function(x, np) + rng.normal(0.0, noise, (100,))
x = xp.asarray(x)
y = xp.asarray(y)
ytrue = _1d_test_function(x, xp)
rmse_within_tol = False
for smoothing in smoothing_range:
ysmooth = self.build(
x, y,
epsilon=1.0,
smoothing=smoothing,
kernel=kernel)(x)
rmse = xp.sqrt(xp.mean((ysmooth - ytrue)**2))
if rmse < rmse_tol:
rmse_within_tol = True
break
assert rmse_within_tol
def test_array_smoothing(self, xp):
# Test using an array for `smoothing` to give less weight to a known
# outlier.
rng = np.random.RandomState(0)
seq = Halton(1, scramble=False, seed=rng)
degree = 2
x = seq.random(50)
P = _vandermonde(x, degree)
poly_coeffs = rng.normal(0.0, 1.0, P.shape[1])
y = P @ poly_coeffs # y = P.dot(poly_coeffs)
y_with_outlier = y.copy()
y_with_outlier[10] += 1.0
smoothing = np.zeros((50,))
smoothing[10] = 1000.0
x, P, poly_coeffs, y = map(xp.asarray, (x, P, poly_coeffs, y))
y_with_outlier, smoothing = map(xp.asarray, (y_with_outlier, smoothing))
yitp = self.build(x, y_with_outlier, smoothing=smoothing)(x)
# Should be able to reproduce the uncorrupted data almost exactly.
xp_assert_close(yitp, y, atol=1e-4)
def test_inconsistent_x_dimensions_error(self):
# ValueError should be raised if the observation points and evaluation
# points have a different number of dimensions.
y = Halton(2, scramble=False, seed=np.random.RandomState()).random(10)
d = _2d_test_function(y, np)
x = Halton(1, scramble=False, seed=np.random.RandomState()).random(10)
match = 'Expected the second axis of `x`'
with pytest.raises(ValueError, match=match):
self.build(y, d)(x)
def test_inconsistent_d_length_error(self):
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(1)
match = 'Expected the first axis of `d`'
with pytest.raises(ValueError, match=match):
self.build(y, d)
def test_y_not_2d_error(self):
y = np.linspace(0, 1, 5)
d = np.zeros(5)
match = '`y` must be a 2-dimensional array.'
with pytest.raises(ValueError, match=match):
self.build(y, d)
def test_inconsistent_smoothing_length_error(self):
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(5)
smoothing = np.ones(1)
match = 'Expected `smoothing` to be'
with pytest.raises(ValueError, match=match):
self.build(y, d, smoothing=smoothing)
def test_invalid_kernel_name_error(self):
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(5)
match = '`kernel` must be one of'
with pytest.raises(ValueError, match=match):
self.build(y, d, kernel='test')
def test_epsilon_not_specified_error(self):
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(5)
for kernel in _AVAILABLE:
if kernel in _SCALE_INVARIANT:
continue
match = '`epsilon` must be specified'
with pytest.raises(ValueError, match=match):
self.build(y, d, kernel=kernel)
def test_x_not_2d_error(self):
y = np.linspace(0, 1, 5)[:, None]
x = np.linspace(0, 1, 5)
d = np.zeros(5)
match = '`x` must be a 2-dimensional array.'
with pytest.raises(ValueError, match=match):
self.build(y, d)(x)
def test_not_enough_observations_error(self):
y = np.linspace(0, 1, 1)[:, None]
d = np.zeros(1)
match = 'At least 2 data points are required'
with pytest.raises(ValueError, match=match):
self.build(y, d, kernel='thin_plate_spline')
def test_degree_warning(self):
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(5)
for kernel, deg in _NAME_TO_MIN_DEGREE.items():
# Only test for kernels that its minimum degree is not 0.
if deg >= 1:
match = f'`degree` should not be below {deg}'
with pytest.warns(Warning, match=match):
self.build(y, d, epsilon=1.0, kernel=kernel, degree=deg-1)
def test_minus_one_degree(self):
# Make sure a degree of -1 is accepted without any warning.
y = np.linspace(0, 1, 5)[:, None]
d = np.zeros(5)
for kernel, _ in _NAME_TO_MIN_DEGREE.items():
self.build(y, d, epsilon=1.0, kernel=kernel, degree=-1)
@skip_xp_backends("jax.numpy", reason="solve raises no error for a singular matrix")
@skip_xp_backends("cupy", reason="solve raises no error for a singular matrix")
def test_rank_error(self, xp):
# An error should be raised when `kernel` is "thin_plate_spline" and
# observations are 2-D and collinear.
y = xp.asarray([[2.0, 0.0], [1.0, 0.0], [0.0, 0.0]])
d = xp.asarray([0.0, 0.0, 0.0])
match = 'does not have full column rank'
with pytest.raises(LinAlgError, match=match):
self.build(y, d, kernel='thin_plate_spline')(y)
def test_single_point(self, xp):
# Make sure interpolation still works with only one point (in 1, 2, and
# 3 dimensions).
for dim in [1, 2, 3]:
y = xp.zeros((1, dim))
d = xp.ones((1,), dtype=xp.float64)
f = self.build(y, d, kernel='linear')(y)
xp_assert_close(f, d)
def test_pickleable(self, xp):
# Make sure we can pickle and unpickle the interpolant without any
# changes in the behavior.
seq = Halton(1, scramble=False, seed=np.random.RandomState(2305982309))
x = 3*seq.random(50)
xitp = 3*seq.random(50)
x, xitp = xp.asarray(x), xp.asarray(xitp)
y = _1d_test_function(x, xp)
interp = self.build(x, y)
yitp1 = interp(xitp)
yitp2 = pickle.loads(pickle.dumps(interp))(xitp)
xp_assert_close(yitp1, yitp2, atol=1e-16)
@make_xp_test_case(RBFInterpolator)
|
_TestRBFInterpolator
|
python
|
apache__airflow
|
providers/standard/src/airflow/providers/standard/decorators/external_python.py
|
{
"start": 1211,
"end": 2724
}
|
class ____(_PythonDecoratedOperator, ExternalPythonOperator):
"""Wraps a Python callable and captures args/kwargs when called for execution."""
template_fields = ExternalPythonOperator.template_fields
custom_operator_name: str = "@task.external_python"
def external_python_task(
python: str | None = None,
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a callable into an Airflow operator to run via a Python virtual environment.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
This function is only used during type checking or auto-completion.
:meta private:
:param python: Full path string (file-system specific) that points to a Python binary inside
a virtualenv that should be used (in ``VENV/bin`` folder). Should be absolute path
(so usually start with "/" or "X:/" depending on the filesystem/os used).
:param python_callable: Function to decorate
:param multiple_outputs: If set to True, the decorated function's return value will be unrolled to
multiple XCom values. Dict will unroll to XCom values with its keys as XCom keys.
Defaults to False.
"""
return task_decorator_factory(
python=python,
python_callable=python_callable,
multiple_outputs=multiple_outputs,
decorated_operator_class=_PythonExternalDecoratedOperator,
**kwargs,
)
|
_PythonExternalDecoratedOperator
|
python
|
fluentpython__example-code-2e
|
05-data-classes/class/coordinates.py
|
{
"start": 221,
"end": 340
}
|
class ____:
def __init__(self, lat, lon):
self.lat = lat
self.lon = lon
# end::COORDINATE[]
|
Coordinate
|
python
|
bokeh__bokeh
|
src/bokeh/core/property/numeric.py
|
{
"start": 5048,
"end": 5936
}
|
class ____(Float):
""" Accept non-negative numeric values.
Args:
default (float, optional) :
A default value for attributes created from this property to have.
help (str or None, optional) :
A documentation string for this property. (default: None)
Example:
.. code-block:: python
>>> class SizeModel(HasProps):
... prop = Size()
...
>>> m = SizeModel()
>>> m.prop = 0
>>> m.prop = 10e6
>>> m.prop = -10 # ValueError !!
>>> m.prop = "foo" # ValueError !!
"""
def validate(self, value: Any, detail: bool = True) -> None:
super().validate(value, detail)
if value < 0:
msg = "" if not detail else f"expected a non-negative number, got {value!r}"
raise ValueError(msg)
|
Size
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/distribute_coordinator_test.py
|
{
"start": 2755,
"end": 4301
}
|
class ____(object):
def __init__(self,
between_graph=False,
should_init=None,
should_checkpoint=None,
should_save_summary=None):
self.extended = MockExtended(between_graph, should_init, should_checkpoint,
should_save_summary)
def configure(self,
session_config=None,
cluster_spec=None,
task_type=None,
task_id=None):
if self.extended.experimental_should_init is None:
if task_id == 0:
self.extended.experimental_should_init = True
else:
self.extended.experimental_should_init = False
if self.extended.should_checkpoint is None:
if task_id == 0:
self.extended.should_checkpoint = True
else:
self.extended.should_checkpoint = False
if self.extended.should_save_summary is None:
if task_id == 0:
self.extended.should_save_summary = True
else:
self.extended.should_save_summary = False
if session_config:
if (cluster_spec and task_type and task_id is not None and
self.extended.experimental_between_graph):
session_config.intra_op_parallelism_threads += 1
if task_type in ["chief", "worker"]:
session_config.device_filters.extend(
["/job:%s/task:%d" % (task_type, task_id), "/job:ps"])
else:
session_config.inter_op_parallelism_threads += 1
session_config.device_filters.append("/job:somejob")
|
MockStrategy
|
python
|
python-openxml__python-docx
|
src/docx/oxml/table.py
|
{
"start": 8904,
"end": 9378
}
|
class ____(BaseOxmlElement):
"""`w:gridCol` element, child of `w:tblGrid`, defines a table column."""
w: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType]
"w:w", ST_TwipsMeasure
)
@property
def gridCol_idx(self) -> int:
"""Index of this `w:gridCol` element within its parent `w:tblGrid` element."""
tblGrid = cast(CT_TblGrid, self.getparent())
return tblGrid.gridCol_lst.index(self)
|
CT_TblGridCol
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-dbt/tests/core/test_tracker.py
|
{
"start": 6889,
"end": 7705
}
|
class ____:
"""Test dependency management functionality."""
@pytest.mark.parametrize(
"dependencies",
[
["dep1", "dep2", "dep3"],
[],
],
)
def test_node_dependencies_set_and_get(self, sample_node_id, dependencies):
"""Test that set_node_dependencies stores and get_node_dependencies retrieves dependencies."""
tracker = NodeTaskTracker()
# Set dependencies
tracker.set_node_dependencies(sample_node_id, dependencies)
# Get dependencies
retrieved_dependencies = tracker.get_node_dependencies(sample_node_id)
# Verify dependencies match
assert retrieved_dependencies == dependencies
assert tracker._node_dependencies[sample_node_id] == dependencies
|
TestNodeTaskTrackerDependencies
|
python
|
getsentry__sentry
|
src/sentry/utils/sdk_crashes/path_replacer.py
|
{
"start": 499,
"end": 1409
}
|
class ____(PathReplacer):
"""
Replaces the path with the part of the path after the first pattern match.
For example, if the pattern is `/sentry/.*` and the path is `/Users/sentry/myfile.js` then the path will be replaced with `/sentry/myfile.js`.
:param patterns: A set of regular expressions.
:param fallback_path: The path to use if no pattern matches.
"""
def __init__(
self,
patterns: set[str],
fallback_path: str,
):
self.patterns = {re.compile(element, re.IGNORECASE) for element in patterns}
self.fallback_path = fallback_path
def replace_path(self, path_field: str, path_value: str) -> str | None:
for pattern in self.patterns:
match = pattern.search(path_value)
if match:
return path_value[match.start() :]
return self.fallback_path
|
KeepAfterPatternMatchPathReplacer
|
python
|
numpy__numpy
|
numpy/lib/tests/test_arraypad.py
|
{
"start": 30650,
"end": 36257
}
|
class ____:
def test_check_simple(self):
a = np.arange(100)
a = np.pad(a, (25, 20), 'reflect')
b = np.array(
[25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6,
5, 4, 3, 2, 1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
98, 97, 96, 95, 94, 93, 92, 91, 90, 89,
88, 87, 86, 85, 84, 83, 82, 81, 80, 79]
)
assert_array_equal(a, b)
def test_check_odd_method(self):
a = np.arange(100)
a = np.pad(a, (25, 20), 'reflect', reflect_type='odd')
b = np.array(
[-25, -24, -23, -22, -21, -20, -19, -18, -17, -16,
-15, -14, -13, -12, -11, -10, -9, -8, -7, -6,
-5, -4, -3, -2, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119]
)
assert_array_equal(a, b)
def test_check_large_pad(self):
a = [[4, 5, 6], [6, 7, 8]]
a = np.pad(a, (5, 7), 'reflect')
b = np.array(
[[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7, 8, 7, 6, 7],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]
)
assert_array_equal(a, b)
def test_check_shape(self):
a = [[4, 5, 6]]
a = np.pad(a, (5, 7), 'reflect')
b = np.array(
[[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5],
[5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5, 6, 5, 4, 5]]
)
assert_array_equal(a, b)
def test_check_01(self):
a = np.pad([1, 2, 3], 2, 'reflect')
b = np.array([3, 2, 1, 2, 3, 2, 1])
assert_array_equal(a, b)
def test_check_02(self):
a = np.pad([1, 2, 3], 3, 'reflect')
b = np.array([2, 3, 2, 1, 2, 3, 2, 1, 2])
assert_array_equal(a, b)
def test_check_03(self):
a = np.pad([1, 2, 3], 4, 'reflect')
b = np.array([1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3])
assert_array_equal(a, b)
def test_check_04(self):
a = np.pad([1, 2, 3], [1, 10], 'reflect')
b = np.array([2, 1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1])
assert_array_equal(a, b)
def test_check_05(self):
a = np.pad([1, 2, 3, 4], [45, 10], 'reflect')
b = np.array(
[4, 3, 2, 1, 2, 3, 4, 3, 2, 1,
2, 3, 4, 3, 2, 1, 2, 3, 4, 3,
2, 1, 2, 3, 4, 3, 2, 1, 2, 3,
4, 3, 2, 1, 2, 3, 4, 3, 2, 1,
2, 3, 4, 3, 2, 1, 2, 3, 4, 3,
2, 1, 2, 3, 4, 3, 2, 1, 2])
assert_array_equal(a, b)
def test_check_06(self):
a = np.pad([1, 2, 3, 4], [15, 2], 'symmetric')
b = np.array(
[2, 3, 4, 4, 3, 2, 1, 1, 2, 3,
4, 4, 3, 2, 1, 1, 2, 3, 4, 4,
3]
)
assert_array_equal(a, b)
def test_check_07(self):
a = np.pad([1, 2, 3, 4, 5, 6], [45, 3], 'symmetric')
b = np.array(
[4, 5, 6, 6, 5, 4, 3, 2, 1, 1,
2, 3, 4, 5, 6, 6, 5, 4, 3, 2,
1, 1, 2, 3, 4, 5, 6, 6, 5, 4,
3, 2, 1, 1, 2, 3, 4, 5, 6, 6,
5, 4, 3, 2, 1, 1, 2, 3, 4, 5,
6, 6, 5, 4])
assert_array_equal(a, b)
|
TestReflect
|
python
|
fsspec__filesystem_spec
|
fsspec/implementations/jupyter.py
|
{
"start": 3643,
"end": 4002
}
|
class ____(fsspec.spec.AbstractBufferedFile):
def _upload_chunk(self, final=False):
"""Never uploads a chunk until file is done
Not suitable for large files
"""
if final is False:
return False
self.buffer.seek(0)
data = self.buffer.read()
self.fs.pipe_file(self.path, data)
|
SimpleFileWriter
|
python
|
apache__airflow
|
providers/standard/src/airflow/providers/standard/decorators/python.py
|
{
"start": 1150,
"end": 3243
}
|
class ____(DecoratedOperator, PythonOperator):
"""
Wraps a Python callable and captures args/kwargs when called for execution.
:param python_callable: A reference to an object that is callable
:param op_kwargs: a dictionary of keyword arguments that will get unpacked
in your function (templated)
:param op_args: a list of positional arguments that will get unpacked when
calling your callable (templated)
:param multiple_outputs: If set to True, the decorated function's return value will be unrolled to
multiple XCom values. Dict will unroll to XCom values with its keys as XCom keys. Defaults to False.
"""
template_fields: Sequence[str] = ("templates_dict", "op_args", "op_kwargs")
template_fields_renderers = {"templates_dict": "json", "op_args": "py", "op_kwargs": "py"}
custom_operator_name: str = "@task"
def __init__(self, *, python_callable, op_args, op_kwargs, **kwargs) -> None:
kwargs_to_upstream = {
"python_callable": python_callable,
"op_args": op_args,
"op_kwargs": op_kwargs,
}
super().__init__(
kwargs_to_upstream=kwargs_to_upstream,
python_callable=python_callable,
op_args=op_args,
op_kwargs=op_kwargs,
**kwargs,
)
def python_task(
python_callable: Callable | None = None,
multiple_outputs: bool | None = None,
**kwargs,
) -> TaskDecorator:
"""
Wrap a function into an Airflow operator.
Accepts kwargs for operator kwarg. Can be reused in a single DAG.
:param python_callable: Function to decorate
:param multiple_outputs: If set to True, the decorated function's return value will be unrolled to
multiple XCom values. Dict will unroll to XCom values with its keys as XCom keys. Defaults to False.
"""
return task_decorator_factory(
python_callable=python_callable,
multiple_outputs=multiple_outputs,
decorated_operator_class=_PythonDecoratedOperator,
**kwargs,
)
|
_PythonDecoratedOperator
|
python
|
PyCQA__pylint
|
tests/functional/u/unused/unused_import_class_def_keyword.py
|
{
"start": 610,
"end": 715
}
|
class ____:
CONF = "Hello World"
SCHEMA = A(arg=CONF)
# Test normal instantiation
A(arg=DOMAIN_3)
|
B
|
python
|
pyca__cryptography
|
tests/hazmat/primitives/test_pbkdf2hmac.py
|
{
"start": 482,
"end": 3394
}
|
class ____:
def test_already_finalized(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
kdf.derive(b"password")
with pytest.raises(AlreadyFinalized):
kdf.derive(b"password2")
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
key = kdf.derive(b"password")
with pytest.raises(AlreadyFinalized):
kdf.verify(b"password", key)
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
kdf.verify(b"password", key)
with pytest.raises(AlreadyFinalized):
kdf.verify(b"password", key)
def test_unsupported_algorithm(self, backend):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
PBKDF2HMAC(DummyHashAlgorithm(), 20, b"salt", 10, backend)
def test_invalid_key(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
key = kdf.derive(b"password")
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
with pytest.raises(InvalidKey):
kdf.verify(b"password2", key)
def test_unicode_error_with_salt(self, backend):
with pytest.raises(TypeError):
PBKDF2HMAC(
hashes.SHA1(),
20,
"salt", # type: ignore[arg-type]
10,
backend,
)
def test_unicode_error_with_key_material(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
with pytest.raises(TypeError):
kdf.derive("unicode here") # type: ignore[arg-type]
def test_buffer_protocol(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 10, b"salt", 10, backend)
data = bytearray(b"data")
assert kdf.derive(data) == b"\xe9n\xaa\x81\xbbt\xa4\xf6\x08\xce"
def test_derive_into(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
buf = bytearray(20)
n = kdf.derive_into(b"password", buf)
assert n == 20
# Verify the output matches what derive would produce
kdf2 = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
expected = kdf2.derive(b"password")
assert buf == expected
@pytest.mark.parametrize(("buflen", "outlen"), [(19, 20), (21, 20)])
def test_derive_into_buffer_incorrect_size(self, buflen, outlen, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), outlen, b"salt", 10, backend)
buf = bytearray(buflen)
with pytest.raises(ValueError, match="buffer must be"):
kdf.derive_into(b"password", buf)
def test_derive_into_already_finalized(self, backend):
kdf = PBKDF2HMAC(hashes.SHA1(), 20, b"salt", 10, backend)
buf = bytearray(20)
kdf.derive_into(b"password", buf)
with pytest.raises(AlreadyFinalized):
kdf.derive_into(b"password2", buf)
|
TestPBKDF2HMAC
|
python
|
getsentry__sentry
|
tests/sentry/auth/services/test_model.py
|
{
"start": 898,
"end": 1351
}
|
class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization()
def test_serializes_correct_fields(self) -> None:
key = ApiKey.objects.create(
organization_id=self.create_organization().id, scope_list=["org:read"]
)
serialized_key = serialize_api_key(key)
assert f"{serialized_key} is so skibidi".lower().find("key") == -1
|
TestRpcApiKey
|
python
|
doocs__leetcode
|
solution/1700-1799/1707.Maximum XOR With an Element From Array/Solution.py
|
{
"start": 0,
"end": 722
}
|
class ____:
__slots__ = ["children"]
def __init__(self):
self.children = [None] * 2
def insert(self, x: int):
node = self
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
def search(self, x: int) -> int:
node = self
ans = 0
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v ^ 1]:
ans |= 1 << i
node = node.children[v ^ 1]
elif node.children[v]:
node = node.children[v]
else:
return -1
return ans
|
Trie
|
python
|
huggingface__transformers
|
src/transformers/models/instructblipvideo/modular_instructblipvideo.py
|
{
"start": 1616,
"end": 6543
}
|
class ____(PreTrainedConfig):
r"""
[`InstructBlipVideoConfig`] is the configuration class to store the configuration of a
[`InstructBlipVideoForConditionalGeneration`]. It is used to instantiate a Instructblipvideo model according to the specified
arguments, defining the vision model, Q-Former model and language model configs. Instantiating a configuration with
the defaults will yield a similar configuration to that of the Instructblipvideo
[Salesforce/instruct-blip-flan-t5](https://huggingface.co/Salesforce/instruct-blip-flan-t5) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vision_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`InstructBlipVideoVisionConfig`].
qformer_config (`dict`, *optional*):
Dictionary of configuration options used to initialize [`InstructBlipVideoQFormerConfig`].
text_config (`dict`, *optional*):
Dictionary of configuration options used to initialize any [`PreTrainedConfig`].
num_query_tokens (`int`, *optional*, defaults to 32):
The number of query tokens passed through the Transformer.
video_token_index (`int`, *optional*):
Token index of special video token.
kwargs (*optional*):
Dictionary of keyword arguments.
Example:
```python
>>> from transformers import (
... InstructBlipVideoVisionConfig,
... InstructBlipVideoQFormerConfig,
... OPTConfig,
... InstructBlipVideoConfig,
... InstructBlipVideoForConditionalGeneration,
... )
>>> # Initializing a InstructBlipVideoConfig with Salesforce/instruct-blip-flan-t5 style configuration
>>> configuration = InstructBlipVideoConfig()
>>> # Initializing a InstructBlipVideoForConditionalGeneration (with random weights) from the Salesforce/instruct-blip-flan-t5 style configuration
>>> model = InstructBlipVideoForConditionalGeneration(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
>>> # We can also initialize a InstructBlipVideoConfig from a InstructBlipVideoVisionConfig, InstructBlipVideoQFormerConfig and any PreTrainedConfig
>>> # Initializing Instructblipvideo vision, Instructblipvideo Q-Former and language model configurations
>>> vision_config = InstructBlipVideoVisionConfig()
>>> qformer_config = InstructBlipVideoQFormerConfig()
>>> text_config = OPTConfig()
>>> config = InstructBlipVideoConfig(vision_config=vision_config, qformer_config=qformer_config, text_config=text_config)
```"""
model_type = "instructblipvideo"
attribute_map = {
"video_token_id": "video_token_index",
}
sub_configs = {
"text_config": AutoConfig,
"qformer_config": InstructBlipVideoQFormerConfig,
"vision_config": InstructBlipVideoVisionConfig,
}
def __init__(
self,
vision_config=None,
qformer_config=None,
text_config=None,
num_query_tokens=32,
video_token_index=None,
**kwargs,
):
if text_config is None:
text_config = CONFIG_MAPPING["opt"]()
logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
elif isinstance(text_config, dict):
text_model_type = text_config.get("model_type", "opt")
text_config = CONFIG_MAPPING[text_model_type](**text_config)
if qformer_config is None:
qformer_config = InstructBlipVideoQFormerConfig()
logger.info("qformer_config is None. Initializing the InstructBlipVideoQFormerConfig with default values.")
elif isinstance(qformer_config, dict):
qformer_config = InstructBlipVideoQFormerConfig(**qformer_config)
if vision_config is None:
vision_config = InstructBlipVideoVisionConfig()
logger.info(
"`vision_config` is `None`. initializing the `InstructBlipVideoVisionConfig` with default values."
)
elif isinstance(vision_config, dict):
vision_config = InstructBlipVideoVisionConfig(**vision_config)
self.text_config = text_config
self.vision_config = vision_config
self.qformer_config = qformer_config
self.num_query_tokens = num_query_tokens
self.video_token_index = video_token_index
self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
self.initializer_factor = 1.0
self.initializer_range = 0.02
super().__init__(**kwargs)
|
InstructBlipVideoConfig
|
python
|
apache__airflow
|
airflow-ctl/src/airflowctl/api/datamodels/generated.py
|
{
"start": 38974,
"end": 39749
}
|
class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["update"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[ConnectionBody], Field(description="A list of entities to be updated.", title="Entities")
]
update_mask: Annotated[
list[str] | None,
Field(
description="A list of field names to update for each entity.Only these fields will be applied from the request body to the database model.Any extra fields provided will be ignored.",
title="Update Mask",
),
] = None
action_on_non_existence: BulkActionNotOnExistence | None = "fail"
|
BulkUpdateActionConnectionBody
|
python
|
pandas-dev__pandas
|
pandas/tests/arithmetic/test_datetime64.py
|
{
"start": 912,
"end": 4957
}
|
class ____:
# Comparison tests for datetime64 vectors fully parametrized over
# DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison
# tests will eventually end up here.
def test_compare_zerodim(self, tz_naive_fixture, box_with_array):
# Test comparison with zero-dimensional array is unboxed
tz = tz_naive_fixture
box = box_with_array
dti = date_range("20130101", periods=3, tz=tz)
other = np.array(dti.to_numpy()[0])
dtarr = tm.box_expected(dti, box)
xbox = get_upcast_box(dtarr, other, True)
result = dtarr <= other
expected = np.array([True, False, False])
expected = tm.box_expected(expected, xbox)
tm.assert_equal(result, expected)
@pytest.mark.parametrize(
"other",
[
"foo",
-1,
99,
4.0,
object(),
timedelta(days=2),
# GH#19800, GH#19301 datetime.date comparison raises to
# match DatetimeIndex/Timestamp. This also matches the behavior
# of stdlib datetime.datetime
datetime(2001, 1, 1).date(),
# GH#19301 None and NaN are *not* cast to NaT for comparisons
None,
np.nan,
],
)
def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array):
# GH#22074, GH#15966
tz = tz_naive_fixture
rng = date_range("1/1/2000", periods=10, tz=tz)
dtarr = tm.box_expected(rng, box_with_array)
assert_invalid_comparison(dtarr, other, box_with_array)
@pytest.mark.parametrize(
"other",
[
# GH#4968 invalid date/int comparisons
list(range(10)),
np.arange(10),
np.arange(10).astype(np.float32),
np.arange(10).astype(object),
pd.timedelta_range("1ns", periods=10).array,
np.array(pd.timedelta_range("1ns", periods=10)),
list(pd.timedelta_range("1ns", periods=10)),
pd.timedelta_range("1 Day", periods=10).astype(object),
pd.period_range("1971-01-01", freq="D", periods=10).array,
pd.period_range("1971-01-01", freq="D", periods=10).astype(object),
],
)
def test_dt64arr_cmp_arraylike_invalid(
self, other, tz_naive_fixture, box_with_array
):
tz = tz_naive_fixture
dta = date_range("1970-01-01", freq="ns", periods=10, tz=tz)._data
obj = tm.box_expected(dta, box_with_array)
assert_invalid_comparison(obj, other, box_with_array)
def test_dt64arr_cmp_mixed_invalid(self, tz_naive_fixture):
tz = tz_naive_fixture
dta = date_range("1970-01-01", freq="h", periods=5, tz=tz)._data
other = np.array([0, 1, 2, dta[3], Timedelta(days=1)])
result = dta == other
expected = np.array([False, False, False, True, False])
tm.assert_numpy_array_equal(result, expected)
result = dta != other
tm.assert_numpy_array_equal(result, ~expected)
msg = "Invalid comparison between|Cannot compare type|not supported between"
with pytest.raises(TypeError, match=msg):
dta < other
with pytest.raises(TypeError, match=msg):
dta > other
with pytest.raises(TypeError, match=msg):
dta <= other
with pytest.raises(TypeError, match=msg):
dta >= other
def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array):
# GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly
tz = tz_naive_fixture
box = box_with_array
ts = Timestamp("2021-01-01", tz=tz)
ser = Series([ts, NaT])
obj = tm.box_expected(ser, box)
xbox = get_upcast_box(obj, ts, True)
expected = Series([True, False], dtype=np.bool_)
expected = tm.box_expected(expected, xbox)
result = obj == ts
tm.assert_equal(result, expected)
|
TestDatetime64ArrayLikeComparisons
|
python
|
fastapi__sqlmodel
|
docs_src/tutorial/fastapi/app_testing/tutorial001/main.py
|
{
"start": 403,
"end": 442
}
|
class ____(HeroBase):
pass
|
HeroCreate
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pylint/single_string_slots.py
|
{
"start": 191,
"end": 299
}
|
class ____:
__slots__: str = f"bar"
def __init__(self, bar):
self.bar = bar
# Non-errors.
|
Foo
|
python
|
sqlalchemy__sqlalchemy
|
test/sql/test_external_traversal.py
|
{
"start": 47629,
"end": 54805
}
|
class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
@classmethod
def setup_test_class(cls):
global t1, t2
t1 = table(
"table1",
column("col1"),
column("col2"),
column("col3"),
column("col4"),
)
t2 = table("table2", column("col1"), column("col2"), column("col3"))
def test_traverse_memoizes_w_columns(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.traverse(expr)
is_not(expr, expr_adapted)
is_(adapter.columns[expr], expr_adapted)
def test_traverse_memoizes_w_itself(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.traverse(expr)
is_not(expr, expr_adapted)
is_(adapter.traverse(expr), expr_adapted)
def test_columns_memoizes_w_itself(self):
t1a = t1.alias()
adapter = sql_util.ColumnAdapter(t1a, anonymize_labels=True)
expr = select(t1a.c.col1).label("x")
expr_adapted = adapter.columns[expr]
is_not(expr, expr_adapted)
is_(adapter.columns[expr], expr_adapted)
def test_wrapping_fallthrough(self):
t1a = t1.alias(name="t1a")
t2a = t2.alias(name="t2a")
a1 = sql_util.ColumnAdapter(t1a)
s1 = (
select(t1a.c.col1, t2a.c.col1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
a2 = sql_util.ColumnAdapter(s1)
a3 = a2.wrap(a1)
a4 = a1.wrap(a2)
a5 = a1.chain(a2)
# t1.c.col1 -> s1.c.t1a_col1
# adapted by a2
is_(a3.columns[t1.c.col1], s1.c.t1a_col1)
is_(a4.columns[t1.c.col1], s1.c.t1a_col1)
# chaining can't fall through because a1 grabs it
# first
is_(a5.columns[t1.c.col1], t1a.c.col1)
# t2.c.col1 -> s1.c.t2a_col1
# adapted by a2
is_(a3.columns[t2.c.col1], s1.c.t2a_col1)
is_(a4.columns[t2.c.col1], s1.c.t2a_col1)
# chaining, t2 hits s1
is_(a5.columns[t2.c.col1], s1.c.t2a_col1)
# t1.c.col2 -> t1a.c.col2
# fallthrough to a1
is_(a3.columns[t1.c.col2], t1a.c.col2)
is_(a4.columns[t1.c.col2], t1a.c.col2)
# chaining hits a1
is_(a5.columns[t1.c.col2], t1a.c.col2)
# t2.c.col2 -> t2.c.col2
# fallthrough to no adaption
is_(a3.columns[t2.c.col2], t2.c.col2)
is_(a4.columns[t2.c.col2], t2.c.col2)
def test_wrapping_ordering(self):
"""illustrate an example where order of wrappers matters.
This test illustrates both the ordering being significant
as well as a scenario where multiple translations are needed
(e.g. wrapping vs. chaining).
"""
stmt = (
select(t1.c.col1, t2.c.col1)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.subquery()
)
sa = stmt.alias()
stmt2 = select(t2, sa).subquery()
a1 = sql_util.ColumnAdapter(stmt)
a2 = sql_util.ColumnAdapter(stmt2)
a2_to_a1 = a2.wrap(a1)
a1_to_a2 = a1.wrap(a2)
# when stmt2 and stmt represent the same column
# in different contexts, order of wrapping matters
# t2.c.col1 via a2 is stmt2.c.col1; then ignored by a1
is_(a2_to_a1.columns[t2.c.col1], stmt2.c.col1)
# t2.c.col1 via a1 is stmt.c.table2_col1; a2 then
# sends this to stmt2.c.table2_col1
is_(a1_to_a2.columns[t2.c.col1], stmt2.c.table2_col1)
# check that these aren't the same column
is_not(stmt2.c.col1, stmt2.c.table2_col1)
# for mutually exclusive columns, order doesn't matter
is_(a2_to_a1.columns[t1.c.col1], stmt2.c.table1_col1)
is_(a1_to_a2.columns[t1.c.col1], stmt2.c.table1_col1)
is_(a2_to_a1.columns[t2.c.col2], stmt2.c.col2)
def test_wrapping_multiple(self):
"""illustrate that wrapping runs both adapters"""
t1a = t1.alias(name="t1a")
t2a = t2.alias(name="t2a")
a1 = sql_util.ColumnAdapter(t1a)
a2 = sql_util.ColumnAdapter(t2a)
a3 = a2.wrap(a1)
stmt = select(t1.c.col1, t2.c.col2)
self.assert_compile(
a3.traverse(stmt),
"SELECT t1a.col1, t2a.col2 FROM table1 AS t1a, table2 AS t2a",
)
# chaining does too because these adapters don't share any
# columns
a4 = a2.chain(a1)
self.assert_compile(
a4.traverse(stmt),
"SELECT t1a.col1, t2a.col2 FROM table1 AS t1a, table2 AS t2a",
)
def test_wrapping_inclusions(self):
"""test wrapping and inclusion rules together,
taking into account multiple objects with equivalent hash identity."""
t1a = t1.alias(name="t1a")
t2a = t2.alias(name="t2a")
a1 = sql_util.ColumnAdapter(
t1a, include_fn=lambda col: "a1" in col._annotations
)
s1 = (
select(t1a, t2a)
.set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL)
.alias()
)
a2 = sql_util.ColumnAdapter(
s1, include_fn=lambda col: "a2" in col._annotations
)
a3 = a2.wrap(a1)
c1a1 = t1.c.col1._annotate(dict(a1=True))
c1a2 = t1.c.col1._annotate(dict(a2=True))
c1aa = t1.c.col1._annotate(dict(a1=True, a2=True))
c2a1 = t2.c.col1._annotate(dict(a1=True))
c2a2 = t2.c.col1._annotate(dict(a2=True))
c2aa = t2.c.col1._annotate(dict(a1=True, a2=True))
is_(a3.columns[c1a1], t1a.c.col1)
is_(a3.columns[c1a2], s1.c.t1a_col1)
is_(a3.columns[c1aa], s1.c.t1a_col1)
# not covered by a1, accepted by a2
is_(a3.columns[c2aa], s1.c.t2a_col1)
# not covered by a1, accepted by a2
is_(a3.columns[c2a2], s1.c.t2a_col1)
# not covered by a1, rejected by a2
is_(a3.columns[c2a1], c2a1)
@testing.combinations(True, False, argnames="colpresent")
@testing.combinations(True, False, argnames="adapt_on_names")
@testing.combinations(True, False, argnames="use_label")
def test_adapt_binary_col(self, colpresent, use_label, adapt_on_names):
"""test #9273"""
if use_label:
stmt = select(t1.c.col1, (t1.c.col2 > 18).label("foo"))
else:
stmt = select(t1.c.col1, (t1.c.col2 > 18))
sq = stmt.subquery()
if colpresent:
s2 = select(sq.c[0], sq.c[1])
else:
s2 = select(sq.c[0])
a1 = sql_util.ColumnAdapter(s2, adapt_on_names=adapt_on_names)
is_(a1.columns[stmt.selected_columns[0]], s2.selected_columns[0])
if colpresent:
is_(a1.columns[stmt.selected_columns[1]], s2.selected_columns[1])
else:
is_(
a1.columns[stmt.selected_columns[1]],
a1.columns[stmt.selected_columns[1]],
)
|
ColumnAdapterTest
|
python
|
apache__airflow
|
providers/pinecone/src/airflow/providers/pinecone/operators/pinecone.py
|
{
"start": 3312,
"end": 5977
}
|
class ____(BaseOperator):
"""
Create a pod based index in Pinecone.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CreatePodIndexOperator`
:param conn_id: The connection id to use when connecting to Pinecone.
:param index_name: Name of the Pinecone index.
:param dimension: The dimension of the vectors to be indexed.
:param environment: The environment to use when creating the index.
:param replicas: The number of replicas to use.
:param shards: The number of shards to use.
:param pods: The number of pods to use.
:param pod_type: The type of pod to use. Defaults to p1.x1
:param metadata_config: The metadata configuration to use.
:param source_collection: The source collection to use.
:param metric: The metric to use. Defaults to cosine.
:param timeout: The timeout to use.
"""
def __init__(
self,
*,
conn_id: str = PineconeHook.default_conn_name,
index_name: str,
dimension: int,
environment: str | None = None,
replicas: int | None = None,
shards: int | None = None,
pods: int | None = None,
pod_type: str = "p1.x1",
metadata_config: dict | None = None,
source_collection: str | None = None,
metric: str = "cosine",
timeout: int | None = None,
**kwargs: Any,
):
super().__init__(**kwargs)
self.conn_id = conn_id
self.index_name = index_name
self.dimension = dimension
self.environment = environment
self.replicas = replicas
self.shards = shards
self.pods = pods
self.pod_type = pod_type
self.metadata_config = metadata_config
self.source_collection = source_collection
self.metric = metric
self.timeout = timeout
@cached_property
def hook(self) -> PineconeHook:
return PineconeHook(conn_id=self.conn_id, environment=self.environment)
def execute(self, context: Context) -> None:
pod_spec_obj = self.hook.get_pod_spec_obj(
replicas=self.replicas,
shards=self.shards,
pods=self.pods,
pod_type=self.pod_type,
metadata_config=self.metadata_config,
source_collection=self.source_collection,
environment=self.environment,
)
self.hook.create_index(
index_name=self.index_name,
dimension=self.dimension,
spec=pod_spec_obj,
metric=self.metric,
timeout=self.timeout,
)
|
CreatePodIndexOperator
|
python
|
aimacode__aima-python
|
logic4e.py
|
{
"start": 32561,
"end": 43293
}
|
class ____(Agent):
"""An agent for the wumpus world that does logical inference. [Figure 7.20]"""
def __init__(self, dimentions):
self.dimrow = dimentions
self.kb = WumpusKB(self.dimrow)
self.t = 0
self.plan = list()
self.current_position = WumpusPosition(1, 1, 'UP')
super().__init__(self.execute)
def execute(self, percept):
self.kb.make_percept_sentence(percept, self.t)
self.kb.add_temporal_sentences(self.t)
temp = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if self.kb.ask_if_true(location(i, j, self.t)):
temp.append(i)
temp.append(j)
if self.kb.ask_if_true(facing_north(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'UP')
elif self.kb.ask_if_true(facing_south(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'DOWN')
elif self.kb.ask_if_true(facing_west(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'LEFT')
elif self.kb.ask_if_true(facing_east(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'RIGHT')
safe_points = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if self.kb.ask_if_true(ok_to_move(i, j, self.t)):
safe_points.append([i, j])
if self.kb.ask_if_true(percept_glitter(self.t)):
goals = list()
goals.append([1, 1])
self.plan.append('Grab')
actions = self.plan_route(self.current_position, goals, safe_points)
self.plan.extend(actions)
self.plan.append('Climb')
if len(self.plan) == 0:
unvisited = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
for k in range(self.t):
if self.kb.ask_if_true(location(i, j, k)):
unvisited.append([i, j])
unvisited_and_safe = list()
for u in unvisited:
for s in safe_points:
if u not in unvisited_and_safe and s == u:
unvisited_and_safe.append(u)
temp = self.plan_route(self.current_position, unvisited_and_safe, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0 and self.kb.ask_if_true(have_arrow(self.t)):
possible_wumpus = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if not self.kb.ask_if_true(wumpus(i, j)):
possible_wumpus.append([i, j])
temp = self.plan_shot(self.current_position, possible_wumpus, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0:
not_unsafe = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if not self.kb.ask_if_true(ok_to_move(i, j, self.t)):
not_unsafe.append([i, j])
temp = self.plan_route(self.current_position, not_unsafe, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0:
start = list()
start.append([1, 1])
temp = self.plan_route(self.current_position, start, safe_points)
self.plan.extend(temp)
self.plan.append('Climb')
action = self.plan[0]
self.plan = self.plan[1:]
self.kb.make_action_sentence(action, self.t)
self.t += 1
return action
def plan_route(self, current, goals, allowed):
problem = PlanRoute(current, goals, allowed, self.dimrow)
return astar_search(problem).solution()
def plan_shot(self, current, goals, allowed):
shooting_positions = set()
for loc in goals:
x = loc[0]
y = loc[1]
for i in range(1, self.dimrow + 1):
if i < x:
shooting_positions.add(WumpusPosition(i, y, 'EAST'))
if i > x:
shooting_positions.add(WumpusPosition(i, y, 'WEST'))
if i < y:
shooting_positions.add(WumpusPosition(x, i, 'NORTH'))
if i > y:
shooting_positions.add(WumpusPosition(x, i, 'SOUTH'))
# Can't have a shooting position from any of the rooms the Wumpus could reside
orientations = ['EAST', 'WEST', 'NORTH', 'SOUTH']
for loc in goals:
for orientation in orientations:
shooting_positions.remove(WumpusPosition(loc[0], loc[1], orientation))
actions = list()
actions.extend(self.plan_route(current, shooting_positions, allowed))
actions.append('Shoot')
return actions
# ______________________________________________________________________________
# 7.7.4 Making plans by propositional inference
def SAT_plan(init, transition, goal, t_max, SAT_solver=dpll_satisfiable):
"""Converts a planning problem to Satisfaction problem by translating it to a cnf sentence.
[Figure 7.22]
>>> transition = {'A': {'Left': 'A', 'Right': 'B'}, 'B': {'Left': 'A', 'Right': 'C'}, 'C': {'Left': 'B', 'Right': 'C'}}
>>> SAT_plan('A', transition, 'C', 2) is None
True
"""
# Functions used by SAT_plan
def translate_to_SAT(init, transition, goal, time):
clauses = []
states = [state for state in transition]
# Symbol claiming state s at time t
state_counter = itertools.count()
for s in states:
for t in range(time + 1):
state_sym[s, t] = Expr("State_{}".format(next(state_counter)))
# Add initial state axiom
clauses.append(state_sym[init, 0])
# Add goal state axiom
clauses.append(state_sym[goal, time])
# All possible transitions
transition_counter = itertools.count()
for s in states:
for action in transition[s]:
s_ = transition[s][action]
for t in range(time):
# Action 'action' taken from state 's' at time 't' to reach 's_'
action_sym[s, action, t] = Expr(
"Transition_{}".format(next(transition_counter)))
# Change the state from s to s_
clauses.append(action_sym[s, action, t] | '==>' | state_sym[s, t])
clauses.append(action_sym[s, action, t] | '==>' | state_sym[s_, t + 1])
# Allow only one state at any time
for t in range(time + 1):
# must be a state at any time
clauses.append(associate('|', [state_sym[s, t] for s in states]))
for s in states:
for s_ in states[states.index(s) + 1:]:
# for each pair of states s, s_ only one is possible at time t
clauses.append((~state_sym[s, t]) | (~state_sym[s_, t]))
# Restrict to one transition per timestep
for t in range(time):
# list of possible transitions at time t
transitions_t = [tr for tr in action_sym if tr[2] == t]
# make sure at least one of the transitions happens
clauses.append(associate('|', [action_sym[tr] for tr in transitions_t]))
for tr in transitions_t:
for tr_ in transitions_t[transitions_t.index(tr) + 1:]:
# there cannot be two transitions tr and tr_ at time t
clauses.append(~action_sym[tr] | ~action_sym[tr_])
# Combine the clauses to form the cnf
return associate('&', clauses)
def extract_solution(model):
true_transitions = [t for t in action_sym if model[action_sym[t]]]
# Sort transitions based on time, which is the 3rd element of the tuple
true_transitions.sort(key=lambda x: x[2])
return [action for s, action, time in true_transitions]
# Body of SAT_plan algorithm
for t in range(t_max):
# dictionaries to help extract the solution from model
state_sym = {}
action_sym = {}
cnf = translate_to_SAT(init, transition, goal, t)
model = SAT_solver(cnf)
if model is not False:
return extract_solution(model)
return None
# ______________________________________________________________________________
# Chapter 9 Inference in First Order Logic
# 9.2 Unification and First Order Inference
# 9.2.1 Unification
def unify(x, y, s={}):
"""Unify expressions x,y with substitution s; return a substitution that
would make x,y equal, or None if x,y can not unify. x and y can be
variables (e.g. Expr('x')), constants, lists, or Exprs. [Figure 9.1]
>>> unify(x, 3, {})
{x: 3}
"""
if s is None:
return None
elif x == y:
return s
elif is_variable(x):
return unify_var(x, y, s)
elif is_variable(y):
return unify_var(y, x, s)
elif isinstance(x, Expr) and isinstance(y, Expr):
return unify(x.args, y.args, unify(x.op, y.op, s))
elif isinstance(x, str) or isinstance(y, str):
return None
elif issequence(x) and issequence(y) and len(x) == len(y):
if not x:
return s
return unify(x[1:], y[1:], unify(x[0], y[0], s))
else:
return None
def is_variable(x):
"""A variable is an Expr with no args and a lowercase symbol as the op."""
return isinstance(x, Expr) and not x.args and x.op[0].islower()
def unify_var(var, x, s):
if var in s:
return unify(s[var], x, s)
elif x in s:
return unify(var, s[x], s)
elif occur_check(var, x, s):
return None
else:
return extend(s, var, x)
def occur_check(var, x, s):
"""Return true if variable var occurs anywhere in x
(or in subst(s, x), if s has a binding for x)."""
if var == x:
return True
elif is_variable(x) and x in s:
return occur_check(var, s[x], s)
elif isinstance(x, Expr):
return (occur_check(var, x.op, s) or
occur_check(var, x.args, s))
elif isinstance(x, (list, tuple)):
return first(e for e in x if occur_check(var, e, s))
else:
return False
def extend(s, var, val):
"""Copy the substitution s and extend it by setting var to val; return copy.
>>> extend({x: 1}, y, 2) == {x: 1, y: 2}
True
"""
s2 = s.copy()
s2[var] = val
return s2
# 9.2.2 Storage and retrieval
|
HybridWumpusAgent
|
python
|
huggingface__transformers
|
src/transformers/models/funnel/modeling_funnel.py
|
{
"start": 23318,
"end": 23980
}
|
class ____(nn.Module):
def __init__(self, config: FunnelConfig, block_index: int) -> None:
super().__init__()
self.attention = FunnelRelMultiheadAttention(config, block_index)
self.ffn = FunnelPositionwiseFFN(config)
def forward(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_inputs,
output_attentions: bool = False,
) -> tuple:
attn = self.attention(query, key, value, attention_inputs, output_attentions=output_attentions)
output = self.ffn(attn[0])
return (output, attn[1]) if output_attentions else (output,)
|
FunnelLayer
|
python
|
tensorflow__tensorflow
|
tensorflow/python/eager/polymorphic_function/tracing_compilation_test.py
|
{
"start": 72410,
"end": 74754
}
|
class ____(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def testMultipleDeviceCheck(self):
def f():
with ops.device('cpu'):
return test_ops.device_placement_op()
func = compiled_fn(f)
with ops.device('cpu:0'):
output = self.evaluate(func())
self.assertIn(compat.as_bytes('CPU:0'), output)
@test_util.run_in_graph_and_eager_modes
def testDeviceAnnotationsRespected(self):
def multi_device_fn():
with ops.device('/cpu:0'):
s0 = test_ops.device_placement_op()
with ops.device('/cpu:1'):
s1 = test_ops.device_placement_op()
with ops.device('/cpu:2'):
s2 = test_ops.device_placement_op()
s3 = test_ops.device_placement_op()
return s0, s1, s2, s3
function_cache = function_cache_lib.FunctionCache()
defined = compiled_fn(multi_device_fn, function_cache=function_cache)
outputs = self.evaluate(defined())
self.assertLen(function_cache, 1)
self.assertIn(compat.as_bytes('CPU:0'), outputs[0])
self.assertIn(compat.as_bytes('CPU:1'), outputs[1])
self.assertIn(compat.as_bytes('CPU:2'), outputs[2])
with ops.device('/cpu:3'):
outputs = self.evaluate(defined())
# All function definitions are agnostic to call site devices.
self.assertLen(function_cache, 1)
self.assertIn(compat.as_bytes('CPU:0'), outputs[0])
self.assertIn(compat.as_bytes('CPU:1'), outputs[1])
self.assertIn(compat.as_bytes('CPU:2'), outputs[2])
self.assertIn(compat.as_bytes('CPU:3'), outputs[3])
with ops.device('/cpu:0'):
outputs = self.evaluate(defined())
self.assertLen(function_cache, 1)
self.assertIn(compat.as_bytes('CPU:0'), outputs[0])
self.assertIn(compat.as_bytes('CPU:1'), outputs[1])
self.assertIn(compat.as_bytes('CPU:2'), outputs[2])
self.assertIn(compat.as_bytes('CPU:0'), outputs[3])
def setUpModule():
ops.enable_eager_execution()
cpus = config.list_physical_devices('CPU')
# Set 4 virtual CPUs
config.set_logical_device_configuration(
cpus[0],
[
context.LogicalDeviceConfiguration(),
context.LogicalDeviceConfiguration(),
context.LogicalDeviceConfiguration(),
context.LogicalDeviceConfiguration(),
],
)
if __name__ == '__main__':
test.main()
|
DevicePlacementTest
|
python
|
zarr-developers__zarr-python
|
src/zarr/errors.py
|
{
"start": 2979,
"end": 3135
}
|
class ____(ZarrFutureWarning):
"""
A warning raised to indicate that a feature is outside the Zarr specification.
"""
|
UnstableSpecificationWarning
|
python
|
numba__numba
|
numba/cuda/testing.py
|
{
"start": 390,
"end": 1614
}
|
class ____(SerialMixin, TestCase):
"""
For tests that use a CUDA device. Test methods in a CUDATestCase must not
be run out of module order, because the ContextResettingTestCase may reset
the context and destroy resources used by a normal CUDATestCase if any of
its tests are run between tests from a CUDATestCase.
"""
def setUp(self):
self._low_occupancy_warnings = config.CUDA_LOW_OCCUPANCY_WARNINGS
self._warn_on_implicit_copy = config.CUDA_WARN_ON_IMPLICIT_COPY
# Disable warnings about low gpu utilization in the test suite
config.CUDA_LOW_OCCUPANCY_WARNINGS = 0
# Disable warnings about host arrays in the test suite
config.CUDA_WARN_ON_IMPLICIT_COPY = 0
def tearDown(self):
config.CUDA_LOW_OCCUPANCY_WARNINGS = self._low_occupancy_warnings
config.CUDA_WARN_ON_IMPLICIT_COPY = self._warn_on_implicit_copy
def skip_if_lto(self, reason):
# Some linkers need the compute capability to be specified, so we
# always specify it here.
cc = devices.get_context().device.compute_capability
linker = driver.Linker.new(cc=cc)
if linker.lto:
self.skipTest(reason)
|
CUDATestCase
|
python
|
facelessuser__pymdown-extensions
|
tests/test_extensions/test_superfences.py
|
{
"start": 47686,
"end": 48855
}
|
class ____(util.MdCase):
"""Test custom formatter that is broken and causes a failure."""
extension = ['pymdownx.superfences']
extension_configs = {
'pymdownx.superfences': {
'custom_fences': [
{
'name': 'test',
'class': 'test',
'format': custom_exploder_fail,
}
]
}
}
def test_custom_fail_exception(self):
"""Test custom fences forced exception."""
with self.assertRaises(SuperFencesException):
self.check_markdown(
r'''
```test
test
```
''',
'',
True
)
def test_custom_fail_exception_blockquote(self):
"""Test custom fences forced exception in a block quote."""
with self.assertRaises(SuperFencesException):
self.check_markdown(
r'''
> ```test
> test
> ```
''',
'',
True
)
|
TestSuperFencesCustomBrokenFail
|
python
|
eriklindernoren__ML-From-Scratch
|
mlfromscratch/unsupervised_learning/k_means.py
|
{
"start": 186,
"end": 3530
}
|
class ____():
"""A simple clustering method that forms k clusters by iteratively reassigning
samples to the closest centroids and after that moves the centroids to the center
of the new formed clusters.
Parameters:
-----------
k: int
The number of clusters the algorithm will form.
max_iterations: int
The number of iterations the algorithm will run for if it does
not converge before that.
"""
def __init__(self, k=2, max_iterations=500):
self.k = k
self.max_iterations = max_iterations
def _init_random_centroids(self, X):
""" Initialize the centroids as k random samples of X"""
n_samples, n_features = np.shape(X)
centroids = np.zeros((self.k, n_features))
for i in range(self.k):
centroid = X[np.random.choice(range(n_samples))]
centroids[i] = centroid
return centroids
def _closest_centroid(self, sample, centroids):
""" Return the index of the closest centroid to the sample """
closest_i = 0
closest_dist = float('inf')
for i, centroid in enumerate(centroids):
distance = euclidean_distance(sample, centroid)
if distance < closest_dist:
closest_i = i
closest_dist = distance
return closest_i
def _create_clusters(self, centroids, X):
""" Assign the samples to the closest centroids to create clusters """
n_samples = np.shape(X)[0]
clusters = [[] for _ in range(self.k)]
for sample_i, sample in enumerate(X):
centroid_i = self._closest_centroid(sample, centroids)
clusters[centroid_i].append(sample_i)
return clusters
def _calculate_centroids(self, clusters, X):
""" Calculate new centroids as the means of the samples in each cluster """
n_features = np.shape(X)[1]
centroids = np.zeros((self.k, n_features))
for i, cluster in enumerate(clusters):
centroid = np.mean(X[cluster], axis=0)
centroids[i] = centroid
return centroids
def _get_cluster_labels(self, clusters, X):
""" Classify samples as the index of their clusters """
# One prediction for each sample
y_pred = np.zeros(np.shape(X)[0])
for cluster_i, cluster in enumerate(clusters):
for sample_i in cluster:
y_pred[sample_i] = cluster_i
return y_pred
def predict(self, X):
""" Do K-Means clustering and return cluster indices """
# Initialize centroids as k random samples from X
centroids = self._init_random_centroids(X)
# Iterate until convergence or for max iterations
for _ in range(self.max_iterations):
# Assign samples to closest centroids (create clusters)
clusters = self._create_clusters(centroids, X)
# Save current centroids for convergence check
prev_centroids = centroids
# Calculate new centroids from the clusters
centroids = self._calculate_centroids(clusters, X)
# If no centroids have changed => convergence
diff = centroids - prev_centroids
if not diff.any():
break
return self._get_cluster_labels(clusters, X)
|
KMeans
|
python
|
tensorflow__tensorflow
|
tensorflow/python/keras/metrics.py
|
{
"start": 18259,
"end": 19487
}
|
class ____(Reduce):
"""Computes the (weighted) mean of the given values.
For example, if values is [1, 3, 5, 7] then the mean is 4.
If the weights were specified as [1, 1, 0, 0] then the mean would be 2.
This metric creates two variables, `total` and `count` that are used to
compute the average of `values`. This average is ultimately returned as `mean`
which is an idempotent operation that simply divides `total` by `count`.
If `sample_weight` is `None`, weights default to 1.
Use `sample_weight` of 0 to mask values.
Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.
Standalone usage:
>>> m = tf.keras.metrics.Mean()
>>> m.update_state([1, 3, 5, 7])
>>> m.result().numpy()
4.0
>>> m.reset_state()
>>> m.update_state([1, 3, 5, 7], sample_weight=[1, 1, 0, 0])
>>> m.result().numpy()
2.0
Usage with `compile()` API:
```python
model.add_metric(tf.keras.metrics.Mean(name='mean_1')(outputs))
model.compile(optimizer='sgd', loss='mse')
```
"""
def __init__(self, name='mean', dtype=None):
super(Mean, self).__init__(
reduction=metrics_utils.Reduction.WEIGHTED_MEAN, name=name, dtype=dtype)
|
Mean
|
python
|
euske__pdfminer
|
pdfminer/pdfdocument.py
|
{
"start": 1452,
"end": 1755
}
|
class ____:
debug = False
def get_trailer(self):
raise NotImplementedError
def get_objids(self):
return []
# Must return
# (strmid, index, genno)
# or (None, pos, genno)
def get_pos(self, objid):
raise KeyError(objid)
## PDFXRef
##
|
PDFBaseXRef
|
python
|
django-haystack__django-haystack
|
haystack/management/commands/haystack_info.py
|
{
"start": 133,
"end": 766
}
|
class ____(BaseCommand):
help = "Provides feedback about the current Haystack setup." # noqa A003
def handle(self, **options):
"""Provides feedback about the current Haystack setup."""
unified_index = connections[DEFAULT_ALIAS].get_unified_index()
indexed = unified_index.get_indexed_models()
index_count = len(indexed)
self.stdout.write("Number of handled %s index(es)." % index_count)
for index in indexed:
self.stdout.write(
" - Model: %s by Index: %s"
% (index.__name__, unified_index.get_indexes()[index])
)
|
Command
|
python
|
vyperlang__vyper
|
vyper/ast/nodes.py
|
{
"start": 25381,
"end": 26477
}
|
class ____(Num):
"""
A decimal.
Attributes
----------
value : decimal.Decimal
Value of the node, represented as a Decimal object.
"""
__slots__ = ()
def __init__(self, parent: Optional["VyperNode"] = None, **kwargs: dict):
super().__init__(parent, **kwargs)
if not isinstance(self.value, decimal.Decimal):
self.value = decimal.Decimal(self.value)
def to_dict(self):
ast_dict = super().to_dict()
ast_dict["value"] = self.node_source_code
return ast_dict
def validate(self):
# note: maybe use self.value == quantize(self.value) for this check
if self.value.as_tuple().exponent < -MAX_DECIMAL_PLACES:
raise InvalidLiteral("Vyper supports a maximum of ten decimal points", self)
if self.value < SizeLimits.MIN_AST_DECIMAL:
raise OverflowException("Value is below lower bound for decimal types", self)
if self.value > SizeLimits.MAX_AST_DECIMAL:
raise OverflowException("Value exceeds upper bound for decimal types", self)
|
Decimal
|
python
|
tensorflow__tensorflow
|
tensorflow/compiler/tests/xla_dump_to_test.py
|
{
"start": 957,
"end": 1732
}
|
class ____(xla_test.XLATestCase):
"""Test that ensures --XLA_FLAGS=--dump_to_xla=<dir> produces output."""
def _compute(self):
with self.session() as sess, self.device_scope():
data = np.array([0], dtype=np.float32)
indices = np.array([0], dtype=np.int32)
d = array_ops.placeholder(data.dtype, shape=data.shape)
i = array_ops.placeholder(indices.dtype, shape=indices.shape)
sess.run(math_ops.segment_max_v2(data, indices, 1), {d: data, i: indices})
def testDumpToTempDir(self):
tmp_dir = self.create_tempdir().full_path
os.environ['XLA_FLAGS'] = '--xla_dump_to=' + tmp_dir
self._compute()
self.assertNotEmpty(glob.glob(os.path.join(tmp_dir, 'module_0*')))
if __name__ == '__main__':
googletest.main()
|
XlaDumpToDirTest
|
python
|
google__pytype
|
pytype/state_test.py
|
{
"start": 2348,
"end": 2750
}
|
class ____(unittest.TestCase):
def setUp(self):
super().setUp()
self._program = cfg.Program()
self._node = self._program.NewCFGNode("test")
def check_binding(self, expected, binding, **varnames):
self.assertEqual(len(binding.origins), 1)
self.assertEqual(self._node, binding.origins[0].where)
self.assertEqual(expected, source_summary(binding, **varnames))
|
ConditionTestBase
|
python
|
pennersr__django-allauth
|
allauth/socialaccount/providers/openid/provider.py
|
{
"start": 319,
"end": 720
}
|
class ____(ProviderAccount):
def get_brand(self):
ret = super(OpenIDAccount, self).get_brand()
domain = urlparse(self.account.uid).netloc
provider_map = {}
for d, p in provider_map.items():
if domain.lower().find(d) >= 0:
ret = p
break
return ret
def to_str(self):
return self.account.uid
|
OpenIDAccount
|
python
|
PyCQA__pylint
|
doc/data/messages/n/notimplemented-raised/bad.py
|
{
"start": 0,
"end": 88
}
|
class ____:
def bore(self):
raise NotImplemented # [notimplemented-raised]
|
Worm
|
python
|
facebook__pyre-check
|
client/command_arguments.py
|
{
"start": 995,
"end": 1498
}
|
class ____(enum.Enum):
_value_: str
TRACE_EVENT = "trace_event"
COLD_START_PHASES = "cold_start_phases"
INCREMENTAL_UPDATES = "incremental_updates"
TAINT = "taint"
INDIVIDUAL_TABLE_SIZES = "individual_table_sizes"
TOTAL_SHARED_MEMORY_SIZE_OVER_TIME = "total_shared_memory_size_over_time"
TOTAL_SHARED_MEMORY_SIZE_OVER_TIME_GRAPH = (
"total_shared_memory_size_over_time_graph" # noqa B950
)
def __str__(self) -> str:
return self.value
|
ProfileOutput
|
python
|
getsentry__sentry
|
src/sentry/api/endpoints/organization_on_demand_metrics_estimation_stats.py
|
{
"start": 1170,
"end": 1828
}
|
class ____(Enum):
"""
Enum to represent the quality of the stats estimation
"""
NO_DATA = "no-data" # no data available (not even metrics)
NO_INDEXED_DATA = "no-indexed-data" # no indexed data available
POOR_INDEXED_DATA = (
"poor-indexed-data" # indexed data available but missing more than 40% intervals
)
ACCEPTABLE_INDEXED_DATA = (
"acceptable-indexed-data" # indexed data available and missing between 20% and 60%
)
# intervals
GOOD_INDEXED_DATA = (
"good-indexed-data" # indexed data available and missing less than 20% intervals
)
@region_silo_endpoint
|
StatsQualityEstimation
|
python
|
pydata__xarray
|
xarray/tests/test_treenode.py
|
{
"start": 6057,
"end": 8465
}
|
class ____:
def test_set_child_node(self) -> None:
john: TreeNode = TreeNode()
mary: TreeNode = TreeNode()
john._set_item("Mary", mary)
assert john.children["Mary"] is mary
assert isinstance(mary, TreeNode)
assert mary.children == {}
assert mary.parent is john
def test_child_already_exists(self) -> None:
mary: TreeNode = TreeNode()
john: TreeNode = TreeNode(children={"Mary": mary})
mary_2: TreeNode = TreeNode()
with pytest.raises(KeyError):
john._set_item("Mary", mary_2, allow_overwrite=False)
def test_set_grandchild(self) -> None:
rose: TreeNode = TreeNode()
mary: TreeNode = TreeNode()
john: TreeNode = TreeNode()
john._set_item("Mary", mary)
john._set_item("Mary/Rose", rose)
assert john.children["Mary"] is mary
assert isinstance(mary, TreeNode)
assert "Rose" in mary.children
assert rose.parent is mary
def test_create_intermediate_child(self) -> None:
john: TreeNode = TreeNode()
rose: TreeNode = TreeNode()
# test intermediate children not allowed
with pytest.raises(KeyError, match="Could not reach"):
john._set_item(path="Mary/Rose", item=rose, new_nodes_along_path=False)
# test intermediate children allowed
john._set_item("Mary/Rose", rose, new_nodes_along_path=True)
assert "Mary" in john.children
mary = john.children["Mary"]
assert isinstance(mary, TreeNode)
assert mary.children == {"Rose": rose}
assert rose.parent == mary
assert rose.parent == mary
def test_overwrite_child(self) -> None:
john: TreeNode = TreeNode()
mary: TreeNode = TreeNode()
john._set_item("Mary", mary)
# test overwriting not allowed
marys_evil_twin: TreeNode = TreeNode()
with pytest.raises(KeyError, match="Already a node object"):
john._set_item("Mary", marys_evil_twin, allow_overwrite=False)
assert john.children["Mary"] is mary
assert marys_evil_twin.parent is None
# test overwriting allowed
marys_evil_twin = TreeNode()
john._set_item("Mary", marys_evil_twin, allow_overwrite=True)
assert john.children["Mary"] is marys_evil_twin
assert marys_evil_twin.parent is john
|
TestSetNodes
|
python
|
pydantic__pydantic
|
tests/mypy/outputs/mypy-plugin_ini/custom_constructor.py
|
{
"start": 33,
"end": 370
}
|
class ____(BaseModel):
id: int
name: str
birth_year: int
def __init__(self, id: int) -> None:
# MYPY: note: "Person" defined here
super().__init__(id=id, name='Patrick', birth_year=1991)
Person(1)
Person(id=1)
Person(name='Patrick')
# MYPY: error: Unexpected keyword argument "name" for "Person" [call-arg]
|
Person
|
python
|
wandb__wandb
|
tests/unit_tests/test_launch/test_runner/test_kubernetes.py
|
{
"start": 7158,
"end": 8551
}
|
class ____:
def __init__(self):
self.pods = dict()
self.secrets = []
self.calls = {"delete": 0}
self.namespaces = []
async def list_namespaced_pod(
self, label_selector=None, namespace="default", field_selector=None
):
ret = []
for _, pod in self.pods.items():
ret.append(pod)
return MockPodList(ret)
async def read_namespaced_pod(self, name, namespace):
return self.pods[name]
async def delete_namespaced_secret(self, namespace, name):
self.secrets = list(
filter(
lambda s: not (s[0] == namespace and s[1].metadata.name == name),
self.secrets,
)
)
self.calls["delete"] += 1
async def create_namespaced_secret(self, namespace, body):
for s in self.secrets:
if s[0] == namespace and s[1].metadata.name == body.metadata.name:
raise ApiException(status=409)
self.secrets.append((namespace, body))
async def read_namespaced_secret(self, namespace, name):
for s in self.secrets:
if s[0] == namespace and s[1].metadata.name == name:
return s[1]
async def create_namespace(self, body):
self.namespaces.append(body)
async def delete_namespace(self, name):
self.namespaces.remove(name)
|
MockCoreV1Api
|
python
|
lepture__authlib
|
authlib/integrations/django_oauth1/authorization_server.py
|
{
"start": 2627,
"end": 4560
}
|
class ____(BaseServer):
def __init__(self, client_model, token_model, token_generator=None):
super().__init__(client_model, token_model, token_generator)
self._temporary_expires_in = self._config.get(
"temporary_credential_expires_in", 86400
)
self._temporary_credential_key_prefix = self._config.get(
"temporary_credential_key_prefix", "temporary_credential:"
)
def create_temporary_credential(self, request):
key_prefix = self._temporary_credential_key_prefix
token = self.token_generator()
client_id = request.client_id
redirect_uri = request.redirect_uri
key = key_prefix + token["oauth_token"]
token["client_id"] = client_id
if redirect_uri:
token["oauth_callback"] = redirect_uri
cache.set(key, token, timeout=self._temporary_expires_in)
return TemporaryCredential(token)
def get_temporary_credential(self, request):
if not request.token:
return None
key_prefix = self._temporary_credential_key_prefix
key = key_prefix + request.token
value = cache.get(key)
if value:
return TemporaryCredential(value)
def delete_temporary_credential(self, request):
if request.token:
key_prefix = self._temporary_credential_key_prefix
key = key_prefix + request.token
cache.delete(key)
def create_authorization_verifier(self, request):
key_prefix = self._temporary_credential_key_prefix
verifier = generate_token(36)
credential = request.credential
user = request.user
key = key_prefix + credential.get_oauth_token()
credential["oauth_verifier"] = verifier
credential["user_id"] = user.pk
cache.set(key, credential, timeout=self._temporary_expires_in)
return verifier
|
CacheAuthorizationServer
|
python
|
ApeWorX__ape
|
src/ape/exceptions.py
|
{
"start": 12270,
"end": 13610
}
|
class ____(NetworkError):
"""
Raised when the network with the given name was not found.
"""
def __init__(
self,
network: str,
ecosystem: Optional[str] = None,
options: Optional[Collection[str]] = None,
):
self.network = network
options = options or []
if network in options:
# Only seen in testing scenarios. Not realistic.
raise ValueError(
f"{network} found in options. Should not have gotten `NetworkNotFoundError`."
)
if options:
message = (
f"No network in '{ecosystem}' named '{network}'."
if ecosystem
else f"No network named '{network}'."
)
close_matches = difflib.get_close_matches(network, options, cutoff=0.6)
if close_matches:
message = f"{message} Did you mean '{', '.join(close_matches)}'?"
else:
# No close matches - show all options.
options_str = "\n".join(sorted(options))
message = f"{message} Options:\n{options_str}"
elif ecosystem:
message = f"'{ecosystem}' has no networks."
else:
message = "No networks found."
super().__init__(message)
|
NetworkNotFoundError
|
python
|
huggingface__transformers
|
src/transformers/models/vilt/image_processing_vilt_fast.py
|
{
"start": 1336,
"end": 9075
}
|
class ____(BaseImageProcessorFast):
resample = PILImageResampling.BICUBIC
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
size = {"shortest_edge": 384}
do_resize = True
do_rescale = True
do_normalize = True
size_divisor = 32
do_pad = True
default_to_square = False
model_input_names = ["pixel_values", "pixel_mask"]
valid_kwargs = ViltImageProcessorKwargs
def _preprocess(
self,
images: list["torch.Tensor"],
do_resize: bool,
size: SizeDict,
interpolation: Optional["F.InterpolationMode"],
size_divisor: Optional[int],
do_pad: bool,
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
image_mean: Optional[Union[float, list[float]]],
image_std: Optional[Union[float, list[float]]],
disable_grouping: Optional[bool],
return_tensors: Optional[Union[str, TensorType]],
**kwargs,
) -> BatchFeature:
"""
Preprocess an image or batch of images.
This method overrides the base class method to include padding and pixel mask generation.
"""
# Group images by size for batched resizing
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
resized_images_grouped = {}
for shape, stacked_images in grouped_images.items():
if do_resize:
stacked_images = self.resize(stacked_images, size, interpolation, size_divisor)
resized_images_grouped[shape] = stacked_images
resized_images = reorder_images(resized_images_grouped, grouped_images_index)
# Group images by size for further processing
grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping)
processed_images_grouped = {}
for shape, stacked_images in grouped_images.items():
# Fused rescale and normalize
stacked_images = self.rescale_and_normalize(
stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std
)
processed_images_grouped[shape] = stacked_images
processed_images = reorder_images(processed_images_grouped, grouped_images_index)
# Handle padding if required
data = {}
if do_pad:
pixel_values, pixel_mask = self._pad_batch(
processed_images, return_tensors, disable_grouping=disable_grouping
)
data = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
else:
# If no padding, just return the processed images
if return_tensors == "pt":
processed_images = torch.stack(processed_images)
data = {"pixel_values": processed_images}
return BatchFeature(data=data, tensor_type=return_tensors)
def resize(
self,
images: "torch.Tensor",
size: SizeDict,
interpolation: Optional["F.InterpolationMode"] = None,
size_divisor: Optional[int] = None,
) -> "torch.Tensor":
"""
Resize an image or batch of images to specified size.
Args:
images (`torch.Tensor`): Image or batch of images to resize.
size (`dict[str, int]`): Size dictionary with shortest_edge key.
interpolation (`F.InterpolationMode`, *optional*): Interpolation method to use.
size_divisor (`int`, *optional*): Value to ensure height/width are divisible by.
Returns:
`torch.Tensor`: Resized image or batch of images.
"""
if interpolation is None:
interpolation = self.resample
# Resize with aspect ratio preservation
shorter = size.shortest_edge
longer = int(MAX_LONGER_EDGE / MAX_SHORTER_EDGE * shorter)
heights = images.shape[-2]
widths = images.shape[-1]
# Determine the new dimensions
if heights < widths:
new_heights = shorter
new_widths = widths * (shorter / heights)
else:
new_heights = heights * (shorter / widths)
new_widths = shorter
# Check if the longer side exceeds max size
if max(new_heights, new_widths) > longer:
scale = longer / max(new_heights, new_widths)
new_heights = new_heights * scale
new_widths = new_widths * scale
new_heights = int(new_heights + 0.5)
new_widths = int(new_widths + 0.5)
# Make dimensions divisible by size_divisor
if size_divisor is not None:
new_heights = new_heights // size_divisor * size_divisor
new_widths = new_widths // size_divisor * size_divisor
# Resize the image
return F.resize(images, [new_heights, new_widths], interpolation=interpolation)
def _pad_batch(
self,
images: list["torch.Tensor"],
return_tensors: Optional[Union[str, TensorType]],
disable_grouping: Optional[bool],
) -> tuple:
"""
Pad a batch of images to the same size based on the maximum dimensions.
Args:
images (`list[torch.Tensor]`): List of images to pad.
return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return.
Returns:
`tuple`: Tuple containing padded images and pixel masks.
"""
# Calculate global maximum dimensions across all images
max_size = get_max_height_width(images)
# Group images by shape before padding
grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
processed_images = {}
processed_masks = {}
for shape, stacked_images in grouped_images.items():
# Create mask template for efficient masking
if return_tensors == "pt" and len(stacked_images) > 0:
device = stacked_images.device
mask_template = torch.zeros(max_size, dtype=torch.int64, device=device)
original_size = stacked_images.shape[-2:]
needs_padding = original_size[0] != max_size[0] or original_size[1] != max_size[1]
if needs_padding:
padding_bottom = max_size[0] - original_size[0]
padding_right = max_size[1] - original_size[1]
padding = [0, 0, padding_right, padding_bottom]
padded_images = F.pad(stacked_images, padding, fill=0)
pixel_mask = mask_template.clone()
pixel_mask[: original_size[0], : original_size[1]].fill_(1)
pixel_masks = pixel_mask.unsqueeze(0).repeat(stacked_images.shape[0], 1, 1)
else:
padded_images = stacked_images
pixel_masks = torch.ones(
(stacked_images.shape[0], max_size[0], max_size[1]),
dtype=torch.int64,
device=stacked_images.device,
)
# Store processed group
processed_images[shape] = padded_images
processed_masks[shape] = pixel_masks
# Reorder images back to original order
padded_images = reorder_images(processed_images, grouped_images_index)
pixel_masks = reorder_images(processed_masks, grouped_images_index)
# Stack if tensors are requested for final result
if return_tensors == "pt" and padded_images:
padded_images = torch.stack(padded_images)
pixel_masks = torch.stack(pixel_masks)
return padded_images, pixel_masks
__all__ = ["ViltImageProcessorFast"]
|
ViltImageProcessorFast
|
python
|
ray-project__ray
|
python/ray/_private/thirdparty/pynvml/pynvml.py
|
{
"start": 70682,
"end": 70964
}
|
class ____(_PrintableStructure):
_fields_ = [
('isGridLicenseSupported', c_int),
('licensableFeaturesCount', c_uint),
('gridLicensableFeatures', c_nvmlGridLicensableFeature_v2_t * NVML_GRID_LICENSE_FEATURE_MAX_COUNT),
]
|
c_nvmlGridLicensableFeatures_v2_t
|
python
|
ray-project__ray
|
python/ray/train/tensorflow/tensorflow_predictor.py
|
{
"start": 603,
"end": 9625
}
|
class ____(DLPredictor):
"""A predictor for TensorFlow models.
Args:
model: A Tensorflow Keras model to use for predictions.
preprocessor: A preprocessor used to transform data batches prior
to prediction.
model_weights: List of weights to use for the model.
use_gpu: If set, the model will be moved to GPU on instantiation and
prediction happens on GPU.
"""
def __init__(
self,
*,
model: Optional[tf.keras.Model] = None,
preprocessor: Optional["Preprocessor"] = None,
use_gpu: bool = False,
):
self.use_gpu = use_gpu
# TensorFlow model objects cannot be pickled, therefore we use
# a callable that returns the model and initialize it here,
# instead of having an initialized model object as an attribute.
# Predictors are not serializable (see the implementation of __reduce__)
# in the Predictor class, so we can safely store the initialized model
# as an attribute.
if use_gpu:
# TODO (jiaodong): #26249 Use multiple GPU devices with sharded input
with tf.device("GPU:0"):
self._model = model
else:
self._model = model
gpu_devices = tf.config.list_physical_devices("GPU")
if len(gpu_devices) > 0 and log_once("tf_predictor_not_using_gpu"):
logger.warning(
"You have `use_gpu` as False but there are "
f"{len(gpu_devices)} GPUs detected on host where "
"prediction will only use CPU. Please consider explicitly "
"setting `TensorflowPredictor(use_gpu=True)` or "
"`batch_predictor.predict(ds, num_gpus_per_worker=1)` to "
"enable GPU prediction."
)
super().__init__(preprocessor)
def __repr__(self):
fn_name = getattr(self._model, "__name__", self._model)
fn_name_str = ""
if fn_name:
fn_name_str = str(fn_name)[:40]
return (
f"{self.__class__.__name__}("
f"model={fn_name_str!r}, "
f"preprocessor={self._preprocessor!r}, "
f"use_gpu={self.use_gpu!r})"
)
@classmethod
def from_checkpoint(
cls,
checkpoint: TensorflowCheckpoint,
model_definition: Optional[
Union[Callable[[], tf.keras.Model], Type[tf.keras.Model]]
] = None,
use_gpu: Optional[bool] = False,
) -> "TensorflowPredictor":
"""Instantiate the predictor from a TensorflowCheckpoint.
Args:
checkpoint: The checkpoint to load the model and preprocessor from.
model_definition: A callable that returns a TensorFlow Keras model
to use. Model weights will be loaded from the checkpoint.
This is only needed if the `checkpoint` was created from
`TensorflowCheckpoint.from_model`.
use_gpu: Whether GPU should be used during prediction.
"""
if model_definition:
raise DeprecationWarning(
"`model_definition` is deprecated. `TensorflowCheckpoint.from_model` "
"now saves the full model definition in .keras format."
)
model = checkpoint.get_model()
preprocessor = checkpoint.get_preprocessor()
return cls(
model=model,
preprocessor=preprocessor,
use_gpu=use_gpu,
)
@DeveloperAPI
def call_model(
self, inputs: Union[tf.Tensor, Dict[str, tf.Tensor]]
) -> Union[tf.Tensor, Dict[str, tf.Tensor]]:
"""Runs inference on a single batch of tensor data.
This method is called by `TorchPredictor.predict` after converting the
original data batch to torch tensors.
Override this method to add custom logic for processing the model input or
output.
Example:
.. testcode::
# List outputs are not supported by default TensorflowPredictor.
def build_model() -> tf.keras.Model:
input = tf.keras.layers.Input(shape=1)
model = tf.keras.models.Model(inputs=input, outputs=[input, input])
return model
# Use a custom predictor to format model output as a dict.
class CustomPredictor(TensorflowPredictor):
def call_model(self, inputs):
model_output = super().call_model(inputs)
return {
str(i): model_output[i] for i in range(len(model_output))
}
import numpy as np
data_batch = np.array([[0.5], [0.6], [0.7]], dtype=np.float32)
predictor = CustomPredictor(model=build_model())
predictions = predictor.predict(data_batch)
Args:
inputs: A batch of data to predict on, represented as either a single
TensorFlow tensor or for multi-input models, a dictionary of tensors.
Returns:
The model outputs, either as a single tensor or a dictionary of tensors.
"""
if self.use_gpu:
with tf.device("GPU:0"):
return self._model(inputs)
else:
return self._model(inputs)
def predict(
self,
data: DataBatchType,
dtype: Optional[Union[tf.dtypes.DType, Dict[str, tf.dtypes.DType]]] = None,
) -> DataBatchType:
"""Run inference on data batch.
If the provided data is a single array or a dataframe/table with a single
column, it will be converted into a single Tensorflow tensor before being
inputted to the model.
If the provided data is a multi-column table or a dict of numpy arrays,
it will be converted into a dict of tensors before being inputted to the
model. This is useful for multi-modal inputs (for example your model accepts
both image and text).
Args:
data: A batch of input data. Either a pandas DataFrame or numpy
array.
dtype: The dtypes to use for the tensors. Either a single dtype for all
tensors or a mapping from column name to dtype.
Examples:
.. testcode::
import numpy as np
import tensorflow as tf
from ray.train.tensorflow import TensorflowPredictor
def build_model():
return tf.keras.Sequential(
[
tf.keras.layers.InputLayer(input_shape=()),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1),
]
)
weights = [np.array([[2.0]]), np.array([0.0])]
predictor = TensorflowPredictor(model=build_model())
data = np.asarray([1, 2, 3])
predictions = predictor.predict(data)
import pandas as pd
import tensorflow as tf
from ray.train.tensorflow import TensorflowPredictor
def build_model():
input1 = tf.keras.layers.Input(shape=(1,), name="A")
input2 = tf.keras.layers.Input(shape=(1,), name="B")
merged = tf.keras.layers.Concatenate(axis=1)([input1, input2])
output = tf.keras.layers.Dense(2, input_dim=2)(merged)
return tf.keras.models.Model(
inputs=[input1, input2], outputs=output)
predictor = TensorflowPredictor(model=build_model())
# Pandas dataframe.
data = pd.DataFrame([[1, 2], [3, 4]], columns=["A", "B"])
predictions = predictor.predict(data)
Returns:
DataBatchType: Prediction result. The return type will be the same as the
input type.
"""
return super(TensorflowPredictor, self).predict(data=data, dtype=dtype)
def _arrays_to_tensors(
self,
numpy_arrays: Union[np.ndarray, Dict[str, np.ndarray]],
dtype: Optional[Union[tf.dtypes.DType, Dict[str, tf.dtypes.DType]]],
) -> Union[tf.Tensor, Dict[str, tf.Tensor]]:
return convert_ndarray_batch_to_tf_tensor_batch(numpy_arrays, dtypes=dtype)
def _tensor_to_array(self, tensor: tf.Tensor) -> np.ndarray:
if not isinstance(tensor, tf.Tensor):
raise ValueError(
"Expected the model to return either a tf.Tensor or a "
f"dict of tf.Tensor, but got {type(tensor)} instead. "
f"To support models with different output types, subclass "
f"TensorflowPredictor and override the `call_model` method "
f"to process the output into either torch.Tensor or Dict["
f"str, torch.Tensor]."
)
return tensor.numpy()
|
TensorflowPredictor
|
python
|
has2k1__plotnine
|
plotnine/guides/guide_colorbar.py
|
{
"start": 13533,
"end": 16280
}
|
class ____(GuideElements):
"""
Access & calculate theming for the colobar
"""
@cached_property
def text(self):
size = self.theme.getp(("legend_text_colorbar", "size"))
ha = self.theme.getp(("legend_text_colorbar", "ha"))
va = self.theme.getp(("legend_text_colorbar", "va"))
is_blank = self.theme.T.is_blank("legend_text_colorbar")
# Default text alignment depends on the direction of the
# colorbar
_loc = get_opposite_side(self.text_position)
if self.is_vertical:
ha = ha or _loc
va = va or "center"
else:
va = va or _loc
ha = ha or "center"
return NS(
margin=self._text_margin,
align=None,
fontsize=size,
ha=ha,
va=va,
is_blank=is_blank,
)
@cached_property
def text_position(self) -> Side:
if not (position := self.theme.getp("legend_text_position")):
position = "right" if self.is_vertical else "bottom"
if self.is_vertical and position not in ("right", "left"):
msg = (
"The text position for a vertical legend must be "
"either left or right."
)
raise PlotnineError(msg)
elif self.is_horizontal and position not in ("bottom", "top"):
msg = (
"The text position for a horizonta legend must be "
"either top or bottom."
)
raise PlotnineError(msg)
return position
@cached_property
def key_width(self):
# We scale up the width only if it inherited its value
dim = (self.is_vertical and "width") or "height"
legend_key_dim = f"legend_key_{dim}"
inherited = self.theme.T.get(legend_key_dim) is None
scale = 1.45 if inherited else 1
return np.round(self.theme.getp(legend_key_dim) * scale)
@cached_property
def key_height(self):
# We scale up the height only if it inherited its value
dim = (self.is_vertical and "height") or "width"
legend_key_dim = f"legend_key_{dim}"
inherited = self.theme.T.get(legend_key_dim) is None
scale = (1.45 * 5) if inherited else 1
return np.round(self.theme.getp(legend_key_dim) * scale)
@cached_property
def frame(self):
lw = self.theme.getp(("legend_frame", "linewidth"), 0)
return NS(linewidth=lw)
@cached_property
def ticks_length(self):
return self.theme.getp("legend_ticks_length")
@cached_property
def ticks(self):
lw = self.theme.getp(("legend_ticks", "linewidth"))
return NS(linewidth=lw)
|
GuideElementsColorbar
|
python
|
kamyu104__LeetCode-Solutions
|
Python/divide-nodes-into-the-maximum-number-of-groups.py
|
{
"start": 1663,
"end": 3324
}
|
class ____(object):
def magnificentSets(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def bfs(u):
group = []
q = [u]
lookup[u] = True
while q:
new_q = []
for u in q:
group.append(u)
for v in adj[u]:
if lookup[v]:
continue
lookup[v] = True
new_q.append(v)
q = new_q
return group
def bfs2(u):
result = 0
lookup = [False]*n
q = {u}
lookup[u] = True
while q:
new_q = set()
for u in q:
for v in adj[u]:
if v in q:
return 0
if lookup[v]:
continue
lookup[v] = True
new_q.add(v)
q = new_q
result += 1
return result
adj = [[] for _ in xrange(n)]
for u, v in edges:
adj[u-1].append(v-1)
adj[v-1].append(u-1)
result = 0
lookup = [0]*n
for u in xrange(n):
if lookup[u]:
continue
group = bfs(u)
mx = 0
for u in group:
d = bfs2(u)
if d == 0:
return -1
mx = max(mx, d)
result += mx
return result
|
Solution2
|
python
|
tensorflow__tensorflow
|
tensorflow/python/distribute/distribute_coordinator.py
|
{
"start": 1497,
"end": 2131
}
|
class ____(object):
"""Specify how distribute coordinator runs."""
# The default mode where distribute coordinator will run as a standalone
# client and connects to remote servers for training. Each remote server can
# use the distribute coordinator binary with task_type set correctly which
# will then turn into standard servers.
STANDALONE_CLIENT = "standalone_client"
# The distribute coordinator runs on each worker. It will run a standard
# server on each worker and optionally run the `worker_fn` that is configured
# to talk to its standard server.
INDEPENDENT_WORKER = "independent_worker"
|
CoordinatorMode
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-appsflyer/source_appsflyer/source.py
|
{
"start": 13988,
"end": 17229
}
|
class ____(AbstractSource):
def check_connection(self, logger, config) -> Tuple[bool, any]:
try:
timezone = config.get("timezone", "UTC")
if timezone not in pendulum.timezones:
return False, "The supplied timezone is invalid."
app_id = config["app_id"]
api_token = config["api_token"]
dates = pendulum.now("UTC").to_date_string()
test_url = f"https://hq1.appsflyer.com/api/agg-data/export/app/{app_id}/partners_report/v5?from={dates}&to={dates}&timezone=UTC"
headers = {"Authorization": f"Bearer {api_token}"}
response = requests.request("GET", url=test_url, headers=headers)
if response.status_code != 200:
error_message = "The supplied APP ID is invalid" if response.status_code == 404 else response.text.rstrip("\n")
if error_message:
return False, error_message
response.raise_for_status()
except Exception as e:
return False, e
return True, None
def is_start_date_before_earliest_date(self, start_date, earliest_date):
if start_date <= earliest_date:
logging.getLogger("airbyte").log(logging.INFO, f"Start date over 90 days, using start_date: {earliest_date}")
return earliest_date
return start_date
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
config["timezone"] = config.get("timezone", "UTC")
timezone = pendulum.timezone(config.get("timezone", "UTC"))
earliest_date = pendulum.today(timezone) - timedelta(days=90)
start_date = parse_date(config.get("start_date") or pendulum.today(timezone), timezone)
config["start_date"] = self.is_start_date_before_earliest_date(start_date, earliest_date)
config["end_date"] = pendulum.now(timezone)
logging.getLogger("airbyte").log(logging.INFO, f"Using start_date: {config['start_date']}, end_date: {config['end_date']}")
auth = TokenAuthenticator(token=config["api_token"])
return [
InAppEvents(authenticator=auth, **config),
OrganicInAppEvents(authenticator=auth, **config),
RetargetingInAppEvents(authenticator=auth, **config),
Installs(authenticator=auth, **config),
OrganicInstalls(authenticator=auth, **config),
RetargetingInstalls(authenticator=auth, **config),
UninstallEvents(authenticator=auth, **config),
OrganicUninstallEvents(authenticator=auth, **config),
DailyReport(authenticator=auth, **config),
RetargetingDailyReport(authenticator=auth, **config),
PartnersReport(authenticator=auth, **config),
RetargetingPartnersReport(authenticator=auth, **config),
PartnersEventsReport(authenticator=auth, **config),
RetargetingPartnersEventsReport(authenticator=auth, **config),
GeoReport(authenticator=auth, **config),
RetargetingGeoReport(authenticator=auth, **config),
GeoEventsReport(authenticator=auth, **config),
RetargetingGeoEventsReport(authenticator=auth, **config),
]
|
SourceAppsflyer
|
python
|
SmileyChris__easy-thumbnails
|
easy_thumbnails/tests/test_aliases.py
|
{
"start": 8024,
"end": 10356
}
|
class ____(GenerationBase):
"""
Test the ``generate_aliases`` signal handler behaviour.
"""
def get_signal_handler(self):
return signal_handlers.generate_aliases
def test_empty(self):
"""
Thumbnails are not generated if there isn't anything to generate...
"""
profile = models.Profile(avatar=None)
files = self.fake_save(profile)
self.assertEqual(len(files), 1)
def test_no_change(self):
"""
Thumbnails are only generated when the file is modified.
"""
profile = models.Profile(avatar='avatars/test.jpg')
files = self.fake_save(profile)
self.assertEqual(len(files), 1)
def test_changed(self):
"""
When a file is modified, thumbnails are built for all matching
non-global aliases.
"""
profile = models.Profile(avatar='avatars/test.jpg')
profile.avatar._committed = False
files = self.fake_save(profile)
# 1 source, 4 thumbs.
self.assertEqual(len(files), 5)
def test_deleted(self):
profile = models.Profile(avatar='avatars/test.jpg')
profile.avatar.delete(save=False)
files = self.fake_save(profile)
self.assertEqual(len(files), 0)
def test_clearable(self):
"""
A ClearablFileInput will set field value to False before pre_save
"""
profile = models.Profile(avatar='avatars/test.jpg')
cls = profile.__class__
profile.avatar = False
pre_save.send(sender=cls, instance=profile)
# Saving will then properly clear
profile.avatar = ''
post_save.send(sender=cls, instance=profile)
# FileField is cleared, but not explicitly deleted, file remains
files = self.storage.listdir('avatars')[1]
self.assertEqual(len(files), 1)
def test_standard_filefield(self):
profile = models.Profile(avatar='avatars/test.jpg')
# Attach a File object to the FileField descriptor, emulating an
# upload.
with self.storage.open(self.create_image(self.storage, 'avatars/second.jpg')) as logo:
profile.logo = logo
list_files = self.fake_save(profile)
# 2 source, 2 thumbs.
self.assertEqual(len(list_files), 4)
|
GenerationTest
|
python
|
davidhalter__jedi
|
jedi/inference/compiled/__init__.py
|
{
"start": 729,
"end": 2651
}
|
class ____(LazyValueWrapper):
"""
This class represents exact values, that makes operations like additions
and exact boolean values possible, while still being a "normal" stub.
"""
def __init__(self, compiled_value):
self.inference_state = compiled_value.inference_state
self._compiled_value = compiled_value
def __getattribute__(self, name):
if name in ('get_safe_value', 'execute_operation', 'access_handle',
'negate', 'py__bool__', 'is_compiled'):
return getattr(self._compiled_value, name)
return super().__getattribute__(name)
def _get_wrapped_value(self):
instance, = builtin_from_name(
self.inference_state, self._compiled_value.name.string_name).execute_with_values()
return instance
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self._compiled_value)
def create_simple_object(inference_state, obj):
"""
Only allows creations of objects that are easily picklable across Python
versions.
"""
assert type(obj) in (int, float, str, bytes, slice, complex, bool), repr(obj)
compiled_value = create_from_access_path(
inference_state,
inference_state.compiled_subprocess.create_simple_object(obj)
)
return ExactValue(compiled_value)
def get_string_value_set(inference_state):
return builtin_from_name(inference_state, 'str').execute_with_values()
def load_module(inference_state, dotted_name, **kwargs):
# Temporary, some tensorflow builtins cannot be loaded, so it's tried again
# and again and it's really slow.
if dotted_name.startswith('tensorflow.'):
return None
access_path = inference_state.compiled_subprocess.load_module(dotted_name=dotted_name, **kwargs)
if access_path is None:
return None
return create_from_access_path(inference_state, access_path)
|
ExactValue
|
python
|
pytorch__pytorch
|
torch/distributed/elastic/rendezvous/dynamic_rendezvous.py
|
{
"start": 27861,
"end": 32610
}
|
class ____:
"""Represent a rendezvous join operation."""
def __call__(self, ctx: _RendezvousContext, deadline: float) -> _Action:
state = ctx.state
# A closed rendezvous means that it no longer accepts new nodes.
if state.closed:
if ctx.node in state.redundancy_list:
msg = f"The rendezvous '{ctx.settings.run_id}' is closed, terminating pending rendezvous."
raise RendezvousGracefulExitError(msg)
return _Action.ERROR_CLOSED
if ctx.node in state.redundancy_list:
msg = f"The node {ctx.node} is in redundancy list"
logger.debug(msg)
# don't apply the timeout logic here, since we want to allow the node to rejoin
if len(state.participants) == ctx.settings.max_nodes:
if _should_keep_alive(ctx):
return _Action.KEEP_ALIVE
else:
return _Action.SYNC
else:
# transition to waiting state that will respect timeouts.
msg = f"The node {ctx.node} is removed from redundancy list"
logger.debug(msg)
return _Action.REMOVE_FROM_REDUNDANCY_LIST
is_participant = ctx.node in state.participants
# If we are part of the rendezvous and it is already complete there is
# no further action to take.
if state.complete and is_participant:
return _Action.FINISH
now = time.monotonic()
if now > deadline:
rollback_period = 5 # 5 seconds
# If we still have time to rollback (a short period on top of the
# operation deadline), try to remove ourself from the rendezvous.
# It is okay if we can't though as our keep-alive will eventually
# expire.
if now <= deadline + rollback_period:
# If we are part of the rendezvous, it means we couldn't find
# enough participants to complete it on time.
if is_participant:
return _Action.REMOVE_FROM_PARTICIPANTS
# If we are in the wait list, it means we couldn't wait till the
# next round of the rendezvous.
if ctx.node in state.wait_list:
return _Action.REMOVE_FROM_WAIT_LIST
return _Action.ERROR_TIMEOUT
if state.complete:
# If we are here, it means we are not part of the rendezvous. In
# case the rendezvous has capacity for additional participants add
# ourself to the wait list for the next round.
if len(state.participants) < ctx.settings.max_nodes:
if ctx.node not in state.wait_list:
return _Action.ADD_TO_WAIT_LIST
elif len(state.participants) >= ctx.settings.max_nodes:
if (
ctx.node not in state.redundancy_list
and ctx.node not in state.wait_list
):
return _Action.ADD_TO_REDUNDANCY_LIST
elif is_participant:
# If the rendezvous has enough number of participants including us,
# check whether we have passed the rendezvous deadline. If yes,
# complete it.
if (
len(state.participants) >= ctx.settings.min_nodes
and len(state.participants) <= ctx.settings.max_nodes
and state.deadline is not None
):
if state.deadline < datetime.now(timezone.utc):
msg = (
f"The node '{ctx.node}' marking the rendezvous complete, "
f"quorum established within deadline"
)
logger.debug(msg)
return _Action.MARK_RENDEZVOUS_COMPLETE
else:
msg = f"The node '{ctx.node}' can't complete rendezvous: deadline reached"
logger.debug(msg)
else:
msg = f"The node '{ctx.node}' can't complete rendezvous: not enough participants"
logger.debug(msg)
else:
# The rendezvous is not complete yet and we are not part of it. Try
# to join.
return _Action.ADD_TO_PARTICIPANTS
if _should_keep_alive(ctx):
return _Action.KEEP_ALIVE
# At this point either the rendezvous is not complete, but we are part
# of it, which means we have to wait for other participants to join; or
# the rendezvous is complete, but we are not part of it, which means we
# have to wait for the next round.
return _Action.SYNC
|
_RendezvousJoinOp
|
python
|
Lightning-AI__lightning
|
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
|
{
"start": 41673,
"end": 41902
}
|
class ____(Callback):
def on_validation_epoch_end(self, trainer, pl_module):
if not trainer.sanity_checking and trainer.current_epoch == 1:
raise RuntimeError("Trouble!")
|
TroubledCallbackOnValidationEpochEnd
|
python
|
walkccc__LeetCode
|
solutions/1019. Next Greater Node In Linked List/1019.py
|
{
"start": 0,
"end": 359
}
|
class ____:
def nextLargerNodes(self, head: ListNode) -> list[int]:
ans = []
stack = []
while head:
while stack and head.val > ans[stack[-1]]:
index = stack.pop()
ans[index] = head.val
stack.append(len(ans))
ans.append(head.val)
head = head.next
for i in stack:
ans[i] = 0
return ans
|
Solution
|
python
|
matplotlib__matplotlib
|
lib/matplotlib/ticker.py
|
{
"start": 68353,
"end": 70838
}
|
class ____(Locator):
"""
Place ticks at every integer multiple of a base plus an offset.
"""
def __init__(self, base=1.0, offset=0.0):
"""
Parameters
----------
base : float > 0, default: 1.0
Interval between ticks.
offset : float, default: 0.0
Value added to each multiple of *base*.
.. versionadded:: 3.8
"""
self._edge = _Edge_integer(base, 0)
self._offset = offset
def set_params(self, base=None, offset=None):
"""
Set parameters within this locator.
Parameters
----------
base : float > 0, optional
Interval between ticks.
offset : float, optional
Value added to each multiple of *base*.
.. versionadded:: 3.8
"""
if base is not None:
self._edge = _Edge_integer(base, 0)
if offset is not None:
self._offset = offset
def __call__(self):
"""Return the locations of the ticks."""
vmin, vmax = self.axis.get_view_interval()
return self.tick_values(vmin, vmax)
def tick_values(self, vmin, vmax):
if vmax < vmin:
vmin, vmax = vmax, vmin
step = self._edge.step
vmin -= self._offset
vmax -= self._offset
vmin = self._edge.ge(vmin) * step
n = (vmax - vmin + 0.001 * step) // step
locs = vmin - step + np.arange(n + 3) * step + self._offset
return self.raise_if_exceeds(locs)
def view_limits(self, dmin, dmax):
"""
Set the view limits to the nearest tick values that contain the data.
"""
if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':
vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset
vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset
if vmin == vmax:
vmin -= 1
vmax += 1
else:
vmin = dmin
vmax = dmax
return mtransforms.nonsingular(vmin, vmax)
def scale_range(vmin, vmax, n=1, threshold=100):
dv = abs(vmax - vmin) # > 0 as nonsingular is called before.
meanv = (vmax + vmin) / 2
if abs(meanv) / dv < threshold:
offset = 0
else:
offset = math.copysign(10 ** (math.log10(abs(meanv)) // 1), meanv)
scale = 10 ** (math.log10(dv / n) // 1)
return scale, offset
|
MultipleLocator
|
python
|
aimacode__aima-python
|
logic.py
|
{
"start": 50240,
"end": 66401
}
|
class ____(Agent):
"""
[Figure 7.20]
An agent for the wumpus world that does logical inference.
"""
def __init__(self, dimentions):
self.dimrow = dimentions
self.kb = WumpusKB(self.dimrow)
self.t = 0
self.plan = list()
self.current_position = WumpusPosition(1, 1, 'UP')
super().__init__(self.execute)
def execute(self, percept):
self.kb.make_percept_sentence(percept, self.t)
self.kb.add_temporal_sentences(self.t)
temp = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if self.kb.ask_if_true(location(i, j, self.t)):
temp.append(i)
temp.append(j)
if self.kb.ask_if_true(facing_north(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'UP')
elif self.kb.ask_if_true(facing_south(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'DOWN')
elif self.kb.ask_if_true(facing_west(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'LEFT')
elif self.kb.ask_if_true(facing_east(self.t)):
self.current_position = WumpusPosition(temp[0], temp[1], 'RIGHT')
safe_points = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if self.kb.ask_if_true(ok_to_move(i, j, self.t)):
safe_points.append([i, j])
if self.kb.ask_if_true(percept_glitter(self.t)):
goals = list()
goals.append([1, 1])
self.plan.append('Grab')
actions = self.plan_route(self.current_position, goals, safe_points)
self.plan.extend(actions)
self.plan.append('Climb')
if len(self.plan) == 0:
unvisited = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
for k in range(self.t):
if self.kb.ask_if_true(location(i, j, k)):
unvisited.append([i, j])
unvisited_and_safe = list()
for u in unvisited:
for s in safe_points:
if u not in unvisited_and_safe and s == u:
unvisited_and_safe.append(u)
temp = self.plan_route(self.current_position, unvisited_and_safe, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0 and self.kb.ask_if_true(have_arrow(self.t)):
possible_wumpus = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if not self.kb.ask_if_true(wumpus(i, j)):
possible_wumpus.append([i, j])
temp = self.plan_shot(self.current_position, possible_wumpus, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0:
not_unsafe = list()
for i in range(1, self.dimrow + 1):
for j in range(1, self.dimrow + 1):
if not self.kb.ask_if_true(ok_to_move(i, j, self.t)):
not_unsafe.append([i, j])
temp = self.plan_route(self.current_position, not_unsafe, safe_points)
self.plan.extend(temp)
if len(self.plan) == 0:
start = list()
start.append([1, 1])
temp = self.plan_route(self.current_position, start, safe_points)
self.plan.extend(temp)
self.plan.append('Climb')
action = self.plan[0]
self.plan = self.plan[1:]
self.kb.make_action_sentence(action, self.t)
self.t += 1
return action
def plan_route(self, current, goals, allowed):
problem = PlanRoute(current, goals, allowed, self.dimrow)
return astar_search(problem).solution()
def plan_shot(self, current, goals, allowed):
shooting_positions = set()
for loc in goals:
x = loc[0]
y = loc[1]
for i in range(1, self.dimrow + 1):
if i < x:
shooting_positions.add(WumpusPosition(i, y, 'EAST'))
if i > x:
shooting_positions.add(WumpusPosition(i, y, 'WEST'))
if i < y:
shooting_positions.add(WumpusPosition(x, i, 'NORTH'))
if i > y:
shooting_positions.add(WumpusPosition(x, i, 'SOUTH'))
# Can't have a shooting position from any of the rooms the Wumpus could reside
orientations = ['EAST', 'WEST', 'NORTH', 'SOUTH']
for loc in goals:
for orientation in orientations:
shooting_positions.remove(WumpusPosition(loc[0], loc[1], orientation))
actions = list()
actions.extend(self.plan_route(current, shooting_positions, allowed))
actions.append('Shoot')
return actions
# ______________________________________________________________________________
def SAT_plan(init, transition, goal, t_max, SAT_solver=cdcl_satisfiable):
"""
[Figure 7.22]
Converts a planning problem to Satisfaction problem by translating it to a cnf sentence.
>>> transition = {'A': {'Left': 'A', 'Right': 'B'}, 'B': {'Left': 'A', 'Right': 'C'}, 'C': {'Left': 'B', 'Right': 'C'}}
>>> SAT_plan('A', transition, 'C', 1) is None
True
"""
# Functions used by SAT_plan
def translate_to_SAT(init, transition, goal, time):
clauses = []
states = [state for state in transition]
# Symbol claiming state s at time t
state_counter = itertools.count()
for s in states:
for t in range(time + 1):
state_sym[s, t] = Expr('S_{}'.format(next(state_counter)))
# Add initial state axiom
clauses.append(state_sym[init, 0])
# Add goal state axiom
clauses.append(state_sym[first(clause[0] for clause in state_sym
if set(conjuncts(clause[0])).issuperset(conjuncts(goal))), time]) \
if isinstance(goal, Expr) else clauses.append(state_sym[goal, time])
# All possible transitions
transition_counter = itertools.count()
for s in states:
for action in transition[s]:
s_ = transition[s][action]
for t in range(time):
# Action 'action' taken from state 's' at time 't' to reach 's_'
action_sym[s, action, t] = Expr('T_{}'.format(next(transition_counter)))
# Change the state from s to s_
clauses.append(action_sym[s, action, t] | '==>' | state_sym[s, t])
clauses.append(action_sym[s, action, t] | '==>' | state_sym[s_, t + 1])
# Allow only one state at any time
for t in range(time + 1):
# must be a state at any time
clauses.append(associate('|', [state_sym[s, t] for s in states]))
for s in states:
for s_ in states[states.index(s) + 1:]:
# for each pair of states s, s_ only one is possible at time t
clauses.append((~state_sym[s, t]) | (~state_sym[s_, t]))
# Restrict to one transition per timestep
for t in range(time):
# list of possible transitions at time t
transitions_t = [tr for tr in action_sym if tr[2] == t]
# make sure at least one of the transitions happens
clauses.append(associate('|', [action_sym[tr] for tr in transitions_t]))
for tr in transitions_t:
for tr_ in transitions_t[transitions_t.index(tr) + 1:]:
# there cannot be two transitions tr and tr_ at time t
clauses.append(~action_sym[tr] | ~action_sym[tr_])
# Combine the clauses to form the cnf
return associate('&', clauses)
def extract_solution(model):
true_transitions = [t for t in action_sym if model[action_sym[t]]]
# Sort transitions based on time, which is the 3rd element of the tuple
true_transitions.sort(key=lambda x: x[2])
return [action for s, action, time in true_transitions]
# Body of SAT_plan algorithm
for t in range(t_max + 1):
# dictionaries to help extract the solution from model
state_sym = {}
action_sym = {}
cnf = translate_to_SAT(init, transition, goal, t)
model = SAT_solver(cnf)
if model is not False:
return extract_solution(model)
return None
# ______________________________________________________________________________
def unify(x, y, s={}):
"""
[Figure 9.1]
Unify expressions x,y with substitution s; return a substitution that
would make x,y equal, or None if x,y can not unify. x and y can be
variables (e.g. Expr('x')), constants, lists, or Exprs.
>>> unify(x, 3, {})
{x: 3}
"""
if s is None:
return None
elif x == y:
return s
elif is_variable(x):
return unify_var(x, y, s)
elif is_variable(y):
return unify_var(y, x, s)
elif isinstance(x, Expr) and isinstance(y, Expr):
return unify(x.args, y.args, unify(x.op, y.op, s))
elif isinstance(x, str) or isinstance(y, str):
return None
elif issequence(x) and issequence(y) and len(x) == len(y):
if not x:
return s
return unify(x[1:], y[1:], unify(x[0], y[0], s))
else:
return None
def is_variable(x):
"""A variable is an Expr with no args and a lowercase symbol as the op."""
return isinstance(x, Expr) and not x.args and x.op[0].islower()
def unify_var(var, x, s):
if var in s:
return unify(s[var], x, s)
elif x in s:
return unify(var, s[x], s)
elif occur_check(var, x, s):
return None
else:
new_s = extend(s, var, x)
cascade_substitution(new_s)
return new_s
def occur_check(var, x, s):
"""Return true if variable var occurs anywhere in x
(or in subst(s, x), if s has a binding for x)."""
if var == x:
return True
elif is_variable(x) and x in s:
return occur_check(var, s[x], s)
elif isinstance(x, Expr):
return (occur_check(var, x.op, s) or
occur_check(var, x.args, s))
elif isinstance(x, (list, tuple)):
return first(e for e in x if occur_check(var, e, s))
else:
return False
def subst(s, x):
"""Substitute the substitution s into the expression x.
>>> subst({x: 42, y:0}, F(x) + y)
(F(42) + 0)
"""
if isinstance(x, list):
return [subst(s, xi) for xi in x]
elif isinstance(x, tuple):
return tuple([subst(s, xi) for xi in x])
elif not isinstance(x, Expr):
return x
elif is_var_symbol(x.op):
return s.get(x, x)
else:
return Expr(x.op, *[subst(s, arg) for arg in x.args])
def cascade_substitution(s):
"""This method allows to return a correct unifier in normal form
and perform a cascade substitution to s.
For every mapping in s perform a cascade substitution on s.get(x)
and if it is replaced with a function ensure that all the function
terms are correct updates by passing over them again.
>>> s = {x: y, y: G(z)}
>>> cascade_substitution(s)
>>> s == {x: G(z), y: G(z)}
True
"""
for x in s:
s[x] = subst(s, s.get(x))
if isinstance(s.get(x), Expr) and not is_variable(s.get(x)):
# Ensure Function Terms are correct updates by passing over them again
s[x] = subst(s, s.get(x))
def unify_mm(x, y, s={}):
"""Unify expressions x,y with substitution s using an efficient rule-based
unification algorithm by Martelli & Montanari; return a substitution that
would make x,y equal, or None if x,y can not unify. x and y can be
variables (e.g. Expr('x')), constants, lists, or Exprs.
>>> unify_mm(x, 3, {})
{x: 3}
"""
set_eq = extend(s, x, y)
s = set_eq.copy()
while True:
trans = 0
for x, y in set_eq.items():
if x == y:
# if x = y this mapping is deleted (rule b)
del s[x]
elif not is_variable(x) and is_variable(y):
# if x is not a variable and y is a variable, rewrite it as y = x in s (rule a)
if s.get(y, None) is None:
s[y] = x
del s[x]
else:
# if a mapping already exist for variable y then apply
# variable elimination (there is a chance to apply rule d)
s[x] = vars_elimination(y, s)
elif not is_variable(x) and not is_variable(y):
# in which case x and y are not variables, if the two root function symbols
# are different, stop with failure, else apply term reduction (rule c)
if x.op is y.op and len(x.args) == len(y.args):
term_reduction(x, y, s)
del s[x]
else:
return None
elif isinstance(y, Expr):
# in which case x is a variable and y is a function or a variable (e.g. F(z) or y),
# if y is a function, we must check if x occurs in y, then stop with failure, else
# try to apply variable elimination to y (rule d)
if occur_check(x, y, s):
return None
s[x] = vars_elimination(y, s)
if y == s.get(x):
trans += 1
else:
trans += 1
if trans == len(set_eq):
# if no transformation has been applied, stop with success
return s
set_eq = s.copy()
def term_reduction(x, y, s):
"""Apply term reduction to x and y if both are functions and the two root function
symbols are equals (e.g. F(x1, x2, ..., xn) and F(x1', x2', ..., xn')) by returning
a new mapping obtained by replacing x: y with {x1: x1', x2: x2', ..., xn: xn'}
"""
for i in range(len(x.args)):
if x.args[i] in s:
s[s.get(x.args[i])] = y.args[i]
else:
s[x.args[i]] = y.args[i]
def vars_elimination(x, s):
"""Apply variable elimination to x: if x is a variable and occurs in s, return
the term mapped by x, else if x is a function recursively applies variable
elimination to each term of the function."""
if not isinstance(x, Expr):
return x
if is_variable(x):
return s.get(x, x)
return Expr(x.op, *[vars_elimination(arg, s) for arg in x.args])
def standardize_variables(sentence, dic=None):
"""Replace all the variables in sentence with new variables."""
if dic is None:
dic = {}
if not isinstance(sentence, Expr):
return sentence
elif is_var_symbol(sentence.op):
if sentence in dic:
return dic[sentence]
else:
v = Expr('v_{}'.format(next(standardize_variables.counter)))
dic[sentence] = v
return v
else:
return Expr(sentence.op, *[standardize_variables(a, dic) for a in sentence.args])
standardize_variables.counter = itertools.count()
# ______________________________________________________________________________
def parse_clauses_from_dimacs(dimacs_cnf):
"""Converts a string into CNF clauses according to the DIMACS format used in SAT competitions"""
return map(lambda c: associate('|', c),
map(lambda c: [expr('~X' + str(abs(l))) if l < 0 else expr('X' + str(l)) for l in c],
map(lambda line: map(int, line.split()),
filter(None, ' '.join(
filter(lambda line: line[0] not in ('c', 'p'),
filter(None, dimacs_cnf.strip().replace('\t', ' ').split('\n')))).split(' 0')))))
# ______________________________________________________________________________
|
HybridWumpusAgent
|
python
|
xlwings__xlwings
|
xlwings/constants.py
|
{
"start": 52083,
"end": 52488
}
|
class ____:
xlDataLabelsShowBubbleSizes = 6 # from enum XlDataLabelsType
xlDataLabelsShowLabel = 4 # from enum XlDataLabelsType
xlDataLabelsShowLabelAndPercent = 5 # from enum XlDataLabelsType
xlDataLabelsShowNone = -4142 # from enum XlDataLabelsType
xlDataLabelsShowPercent = 3 # from enum XlDataLabelsType
xlDataLabelsShowValue = 2 # from enum XlDataLabelsType
|
DataLabelsType
|
python
|
tox-dev__tox
|
src/tox/tox_env/python/pip/req/args.py
|
{
"start": 2829,
"end": 3322
}
|
class ____(Action):
def __call__(
self,
parser: ArgumentParser, # noqa: ARG002
namespace: Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None, # noqa: ARG002
) -> None:
if getattr(namespace, self.dest, None) is None:
setattr(namespace, self.dest, [])
current = getattr(namespace, self.dest)
if values not in current:
bisect.insort(current, values)
|
AddSortedUniqueAction
|
python
|
pypa__warehouse
|
tests/unit/macaroons/test_models.py
|
{
"start": 225,
"end": 1364
}
|
class ____:
@pytest.mark.parametrize(
("value", "expected"),
[
(
[
caveats.ProjectName(normalized_names=["example"]),
caveats.Expiration(expires_at=1705876828, not_before=1705875828),
],
[[1, ["example"]], [0, 1705876828, 1705875828]],
),
([], []),
],
)
def test_serialization(self, value, expected):
dm = models.Macaroon()
dm.caveats = value
assert dm._caveats == expected
@pytest.mark.parametrize(
("value", "expected"),
[
(
[[3, "a614e122-a9ee-473c-b6df-8c4f1b776628"], [1, ["foo", "bar"]]],
[
caveats.RequestUser(user_id="a614e122-a9ee-473c-b6df-8c4f1b776628"),
caveats.ProjectName(normalized_names=["foo", "bar"]),
],
),
([], []),
],
)
def test_deserialization(self, value, expected):
dm = models.Macaroon()
dm._caveats = value
assert dm.caveats == expected
|
TestCaveats
|
python
|
getsentry__sentry
|
src/sentry/integrations/bitbucket/webhook.py
|
{
"start": 2616,
"end": 3922
}
|
class ____(SCMWebhook, ABC):
@property
def provider(self) -> str:
return IntegrationProviderSlug.BITBUCKET.value
def update_repo_data(self, repo: Repository, event: Mapping[str, Any]) -> None:
"""
Given a webhook payload, update stored repo data if needed.
NB: Assumes event['repository']['full_name'] is defined. Rework this if
that stops being a safe assumption.
"""
name_from_event = event["repository"]["full_name"]
# build the URL manually since it doesn't come back from the API in
# the form that we need
# see https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-entity_repository
# and click on 'Repository property' underneath the table for example data
# (all entries are from the `api` subdomain, rather than bitbucket.org)
url_from_event = f"https://bitbucket.org/{name_from_event}"
if (
repo.name != name_from_event
or repo.config.get("name") != name_from_event
or repo.url != url_from_event
):
repo.update(
name=name_from_event,
url=url_from_event,
config=dict(repo.config, name=name_from_event),
)
|
BitbucketWebhook
|
python
|
walkccc__LeetCode
|
solutions/1776. Car Fleet II/1776.py
|
{
"start": 0,
"end": 817
}
|
class ____:
def getCollisionTimes(self, cars: list[list[int]]) -> list[float]:
ans = []
stack = [] # (pos, speed, collisionTime)
def getCollisionTime(
car: tuple[int, int, int],
pos: int, speed: int) -> float:
return (car[0] - pos) / (speed - car[1])
for pos, speed in reversed(cars):
while stack and (
speed <= stack[-1][1] or getCollisionTime(stack[-1],
pos, speed) >=
stack[-1][2]):
stack.pop()
if stack:
collisionTime = getCollisionTime(stack[-1], pos, speed)
stack.append((pos, speed, collisionTime))
ans.append(collisionTime)
else:
stack.append((pos, speed, math.inf))
ans.append(-1)
return ans[::-1]
|
Solution
|
python
|
GoogleCloudPlatform__python-docs-samples
|
healthcare/api-client/v1beta1/fhir/fhir_resources_test.py
|
{
"start": 1265,
"end": 9498
}
|
class ____(Exception):
"""Operation is not yet complete"""
@retry.Retry(predicate=retry.if_exception_type(OperationNotComplete))
def wait_for_operation(operation_name: str):
operation = (
client.projects()
.locations()
.datasets()
.operations()
.get(name=operation_name)
.execute()
)
if not operation.get("done", False):
raise OperationNotComplete(operation)
@pytest.fixture(scope="module")
def test_dataset():
operation = fhir_stores.create_dataset(
service_account_json, project_id, cloud_region, dataset_id
)
# Wait for the dataset to be created
wait_for_operation(operation["name"])
yield
# Clean up
fhir_stores.delete_dataset(
service_account_json, project_id, cloud_region, dataset_id
)
@pytest.fixture(scope="module")
def test_fhir_store():
fhir_store = fhir_stores.create_fhir_store(
service_account_json, project_id, cloud_region, dataset_id, fhir_store_id
)
yield fhir_store
# Clean up
fhir_stores.delete_fhir_store(
service_account_json, project_id, cloud_region, dataset_id, fhir_store_id
)
# Fixture that creates/deletes a Patient resource for various tests.
@pytest.fixture(scope="module")
def test_patient():
patient_response = fhir_resources.create_patient(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
)
patient_resource_id = patient_response.json()["id"]
yield patient_resource_id
# Clean up
fhir_resources.delete_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
resource_type,
patient_resource_id,
)
def test_create_patient(test_dataset, test_fhir_store, capsys):
fhir_resources.create_patient(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
)
out, _ = capsys.readouterr()
print(out)
assert "Created Patient" in out
@pytest.mark.skip(reason="flaky test sometimes returns 403 errors, need to investigate")
def test_conditional_patch_resource(
test_dataset, test_fhir_store, test_patient, capsys
):
# The conditional method tests use an Observation, so we have to create an
# Encounter from test_patient and then create an Observation from the
# Encounter.
encounter_response = fhir_resources.create_encounter(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
)
encounter_resource_id = encounter_response.json()["id"]
observation_response = fhir_resources.create_observation(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
encounter_resource_id,
)
observation_resource_id = observation_response.json()["id"]
fhir_resources.conditional_patch_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
)
# In accordance with the FHIR spec, if conditional patch or conditional update
# can only be applied to one resource at a time. If the search criteria
# identify more than one match, the request returns a 412 Precondition Failed
# error. Every time the tests create an Observation resource, the resource is
# identical, therefore you have to delete each Observation after it's created
# or else conditional patch/update will detect more than one Observation
# that matches.
fhir_resources.delete_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
"Observation",
observation_resource_id,
)
out, _ = capsys.readouterr()
print(out)
assert "Conditionally patched" in out
@pytest.mark.skip(reason="flaky test sometimes returns 412 errors, need to investigate")
def test_conditional_update_resource(
test_dataset, test_fhir_store, test_patient, capsys
):
# The conditional method tests use an Observation, so we have to create an
# Encounter from test_patient and then create an Observation from the
# Encounter.
encounter_response = fhir_resources.create_encounter(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
)
encounter_resource_id = encounter_response.json()["id"]
observation_response = fhir_resources.create_observation(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
encounter_resource_id,
)
observation_resource_id = observation_response.json()["id"]
fhir_resources.conditional_update_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
encounter_resource_id,
)
# In accordance with the FHIR spec, if conditional patch or conditional update
# can only be applied to one resource at a time. If the search criteria
# identify more than one match, the request returns a 412 Precondition Failed
# error. Every time the tests create an Observation resource, the resource is
# identical, therefore you have to delete each Observation after it's created
# or else conditional patch/update will detect more than one Observation
# that matches.
fhir_resources.delete_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
"Observation",
observation_resource_id,
)
out, _ = capsys.readouterr()
assert "Conditionally updated" in out
def test_conditional_delete_resource(
test_dataset, test_fhir_store, test_patient, capsys
):
# The conditional method tests use an Observation, so we have to create an
# Encounter from test_patient and then create an Observation from the
# Encounter.
@backoff.on_exception(
backoff.expo, HTTPError, max_time=BACKOFF_MAX_TIME, giveup=fatal_code
)
def create_encounter():
encounter_response = fhir_resources.create_encounter(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
)
return encounter_response.json()["id"]
encounter_resource_id = create_encounter()
@backoff.on_exception(
backoff.expo, HTTPError, max_time=BACKOFF_MAX_TIME, giveup=fatal_code
)
def create_observation():
fhir_resources.create_observation(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
test_patient,
encounter_resource_id,
)
create_observation()
@backoff.on_exception(
backoff.expo, HTTPError, max_time=BACKOFF_MAX_TIME, giveup=fatal_code
)
def conditional_delete_resource():
fhir_resources.conditional_delete_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
)
conditional_delete_resource()
out, _ = capsys.readouterr()
print(out)
assert "Conditionally deleted" in out
def test_delete_patient(test_dataset, test_fhir_store, test_patient, capsys):
fhir_resources.delete_resource(
service_account_json,
base_url,
project_id,
cloud_region,
dataset_id,
fhir_store_id,
resource_type,
test_patient,
)
out, _ = capsys.readouterr()
print(out)
assert "Deleted Patient resource" in out
|
OperationNotComplete
|
python
|
walkccc__LeetCode
|
solutions/263. Ugly Number/263.py
|
{
"start": 0,
"end": 180
}
|
class ____:
def isUgly(self, n: int) -> bool:
if n == 0:
return False
for prime in 2, 3, 5:
while n % prime == 0:
n //= prime
return n == 1
|
Solution
|
python
|
getsentry__sentry
|
src/sentry/integrations/types.py
|
{
"start": 637,
"end": 1061
}
|
class ____(StrEnum):
SLACK = "slack"
DISCORD = "discord"
MSTEAMS = "msteams"
JIRA = "jira"
JIRA_SERVER = "jira_server"
AZURE_DEVOPS = "vsts"
GITHUB = "github"
GITHUB_ENTERPRISE = "github_enterprise"
GITLAB = "gitlab"
BITBUCKET = "bitbucket"
BITBUCKET_SERVER = "bitbucket_server"
PAGERDUTY = "pagerduty"
OPSGENIE = "opsgenie"
PERFORCE = "perforce"
|
IntegrationProviderSlug
|
python
|
chroma-core__chroma
|
chromadb/execution/expression/operator.py
|
{
"start": 35973,
"end": 36198
}
|
class ____(Rank):
"""Subtraction of two ranks"""
left: Rank
right: Rank
def to_dict(self) -> Dict[str, Any]:
return {"$sub": {"left": self.left.to_dict(), "right": self.right.to_dict()}}
@dataclass
|
Sub
|
python
|
lepture__authlib
|
authlib/oauth2/rfc6749/errors.py
|
{
"start": 4987,
"end": 5307
}
|
class ____(OAuth2Error):
"""The requested scope is invalid, unknown, malformed, or
exceeds the scope granted by the resource owner.
https://tools.ietf.org/html/rfc6749#section-5.2
"""
error = "invalid_scope"
description = "The requested scope is invalid, unknown, or malformed."
|
InvalidScopeError
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/definitions/partitions/definition/time_window.py
|
{
"start": 1901,
"end": 47507
}
|
class ____(PartitionsDefinition, IHaveNew):
r"""A set of partitions where each partition corresponds to a time window.
The provided cron_schedule determines the bounds of the time windows. E.g. a cron_schedule of
"0 0 \\* \\* \\*" will result in daily partitions that start at midnight and end at midnight of the
following day.
The string partition_key associated with each partition corresponds to the start of the
partition's time window.
The first partition in the set will start on at the first cron_schedule tick that is equal to
or after the given start datetime. The last partition in the set will end before the current
time, unless the end_offset argument is set to a positive number.
We recommended limiting partition counts for each asset to 100,000 partitions or fewer.
Args:
cron_schedule (str): Determines the bounds of the time windows.
start (datetime): The first partition in the set will start on at the first cron_schedule
tick that is equal to or after this value.
timezone (Optional[str]): The timezone in which each time should exist.
Supported strings for timezones are the ones provided by the
`IANA time zone database <https://www.iana.org/time-zones>`_ - e.g. "America/Los_Angeles".
end (datetime): The last partition (excluding) in the set.
fmt (str): The date format to use for partition_keys. Note that if a non-UTC timezone is
used, and the cron schedule repeats every hour or faster, the date format must include
a timezone offset to disambiguate between multiple instances of the same time before and
after the Fall DST transition. If the format does not contain this offset, the second
instance of the ambiguous time partition key will have the UTC offset automatically
appended to it.
end_offset (int): Extends the partition set by a number of partitions equal to the value
passed. If end_offset is 0 (the default), the last partition ends before the current
time. If end_offset is 1, the second-to-last partition ends before the current time,
and so on.
exclusions (Optional[Sequence[Union[str, datetime]]]): Specifies a sequence of cron strings
or datetime objects that should be excluded from the partition set. Every tick of the
cron schedule that matches an excluded datetime or matches the tick of an excluded
cron string will be excluded from the partition set.
"""
start_ts: TimestampWithTimezone
timezone: PublicAttr[str]
end_ts: Optional[TimestampWithTimezone]
fmt: PublicAttr[str]
end_offset: PublicAttr[int]
cron_schedule: PublicAttr[str]
exclusions: PublicAttr[Optional[Sequence[Union[str, TimestampWithTimezone]]]]
def __new__(
cls,
start: Union[datetime, str, TimestampWithTimezone],
fmt: str,
end: Union[datetime, str, TimestampWithTimezone, None] = None,
schedule_type: Optional[ScheduleType] = None,
timezone: Optional[str] = None,
end_offset: int = 0,
minute_offset: Optional[int] = None,
hour_offset: Optional[int] = None,
day_offset: Optional[int] = None,
cron_schedule: Optional[str] = None,
exclusions: Optional[Sequence[Union[str, datetime, TimestampWithTimezone]]] = None,
):
check.opt_str_param(timezone, "timezone")
timezone = timezone or "UTC"
if isinstance(start, str):
start_dt = dst_safe_strptime(start, timezone, fmt)
start = TimestampWithTimezone(start_dt.timestamp(), timezone)
elif isinstance(start, datetime):
start_dt = start.replace(tzinfo=get_timezone(timezone))
start = TimestampWithTimezone(start_dt.timestamp(), timezone)
if not end:
end = None
elif isinstance(end, str):
end_dt = dst_safe_strptime(end, timezone, fmt)
end = TimestampWithTimezone(end_dt.timestamp(), timezone)
elif isinstance(end, datetime):
end_dt = end.replace(tzinfo=get_timezone(timezone))
end = TimestampWithTimezone(end_dt.timestamp(), timezone)
if cron_schedule is not None:
check.invariant(
schedule_type is None and not minute_offset and not hour_offset and not day_offset,
"If cron_schedule argument is provided, then schedule_type, minute_offset, "
"hour_offset, and day_offset can't also be provided",
)
else:
if schedule_type is None:
check.failed("One of schedule_type and cron_schedule must be provided")
cron_schedule = cron_schedule_from_schedule_type_and_offsets(
schedule_type=schedule_type,
minute_offset=minute_offset or 0,
hour_offset=hour_offset or 0,
day_offset=day_offset or None,
)
if not is_valid_cron_schedule(cron_schedule):
raise DagsterInvalidDefinitionError(
f"Found invalid cron schedule '{cron_schedule}' for a"
" TimeWindowPartitionsDefinition."
)
cleaned_exclusions: Optional[Sequence[Union[str, TimestampWithTimezone]]] = None
if exclusions:
check.sequence_param(
exclusions,
"exclusions",
of_type=(str, datetime, TimestampWithTimezone),
)
cron_exclusions = [cs for cs in exclusions if isinstance(cs, str)]
invalid_exclusions = [cs for cs in cron_exclusions if not is_valid_cron_schedule(cs)]
if invalid_exclusions:
quoted_exclusions = [f"'{excl}'" for excl in invalid_exclusions]
invalid_exclusion_str = ", ".join(quoted_exclusions)
raise DagsterInvalidDefinitionError(
f"Found invalid cron schedule(s) {invalid_exclusion_str} in the exclusions"
" argument for a TimeWindowPartitionsDefinition. Expected a set of valid cron"
" strings and datetime objects."
)
cleaned_exclusions = []
for exclusion_part in exclusions:
if isinstance(exclusion_part, datetime):
dt = exclusion_part.replace(tzinfo=get_timezone(timezone))
cleaned_exclusions.append(TimestampWithTimezone(dt.timestamp(), timezone))
else:
cleaned_exclusions.append(exclusion_part)
return super().__new__(
cls,
start_ts=start,
timezone=timezone,
end_ts=end,
fmt=fmt,
end_offset=end_offset,
cron_schedule=cron_schedule,
exclusions=cleaned_exclusions if cleaned_exclusions else None,
)
@property
def start_timestamp(self) -> float:
return self.start_ts.timestamp
@property
def end_timestamp(self) -> Optional[float]:
return self.end_ts.timestamp if self.end_ts else None
@public
@cached_property
def start(self) -> datetime:
start_timestamp_with_timezone = self.start_ts
return datetime_from_timestamp(
start_timestamp_with_timezone.timestamp, start_timestamp_with_timezone.timezone
)
@public
@cached_property
def end(self) -> Optional[datetime]:
end_timestamp_with_timezone = self.end_ts
if not end_timestamp_with_timezone:
return None
return datetime.fromtimestamp(
end_timestamp_with_timezone.timestamp,
get_timezone(end_timestamp_with_timezone.timezone),
)
def _get_current_timestamp(self) -> float:
with partition_loading_context() as ctx:
current_time = ctx.effective_dt
# if a naive current time was passed in, assume it was the same timezone as the partition set
if not current_time.tzinfo:
current_time = current_time.replace(tzinfo=get_timezone(self.timezone))
return current_time.timestamp()
def get_num_partitions_in_window(self, time_window: TimeWindow) -> int:
if time_window.start.timestamp() >= time_window.end.timestamp():
return 0
if self.is_basic_daily:
return (
date(
time_window.end.year,
time_window.end.month,
time_window.end.day,
)
- date(
time_window.start.year,
time_window.start.month,
time_window.start.day,
)
).days
fixed_minute_interval = get_fixed_minute_interval(self.cron_schedule)
if fixed_minute_interval and not self.exclusions:
minutes_in_window = (time_window.end.timestamp() - time_window.start.timestamp()) / 60
return int(minutes_in_window // fixed_minute_interval)
return len(self.get_partition_keys_in_time_window(time_window))
def get_num_partitions(self) -> int:
last_partition_window = self.get_last_partition_window()
first_partition_window = self.get_first_partition_window()
if not last_partition_window or not first_partition_window:
return 0
return self.get_num_partitions_in_window(
TimeWindow(start=first_partition_window.start, end=last_partition_window.end)
)
def get_partition_keys_between_indexes(self, start_idx: int, end_idx: int) -> list[str]:
# Fetches the partition keys between the given start and end indices.
# Start index is inclusive, end index is exclusive.
# Method added for performance reasons, to only string format
# partition keys included within the indices.
current_timestamp = self._get_current_timestamp()
partitions_past_current_time = 0
partition_keys = []
reached_end = False
for idx, time_window in enumerate(self._iterate_time_windows(self.start_timestamp)):
if time_window.end.timestamp() >= current_timestamp:
reached_end = True
if self.end_timestamp is not None and time_window.end.timestamp() > self.end_timestamp:
reached_end = True
if (
time_window.end.timestamp() <= current_timestamp
or partitions_past_current_time < self.end_offset
):
if idx >= start_idx and idx < end_idx:
partition_keys.append(
dst_safe_strftime(
time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
if time_window.end.timestamp() > current_timestamp:
partitions_past_current_time += 1
else:
break
if len(partition_keys) >= end_idx - start_idx:
break
if reached_end and self.end_offset < 0:
partition_keys = partition_keys[: self.end_offset]
return partition_keys
def is_window_start_excluded(self, window_start: datetime):
if not self.exclusions:
return False
start_ts = TimestampWithTimezone(
window_start.replace(tzinfo=get_timezone(self.timezone)).timestamp(), self.timezone
)
if start_ts in self.exclusions:
return True
excluded_cron_strings = [
cron_string for cron_string in self.exclusions if isinstance(cron_string, str)
]
for cron_string in excluded_cron_strings:
if window_start == next(
cron_string_iterator(window_start.timestamp(), cron_string, self.timezone)
):
return True
return False
def get_partition_keys(
self,
current_time: Optional[datetime] = None,
dynamic_partitions_store: Optional["DynamicPartitionsStore"] = None,
) -> Sequence[str]:
with partition_loading_context(current_time, dynamic_partitions_store):
current_timestamp = self._get_current_timestamp()
last_partition_window = self._get_last_partition_window(current_timestamp)
if not last_partition_window:
return []
partition_keys = []
for time_window in self._iterate_time_windows(self.start_timestamp):
partition_keys.append(
dst_safe_strftime(
time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
if time_window.start.timestamp() >= last_partition_window.start.timestamp():
break
return partition_keys
def get_paginated_partition_keys(
self,
context: PartitionLoadingContext,
limit: int,
ascending: bool,
cursor: Optional[str] = None,
) -> PaginatedResults[str]:
with partition_loading_context(new_ctx=context):
current_timestamp = self._get_current_timestamp()
if cursor:
time_window_cursor = TimeWindowCursor.from_cursor(cursor)
start_timestamp = time_window_cursor.start_timestamp
end_timestamp = time_window_cursor.end_timestamp
offset_partitions_count = time_window_cursor.offset_partition_count
else:
start_timestamp = self.start_timestamp
end_timestamp = current_timestamp
offset_partitions_count = 0
partition_keys: list[str] = []
has_more = False
if not ascending:
offset_time_windows = []
if self.end_offset > 0 and self.end_offset > offset_partitions_count:
last_no_offset_time_window = next(
iter(self._reverse_iterate_time_windows(end_timestamp)), None
)
lookforward_time = (
last_no_offset_time_window.end.timestamp()
if last_no_offset_time_window
else end_timestamp
)
for time_window in self._iterate_time_windows(lookforward_time):
if (
self.end_timestamp is not None
and time_window.end.timestamp() > self.end_timestamp
):
break
if len(offset_time_windows) >= self.end_offset - offset_partitions_count:
break
if not self.is_window_start_excluded(time_window.start):
offset_time_windows.append(
dst_safe_strftime(
time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
partition_keys = list(reversed(offset_time_windows))[:limit]
offset_partitions_count += len(partition_keys)
for time_window in self._reverse_iterate_time_windows(end_timestamp):
if len(partition_keys) >= limit - min(0, self.end_offset):
has_more = True
break
if time_window.start.timestamp() < start_timestamp:
break
partition_keys.append(
dst_safe_strftime(
time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
if self.end_offset < 0 and not cursor:
# only subset if we did not have a cursor... if we did have a cursor, we've already
# applied the offset to the end, since we're moving backwards from the end
partition_keys = partition_keys[-1 * min(0, self.end_offset) :]
else:
for time_window in self._iterate_time_windows(start_timestamp):
if (
self.end_timestamp is not None
and time_window.end.timestamp() > self.end_timestamp
):
break
if (
time_window.end.timestamp() <= end_timestamp
or offset_partitions_count < self.end_offset
):
partition_keys.append(
dst_safe_strftime(
time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
if time_window.end.timestamp() > end_timestamp:
offset_partitions_count += 1
if len(partition_keys) >= limit - min(0, self.end_offset):
has_more = True
break
else:
break
if has_more:
# exited due to limit; subset in case we overshot (if end_offset < 0)
partition_keys = partition_keys[:limit]
elif self.end_offset < 0:
# only subset if we did not eject early due to the limit
partition_keys = partition_keys[: self.end_offset]
if not partition_keys:
next_cursor = TimeWindowCursor(
start_timestamp=int(start_timestamp),
end_timestamp=int(end_timestamp),
offset_partition_count=offset_partitions_count,
)
elif ascending:
last_partition_key = partition_keys[-1]
last_time_window = self.time_window_for_partition_key(last_partition_key)
next_cursor = TimeWindowCursor(
start_timestamp=int(last_time_window.end.timestamp()),
end_timestamp=int(end_timestamp),
offset_partition_count=offset_partitions_count,
)
else:
last_partition_key = partition_keys[-1]
last_time_window = self.time_window_for_partition_key(last_partition_key)
next_cursor = TimeWindowCursor(
start_timestamp=int(start_timestamp),
end_timestamp=int(end_timestamp)
if self.end_offset > 0 and offset_partitions_count < self.end_offset
else int(last_time_window.start.timestamp()),
offset_partition_count=offset_partitions_count,
)
return PaginatedResults(
results=partition_keys,
cursor=str(next_cursor),
has_more=has_more,
)
def __str__(self) -> str:
schedule_str = (
self.schedule_type.value.capitalize() if self.schedule_type else self.cron_schedule
)
partition_def_str = f"{schedule_str}, starting {dst_safe_strftime(self.start, self.timezone, self.fmt, self.cron_schedule)} {self.timezone}."
if self.end_offset != 0:
partition_def_str += (
" End offsetted by"
f" {self.end_offset} partition{'' if self.end_offset == 1 else 's'}."
)
return partition_def_str
def __repr__(self):
# Between python 3.8 and 3.9 the repr of a datetime object changed.
# Replaces start time with timestamp as a workaround to make sure the repr is consistent across versions.
# Make sure to update this __repr__ if any new fields are added to TimeWindowPartitionsDefinition.
exclusions_str = f", exclusions={self.exclusions}" if self.exclusions else ""
return (
f"TimeWindowPartitionsDefinition(start={self.start_timestamp},"
f" end={self.end_timestamp if self.end_timestamp is not None else None},"
f" timezone='{self.timezone}', fmt='{self.fmt}', end_offset={self.end_offset},"
f" cron_schedule='{self.cron_schedule}')"
) + exclusions_str
def __hash__(self):
return hash(tuple(self.__repr__()))
@functools.lru_cache(maxsize=100)
def time_window_for_partition_key(self, partition_key: str) -> TimeWindow:
partition_key_dt = dst_safe_strptime(partition_key, self.timezone, self.fmt)
return next(iter(self._iterate_time_windows(partition_key_dt.timestamp())))
@functools.lru_cache(maxsize=5)
def time_windows_for_partition_keys(
self, partition_keys: frozenset[str], validate: bool = True
) -> Sequence[TimeWindow]:
if len(partition_keys) == 0:
return []
sorted_pks = sorted(
partition_keys,
key=lambda pk: dst_safe_strptime(pk, self.timezone, self.fmt).timestamp(),
)
cur_windows_iterator = iter(
self._iterate_time_windows(
dst_safe_strptime(sorted_pks[0], self.timezone, self.fmt).timestamp()
)
)
partition_key_time_windows: list[TimeWindow] = []
for partition_key in sorted_pks:
next_window = next(cur_windows_iterator)
if (
dst_safe_strftime(next_window.start, self.timezone, self.fmt, self.cron_schedule)
== partition_key
):
partition_key_time_windows.append(next_window)
else:
cur_windows_iterator = iter(
self._iterate_time_windows(
dst_safe_strptime(partition_key, self.timezone, self.fmt).timestamp()
)
)
partition_key_time_windows.append(next(cur_windows_iterator))
if validate:
start_time_window = self.get_first_partition_window()
end_time_window = self.get_last_partition_window()
if start_time_window is None or end_time_window is None:
check.failed("No partitions in the PartitionsDefinition")
start_timestamp = start_time_window.start.timestamp()
end_timestamp = end_time_window.end.timestamp()
partition_key_time_windows = [
tw
for tw in partition_key_time_windows
if tw.start.timestamp() >= start_timestamp and tw.end.timestamp() <= end_timestamp
]
return partition_key_time_windows
def start_time_for_partition_key(self, partition_key: str) -> datetime:
partition_key_dt = dst_safe_strptime(partition_key, self.timezone, self.fmt)
if self.is_basic_hourly or self.is_basic_daily:
return partition_key_dt
# the datetime format might not include granular components, so we need to recover them,
# e.g. if cron_schedule="0 7 * * *" and fmt="%Y-%m-%d".
# we make the assumption that the parsed partition key is <= the start datetime.
return next(iter(self._iterate_time_windows(partition_key_dt.timestamp()))).start
def get_next_partition_key(self, partition_key: str) -> Optional[str]:
last_partition_window = self.get_last_partition_window()
if last_partition_window is None:
return None
partition_key_dt = dst_safe_strptime(partition_key, self.timezone, self.fmt)
windows_iter = iter(self._iterate_time_windows(partition_key_dt.timestamp()))
next(windows_iter)
start_time = next(windows_iter).start
if start_time.timestamp() >= last_partition_window.end.timestamp():
return None
else:
return dst_safe_strftime(start_time, self.timezone, self.fmt, self.cron_schedule)
def get_next_partition_window(
self, end_dt: datetime, respect_bounds: bool = True
) -> Optional[TimeWindow]:
windows_iter = iter(self._iterate_time_windows(end_dt.timestamp()))
next_window = next(windows_iter)
if respect_bounds:
last_partition_window = self.get_last_partition_window()
if last_partition_window is None:
return None
if next_window.start.timestamp() >= last_partition_window.end.timestamp():
return None
return next_window
def get_prev_partition_window(
self, start_dt: datetime, respect_bounds: bool = True
) -> Optional[TimeWindow]:
windows_iter = iter(self._reverse_iterate_time_windows(start_dt.timestamp()))
prev_window = next(windows_iter)
if respect_bounds:
first_partition_window = self.get_first_partition_window()
if (
first_partition_window is None
or prev_window.start.timestamp() < first_partition_window.start.timestamp()
):
return None
return prev_window
@functools.lru_cache(maxsize=256)
def _get_first_partition_window(self, current_timestamp: float) -> Optional[TimeWindow]:
time_window = next(iter(self._iterate_time_windows(self.start_timestamp)))
if self.end_timestamp is not None and self.end_timestamp <= self.start_timestamp:
return None
if self.end_offset == 0:
return time_window if time_window.end.timestamp() <= current_timestamp else None
elif self.end_offset > 0:
iterator = iter(self._iterate_time_windows(current_timestamp))
# first returned time window is time window of current time
curr_window_plus_offset = next(iterator)
for _ in range(self.end_offset):
curr_window_plus_offset = next(iterator)
return (
time_window
if time_window.end.timestamp() <= curr_window_plus_offset.start.timestamp()
else None
)
else:
# end offset < 0
end_window = None
iterator = iter(self._reverse_iterate_time_windows(current_timestamp))
for _ in range(abs(self.end_offset)):
end_window = next(iterator)
if end_window is None:
check.failed("end_window should not be None")
return (
time_window if time_window.end.timestamp() <= end_window.start.timestamp() else None
)
def get_first_partition_window(self) -> Optional[TimeWindow]:
return self._get_first_partition_window(self._get_current_timestamp())
@functools.lru_cache(maxsize=256)
def _get_last_partition_window(
self, current_timestamp: float, ignore_exclusions: bool = False
) -> Optional[TimeWindow]:
first_window = self.get_first_partition_window()
if first_window is None:
return None
if self.end_offset == 0:
if self.end_timestamp is not None and self.end_timestamp < current_timestamp:
current_timestamp = self.end_timestamp
return next(
iter(
self._reverse_iterate_time_windows(
current_timestamp, ignore_exclusions=ignore_exclusions
)
)
)
last_window_before_end_timestamp = None
current_timestamp_window = None
if self.end_timestamp is not None:
last_window_before_end_timestamp = next(
iter(
self._reverse_iterate_time_windows(
self.end_timestamp, ignore_exclusions=ignore_exclusions
)
)
)
current_timestamp_iter = iter(
self._reverse_iterate_time_windows(
current_timestamp, ignore_exclusions=ignore_exclusions
)
)
# first returned time window is the last window <= the current timestamp
end_offset_zero_window = next(current_timestamp_iter)
if self.end_offset < 0:
for _ in range(abs(self.end_offset)):
current_timestamp_window = next(current_timestamp_iter)
else:
current_timestamp_iter = iter(
self._iterate_time_windows(
end_offset_zero_window.end.timestamp(), ignore_exclusions=ignore_exclusions
)
)
for _ in range(self.end_offset):
current_timestamp_window = next(current_timestamp_iter)
current_timestamp_window = check.not_none(
current_timestamp_window,
"current_timestamp_window should not be None if end_offset != 0",
)
if (
last_window_before_end_timestamp
and last_window_before_end_timestamp.start.timestamp()
<= current_timestamp_window.start.timestamp()
):
return last_window_before_end_timestamp
elif current_timestamp_window.start.timestamp() < first_window.start.timestamp():
return first_window
else:
return current_timestamp_window
def get_last_partition_window(self) -> Optional[TimeWindow]:
return self._get_last_partition_window(
self._get_current_timestamp(), ignore_exclusions=False
)
def get_last_partition_window_ignoring_exclusions(self) -> Optional[TimeWindow]:
return self._get_last_partition_window(
self._get_current_timestamp(), ignore_exclusions=True
)
def get_first_partition_key(self) -> Optional[str]:
first_window = self.get_first_partition_window()
if first_window is None:
return None
return dst_safe_strftime(first_window.start, self.timezone, self.fmt, self.cron_schedule)
def get_last_partition_key(self) -> Optional[str]:
last_window = self.get_last_partition_window()
if last_window is None:
return None
return dst_safe_strftime(last_window.start, self.timezone, self.fmt, self.cron_schedule)
def end_time_for_partition_key(self, partition_key: str) -> datetime:
return self.time_window_for_partition_key(partition_key).end
@functools.lru_cache(maxsize=5)
def get_partition_keys_in_time_window(self, time_window: TimeWindow) -> Sequence[str]:
result: list[str] = []
time_window_end_timestamp = time_window.end.timestamp()
for partition_time_window in self._iterate_time_windows(time_window.start.timestamp()):
if partition_time_window.start.timestamp() < time_window_end_timestamp:
result.append(
dst_safe_strftime(
partition_time_window.start, self.timezone, self.fmt, self.cron_schedule
)
)
else:
break
return result
def get_partition_subset_in_time_window(
self, time_window: TimeWindow
) -> "TimeWindowPartitionsSubset":
return self.partitions_subset_class(
partitions_def=self, num_partitions=None, included_time_windows=[time_window]
)
def get_partition_key_range_for_time_window(
self, time_window: TimeWindow, respect_bounds: bool = True
) -> PartitionKeyRange:
start_partition_key = self.get_partition_key_for_timestamp(time_window.start.timestamp())
end_partition_key = self.get_partition_key_for_timestamp(
check.not_none(
self.get_prev_partition_window(time_window.end, respect_bounds=respect_bounds)
).start.timestamp()
)
return PartitionKeyRange(start_partition_key, end_partition_key)
def get_partition_keys_in_range(self, partition_key_range: PartitionKeyRange) -> Sequence[str]:
start_time = self.start_time_for_partition_key(partition_key_range.start)
check.invariant(
start_time.timestamp() >= self.start_timestamp,
(
f"Partition key range start {partition_key_range.start} is before "
f"the partitions definition start time {self.start}"
),
)
end_time = self.end_time_for_partition_key(partition_key_range.end)
if self.end_timestamp is not None:
check.invariant(
end_time.timestamp() <= self.end_timestamp,
(
f"Partition key range end {partition_key_range.end} is after the "
f"partitions definition end time {self.end}"
),
)
return self.get_partition_keys_in_time_window(TimeWindow(start_time, end_time))
@public
@property
def schedule_type(self) -> Optional[ScheduleType]:
"""Optional[ScheduleType]: An enum representing the partition cadence (hourly, daily,
weekly, or monthly).
"""
if re.fullmatch(r"\d+ \* \* \* \*", self.cron_schedule):
return ScheduleType.HOURLY
elif re.fullmatch(r"\d+ \d+ \* \* \*", self.cron_schedule):
return ScheduleType.DAILY
elif re.fullmatch(r"\d+ \d+ \* \* \d+", self.cron_schedule):
return ScheduleType.WEEKLY
elif re.fullmatch(r"\d+ \d+ \d+ \* \*", self.cron_schedule):
return ScheduleType.MONTHLY
else:
return None
@public
@property
def minute_offset(self) -> int:
"""int: Number of minutes past the hour to "split" partitions. Defaults to 0.
For example, returns 15 if each partition starts at 15 minutes past the hour.
"""
match = re.fullmatch(r"(\d+) (\d+|\*) (\d+|\*) (\d+|\*) (\d+|\*)", self.cron_schedule)
if match is None:
check.failed(f"{self.cron_schedule} has no minute offset")
return int(match.groups()[0])
@public
@property
def hour_offset(self) -> int:
"""int: Number of hours past 00:00 to "split" partitions. Defaults to 0.
For example, returns 1 if each partition starts at 01:00.
"""
match = re.fullmatch(r"(\d+|\*) (\d+) (\d+|\*) (\d+|\*) (\d+|\*)", self.cron_schedule)
if match is None:
check.failed(f"{self.cron_schedule} has no hour offset")
return int(match.groups()[1])
@public
@property
def day_offset(self) -> int:
"""int: For a weekly or monthly partitions definition, returns the day to "split" partitions
by. Each partition will start on this day, and end before this day in the following
week/month. Returns 0 if the day_offset parameter is unset in the
WeeklyPartitionsDefinition, MonthlyPartitionsDefinition, or the provided cron schedule.
For weekly partitions, returns a value between 0 (representing Sunday) and 6 (representing
Saturday). Providing a value of 1 means that a partition will exist weekly from Monday to
the following Sunday.
For monthly partitions, returns a value between 0 (the first day of the month) and 31 (the
last possible day of the month).
"""
schedule_type = self.schedule_type
if schedule_type == ScheduleType.WEEKLY:
match = re.fullmatch(r"(\d+|\*) (\d+|\*) (\d+|\*) (\d+|\*) (\d+)", self.cron_schedule)
if match is None:
check.failed(f"{self.cron_schedule} has no day offset")
return int(match.groups()[4])
elif schedule_type == ScheduleType.MONTHLY:
match = re.fullmatch(r"(\d+|\*) (\d+|\*) (\d+) (\d+|\*) (\d+|\*)", self.cron_schedule)
if match is None:
check.failed(f"{self.cron_schedule} has no day offset")
return int(match.groups()[2])
else:
check.failed(f"Unsupported schedule type for day_offset: {schedule_type}")
@public
def get_cron_schedule(
self,
minute_of_hour: Optional[int] = None,
hour_of_day: Optional[int] = None,
day_of_week: Optional[int] = None,
day_of_month: Optional[int] = None,
) -> str:
"""The schedule executes at the cadence specified by the partitioning, but may overwrite
the minute/hour/day offset of the partitioning.
This is useful e.g. if you have partitions that span midnight to midnight but you want to
schedule a job that runs at 2 am.
"""
if (
minute_of_hour is None
and hour_of_day is None
and day_of_week is None
and day_of_month is None
):
return self.cron_schedule
schedule_type = self.schedule_type
if schedule_type is None:
check.failed(
f"{self.cron_schedule} does not support"
" minute_of_hour/hour_of_day/day_of_week/day_of_month arguments"
)
minute_of_hour = cast(
"int",
check.opt_int_param(minute_of_hour, "minute_of_hour", default=self.minute_offset),
)
if schedule_type == ScheduleType.HOURLY:
check.invariant(
hour_of_day is None, "Cannot set hour parameter with hourly partitions."
)
else:
hour_of_day = cast(
"int", check.opt_int_param(hour_of_day, "hour_of_day", default=self.hour_offset)
)
if schedule_type == ScheduleType.DAILY:
check.invariant(
day_of_week is None, "Cannot set day of week parameter with daily partitions."
)
check.invariant(
day_of_month is None, "Cannot set day of month parameter with daily partitions."
)
if schedule_type == ScheduleType.MONTHLY:
default = self.day_offset or 1
day_offset = check.opt_int_param(day_of_month, "day_of_month", default=default)
elif schedule_type == ScheduleType.WEEKLY:
default = self.day_offset or 0
day_offset = check.opt_int_param(day_of_week, "day_of_week", default=default)
else:
day_offset = 0
return cron_schedule_from_schedule_type_and_offsets(
schedule_type,
minute_offset=minute_of_hour,
hour_offset=hour_of_day or 0,
day_offset=day_offset,
)
def _iterate_time_windows(
self, start_timestamp: float, ignore_exclusions: bool = False
) -> Iterable[TimeWindow]:
"""Returns an infinite generator of time windows that start >= the given start time."""
iterator = cron_string_iterator(
start_timestamp=start_timestamp,
cron_string=self.cron_schedule,
execution_timezone=self.timezone,
)
curr_time = next(iterator)
while curr_time.timestamp() < start_timestamp:
curr_time = next(iterator)
while True:
next_time = next(iterator)
if not self.is_window_start_excluded(curr_time) or ignore_exclusions:
yield TimeWindow(curr_time, next_time)
curr_time = next_time
def _reverse_iterate_time_windows(
self, end_timestamp: float, ignore_exclusions: bool = False
) -> Iterable[TimeWindow]:
"""Returns an infinite generator of time windows that end before the given end timestamp.
For example, if you pass in any time on day N (including midnight) for a daily partition
with offset 0 bounded at midnight, the first element this iterator will return is
[day N-1, day N).
If ignore_exclusions is True, excluded windows will be included in the iteration. This is
useful for checking for skipping excluded windows when calculating a schedule off of the
time window partitions definition
"""
iterator = reverse_cron_string_iterator(
end_timestamp=end_timestamp,
cron_string=self.cron_schedule,
execution_timezone=self.timezone,
)
curr_time = next(iterator)
while curr_time.timestamp() > end_timestamp:
curr_time = next(iterator)
while True:
prev_time = next(iterator)
if not self.is_window_start_excluded(prev_time) or ignore_exclusions:
yield TimeWindow(prev_time, curr_time)
curr_time = prev_time
def get_partition_key_for_timestamp(self, timestamp: float, end_closed: bool = False) -> str:
"""Args:
timestamp (float): Timestamp from the unix epoch, UTC.
end_closed (bool): Whether the interval is closed at the end or at the beginning.
"""
rev_iter = reverse_cron_string_iterator(timestamp, self.cron_schedule, self.timezone)
prev_partition_key = None
while prev_partition_key is None:
prev_dt = next(rev_iter)
if end_closed and prev_dt.timestamp() == timestamp:
continue
if self.is_window_start_excluded(prev_dt):
continue
prev_partition_key = dst_safe_strftime(
prev_dt, self.timezone, self.fmt, self.cron_schedule
)
iterator = cron_string_iterator(timestamp, self.cron_schedule, self.timezone)
next_partition_key = None
next_dt = None
while next_partition_key is None:
next_dt = next(iterator)
if self.is_window_start_excluded(next_dt):
continue
next_partition_key = dst_safe_strftime(
next_dt, self.timezone, self.fmt, self.cron_schedule
)
if end_closed or (next_dt and next_dt.timestamp() > timestamp):
return prev_partition_key
else:
return next_partition_key
def less_than(self, partition_key1: str, partition_key2: str) -> bool:
"""Returns true if the partition_key1 is earlier than partition_key2."""
return (
self.start_time_for_partition_key(partition_key1).timestamp()
< self.start_time_for_partition_key(partition_key2).timestamp()
)
@property
def partitions_subset_class(self) -> type["TimeWindowPartitionsSubset"]:
from dagster._core.definitions.partitions.subset.time_window import (
TimeWindowPartitionsSubset,
)
return TimeWindowPartitionsSubset
def subset_with_all_partitions(self) -> "PartitionsSubset":
first_window = self.get_first_partition_window()
last_window = self.get_last_partition_window()
windows = (
[]
if first_window is None or last_window is None
else [TimeWindow(first_window.start, last_window.end)]
)
return self.partitions_subset_class(
partitions_def=self, num_partitions=None, included_time_windows=windows
)
def get_serializable_unique_identifier(
self, dynamic_partitions_store: Optional["DynamicPartitionsStore"] = None
) -> str:
return hashlib.sha1(self.__repr__().encode("utf-8")).hexdigest()
def has_partition_key(self, partition_key: str) -> bool:
"""Returns a boolean representing if the given partition key is valid."""
try:
partition_start_time = self.start_time_for_partition_key(partition_key)
partition_start_timestamp = partition_start_time.timestamp()
except ValueError:
# unparseable partition key
return False
if self.is_window_start_excluded(partition_start_time):
return False
first_partition_window = self.get_first_partition_window()
last_partition_window = self.get_last_partition_window()
return not (
# no partitions at all
first_partition_window is None
or last_partition_window is None
# partition starts before the first valid partition
or partition_start_timestamp < first_partition_window.start.timestamp()
# partition starts after the last valid partition
or partition_start_timestamp > last_partition_window.start.timestamp()
# partition key string does not represent the start of an actual partition
or dst_safe_strftime(partition_start_time, self.timezone, self.fmt, self.cron_schedule)
!= partition_key
)
def equal_except_for_start_or_end(self, other: "TimeWindowPartitionsDefinition") -> bool:
"""Returns True iff this is identical to other, except they're allowed to have different
start and end datetimes.
"""
return (
self.timezone == other.timezone
and self.fmt == other.fmt
and self.cron_schedule == other.cron_schedule
and self.end_offset == other.end_offset
and self.exclusions == other.exclusions
)
def get_partition_key(self, key: Union[str, date, datetime]) -> str:
if isinstance(key, date) or isinstance(key, datetime):
key = key.strftime(self.fmt)
# now should have str
check.str_param(key, "key")
if not self.has_partition_key(key):
raise ValueError(f"Got invalid partition key {key!r}")
return key
@property
def is_basic_daily(self) -> bool:
return not self.exclusions and is_basic_daily(self.cron_schedule)
@property
def is_basic_hourly(self) -> bool:
return not self.exclusions and is_basic_hourly(self.cron_schedule)
|
TimeWindowPartitionsDefinition
|
python
|
great-expectations__great_expectations
|
tests/core/test_expectation_suite.py
|
{
"start": 7592,
"end": 27423
}
|
class ____:
"""Tests related to the 1.0 CRUD API."""
expectation_suite_name = "test-suite"
@pytest.fixture
def expectation(self) -> gxe.ExpectColumnValuesToBeInSet:
return gxe.ExpectColumnValuesToBeInSet(
column="a",
value_set=[1, 2, 3],
result_format="BASIC",
)
@pytest.mark.unit
def test_instantiate_suite_with_expectations(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
columns = ["a", "b", "c", "d", "e"]
expectations = [expectation.copy(update={"column": column}) for column in columns]
suite = ExpectationSuite(name=self.expectation_suite_name, expectations=expectations)
assert suite.expectations == expectations
@pytest.mark.unit
def test_instantiate_suite_fails_with_expectations_with_ids(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
columns = ["a", "b", "c", "d", "e"]
expectations = [
expectation.copy(update={"column": column, "id": uuid4()}) for column in columns
]
with pytest.raises(
ValueError,
match=r"Expectations in parameter `expectations` must not belong to another ExpectationSuite.", # noqa: E501 # FIXME CoP
):
ExpectationSuite(name=self.expectation_suite_name, expectations=expectations)
@pytest.mark.unit
def test_add_success_with_saved_suite(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
suite = ExpectationSuite(name=self.expectation_suite_name)
created_expectation = suite.add_expectation(expectation=expectation)
assert created_expectation == context.expectations_store.add_expectation.return_value
context.expectations_store.add_expectation.assert_called_once_with(
suite=suite, expectation=expectation
)
@pytest.mark.unit
def test_add_success_with_unsaved_suite(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = False
set_context(project=context)
suite = ExpectationSuite(name=self.expectation_suite_name)
created_expectation = suite.add_expectation(expectation=expectation)
assert created_expectation == expectation
assert len(suite.expectations) == 1
# expect that adding an expectation to this suite doesnt have the side effect of
# persisting the suite to the data context
context.expectations_store.set.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_duplicate_when_expectation_already_exists(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
suite.add_expectation(expectation=expectation)
assert len(suite.expectations) == 1
context.expectations_store.update.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_duplicate_when_expectation_differs_rendered_content(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
dup_expectation = deepcopy(expectation)
dup_expectation.render()
assert expectation.rendered_content != dup_expectation.rendered_content
suite.add_expectation(expectation=dup_expectation)
assert len(suite.expectations) == 1
context.expectations_store.update.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_duplicate_when_expectation_differs_meta(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
dup_expectation = deepcopy(expectation)
dup_expectation.meta = {"author": "Guido van Rossum"}
assert expectation.meta != dup_expectation.meta
suite.add_expectation(expectation=dup_expectation)
assert len(suite.expectations) == 1
context.expectations_store.update.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_duplicate_when_expectation_differs_notes(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
dup_expectation = deepcopy(expectation)
dup_expectation.notes = "These are my notes!"
assert expectation.notes != dup_expectation.notes
suite.add_expectation(expectation=dup_expectation)
assert len(suite.expectations) == 1
context.expectations_store.update.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_duplicate_when_expectation_differs_id(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
suite.expectations[0].id = str(uuid.uuid4())
dup_expectation = deepcopy(expectation)
dup_expectation.id = None
assert expectation.id != dup_expectation.id
suite.add_expectation(expectation=dup_expectation)
assert len(suite.expectations) == 1
context.expectations_store.update.assert_not_called()
@pytest.mark.unit
def test_add_doesnt_mutate_suite_when_save_fails(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.add_expectation.side_effect = (
ConnectionError()
) # arbitrary exception
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name="test-suite",
)
with pytest.raises(ConnectionError): # exception type isn't important
suite.add_expectation(expectation=expectation)
assert len(suite.expectations) == 0, "Expectation must not be added to Suite."
@pytest.mark.unit
def test_add_success_when_attributes_are_identical(self):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
parameters = {"column": "passenger_count"}
expectation_a = ExpectColumnValuesToBeUnique(**parameters)
expectation_b = ExpectColumnValuesToNotBeNull(**parameters)
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation_a],
)
suite.add_expectation(expectation=expectation_b)
assert len(suite.expectations) == 2
@pytest.mark.unit
def test_delete_success_with_saved_suite(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
context.expectations_store.has_key.return_value = True
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
deleted_expectation = suite.delete_expectation(expectation=expectation)
assert deleted_expectation == expectation
assert suite.expectations == []
# expect that the data context is kept in sync with the mutation
context.expectations_store.delete_expectation.assert_called_once_with(
suite=suite, expectation=expectation
)
@pytest.mark.unit
def test_delete_success_with_unsaved_suite(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
context.expectations_store.has_key.return_value = False
suite = ExpectationSuite(
name=self.expectation_suite_name,
expectations=[expectation],
)
deleted_expectation = suite.delete_expectation(expectation=expectation)
assert deleted_expectation == expectation
assert suite.expectations == []
# expect that deleting an expectation from this suite doesnt have the side effect of
# persisting the suite to the data context
context.expectations_store.delete_expectation.assert_not_called()
@pytest.mark.unit
@pytest.mark.parametrize(
"input_kwargs",
[
pytest.param({"id": str(uuid.uuid4())}, id="id"),
pytest.param({"meta": {"author": "Alexandre Dumas"}}, id="meta"),
pytest.param({"notes": "Just some thoughts!"}, id="notes"),
],
)
def test_delete_success_with_equalish_expectation(self, input_kwargs: dict):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
expectation = gxe.ExpectColumnValuesToBeInSet(column="a", value_set=[1, 2, 3])
suite = ExpectationSuite(
name="test-suite",
expectations=[expectation],
)
suite.delete_expectation(
expectation=gxe.ExpectColumnValuesToBeInSet(
column="a", value_set=[1, 2, 3], **input_kwargs
)
)
assert suite.expectations == []
@pytest.mark.unit
def test_delete_fails_when_expectation_is_not_found(self, expectation):
context = Mock(spec=AbstractDataContext)
set_context(project=context)
suite = ExpectationSuite(
name="test-suite",
)
with pytest.raises(KeyError, match=r"No matching expectation was found."):
suite.delete_expectation(expectation=expectation)
context.expectations_store.delete_expectation.assert_not_called()
@pytest.mark.unit
def test_delete_doesnt_mutate_suite_when_save_fails(self, expectation):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
context.expectations_store.delete_expectation.side_effect = (
ConnectionError()
) # arbitrary exception
set_context(project=context)
suite = ExpectationSuite(
name="test-suite",
expectations=[expectation],
)
with pytest.raises(ConnectionError): # exception type isn't important
suite.delete_expectation(expectation=expectation)
assert len(suite.expectations) == 1, "Expectation must still be in Suite."
@pytest.mark.unit
def test_save_success(self):
context = Mock(spec=AbstractDataContext)
context.expectations_store.has_key.return_value = True
set_context(project=context)
suite = ExpectationSuite(
name=self.expectation_suite_name,
)
store_key = context.expectations_store.get_key.return_value
suite.save()
# expect that the data context is kept in sync
context.expectations_store.update.assert_called_once_with(key=store_key, value=suite)
@pytest.mark.unit
def test_save_before_add_raises(self):
gx.get_context(mode="ephemeral")
suite = ExpectationSuite(
name=self.expectation_suite_name,
)
with pytest.raises(gx_exceptions.ExpectationSuiteNotAddedError):
suite.save()
@pytest.mark.filesystem
def test_filesystem_context_update_suite_adds_ids(self, empty_data_context, expectation):
context = empty_data_context
self._test_update_suite_adds_ids(context, expectation)
@pytest.mark.cloud
def test_cloud_context_update_suite_adds_ids(
self,
unset_gx_env_variables: None,
empty_cloud_context_fluent,
expectation,
):
context = empty_cloud_context_fluent
self._test_update_suite_adds_ids(context, expectation)
def _test_update_suite_adds_ids(self, context, expectation):
suite_name = "test-suite"
suite = ExpectationSuite(suite_name)
suite = context.suites.add(suite)
uuid_to_test = suite.id
try:
UUID(uuid_to_test)
except TypeError:
pytest.fail(f"Expected UUID in ExpectationSuite.id, found {uuid_to_test}")
expectation.id = None
suite.add_expectation(expectation)
expectation = copy(expectation)
expectation.column = "foo"
suite.add_expectation(expectation)
assert len(suite.expectations) == 2
for expectation in suite.expectations:
uuid_to_test = expectation.id
try:
UUID(uuid_to_test)
except TypeError:
pytest.fail(f"Expected UUID in ExpectationConfiguration.id, found {uuid_to_test}")
@pytest.mark.unit
def test_suite_add_expectation_doesnt_allow_adding_an_expectation_with_id(self, expectation):
suite = ExpectationSuite("test-suite")
provided_id = "6b3f003d-d97b-4649-ba23-3f4e30986297"
expectation.id = provided_id
with pytest.raises(
RuntimeError,
match=r"Cannot add Expectation because it already belongs to an ExpectationSuite.",
):
suite.add_expectation(expectation)
@pytest.mark.cloud
def test_cloud_expectation_can_be_saved_after_added(
self,
unset_gx_env_variables: None,
empty_cloud_context_fluent,
expectation,
):
context = empty_cloud_context_fluent
self._test_expectation_can_be_saved_after_added(context, expectation)
@pytest.mark.filesystem
def test_filesystem_expectation_can_be_saved_after_added(self, empty_data_context, expectation):
context = empty_data_context
self._test_expectation_can_be_saved_after_added(context, expectation)
def _test_expectation_can_be_saved_after_added(self, context, expectation):
suite_name = "test-suite"
suite = ExpectationSuite(suite_name)
suite = context.suites.add(suite)
suite.add_expectation(expectation)
updated_column_name = "foo"
assert expectation.column != updated_column_name
expectation.column = updated_column_name
expectation.save()
assert suite.expectations[0].column == updated_column_name
suite = context.suites.get(suite_name)
assert len(suite.expectations) == 1
assert suite.expectations[0].column == updated_column_name
@pytest.mark.cloud
def test_cloud_expectation_can_be_saved_after_update(
self,
unset_gx_env_variables: None,
empty_cloud_context_fluent,
expectation,
):
context = empty_cloud_context_fluent
self._test_expectation_can_be_saved_after_update(context, expectation)
@pytest.mark.filesystem
def test_filesystem_expectation_can_be_saved_after_update(
self, empty_data_context, expectation
):
context = empty_data_context
self._test_expectation_can_be_saved_after_update(context, expectation)
def _test_expectation_can_be_saved_after_update(self, context, expectation):
suite_name = "test-suite"
suite = ExpectationSuite(suite_name, expectations=[expectation])
suite = context.suites.add(suite)
expectation = suite.expectations[0]
updated_column_name = "foo"
expectation.column = updated_column_name
expectation.save()
assert suite.expectations[0].column == updated_column_name
suite = context.suites.get(suite_name)
assert len(suite.expectations) == 1
assert suite.expectations[0].column == updated_column_name
@pytest.mark.filesystem
def test_expectation_save_only_persists_single_change(self, empty_data_context):
context = empty_data_context
suite_name = "test-suite"
expectations = [
gxe.ExpectColumnValuesToBeInSet(
column="a",
value_set=[1, 2, 3],
),
gxe.ExpectColumnValuesToBeInSet(
column="b",
value_set=[4, 5, 6],
),
]
suite = ExpectationSuite(
name=suite_name,
expectations=expectations,
)
context.suites.add(suite)
assert suite.expectations[0].column == "a"
assert suite.expectations[1].column == "b"
# Change the column names of both expectations
expectation = suite.expectations[0]
other_expectation = suite.expectations[1]
expectation.column = "c"
other_expectation.column = "d"
# Only persist change made to first expectation
expectation.save()
updated_suite = context.suites.get(name=suite_name)
assert updated_suite.expectations[0].column == "c"
assert updated_suite.expectations[1].column == "b"
@pytest.mark.cloud
def test_expectation_save_callback_can_come_from_any_copy_of_a_suite(
self,
unset_gx_env_variables: None,
empty_cloud_context_fluent,
):
"""Equivalent calls to ExpectationSuite._save_expectation from different copies of a
single ExpectationSuite must produce equivalent side effects.
In some cases, the ExpectationsStore replaces Expectations from a given suite with Expectations
from another copy of the same suite, in order to keep the ExpectationSuite in memory up to date
with the remote ExpectationSuite. ExpectationSuite._save_expectation (and the corresponding logic
the suite uses within the ExpectationsStore) must work equivalently regardless of which Suite instance
it belongs to.
""" # noqa: E501 # FIXME CoP
# Arrange
context = empty_cloud_context_fluent
suite_name = "test-suite"
suite_a = ExpectationSuite(name=suite_name)
column_name = "a"
updated_column_name = "foo"
expectations = [
gxe.ExpectColumnValuesToBeInSet(
column=column_name,
value_set=[1, 2, 3],
),
gxe.ExpectColumnValuesToBeInSet(
column="b",
value_set=[4, 5, 6],
),
]
for expectation in expectations:
suite_a.add_expectation(expectation)
context.suites.add(suite_a)
suite_b = context.suites.get(name=suite_name)
# Act
suite_a.expectations = suite_b.expectations
expectation = suite_a.expectations[0]
# the following assert is the method equivalent of `is`
assert expectation._save_callback == suite_b._save_expectation
assert expectation.column == column_name
expectation.column = updated_column_name
expectation.save()
# Assert
fetched_suite = context.suites.get(name=suite_name)
assert (
suite_a.expectations[0].column
== fetched_suite.expectations[0].column
== updated_column_name
)
@pytest.mark.unit
def test_expectation_suite_name_can_be_updated(self, empty_cloud_context_fluent):
"""Expect that ExpectationSuite.name can be updated directly"""
suite = ExpectationSuite(name=self.expectation_suite_name)
new_name = "updated name"
suite.name = "updated name"
assert suite.name == new_name
|
TestCRUDMethods
|
python
|
mlflow__mlflow
|
examples/paddle/train_high_level_api.py
|
{
"start": 180,
"end": 965
}
|
class ____(paddle.nn.Layer):
def __init__(self):
super().__init__()
self.fc_ = paddle.nn.Linear(13, 1, None)
def forward(self, inputs):
pred = self.fc_(inputs)
return pred
model = paddle.Model(UCIHousing())
optim = paddle.optimizer.Adam(learning_rate=0.01, parameters=model.parameters())
model.prepare(optim, paddle.nn.MSELoss())
model.fit(train_dataset, epochs=6, batch_size=8, verbose=1)
with mlflow.start_run() as run:
mlflow.paddle.log_model(model, name="model")
print(f"Model saved in run {run.info.run_id}")
# load model
model_path = mlflow.get_artifact_uri("model")
pd_model = mlflow.paddle.load_model(model_path)
np_test_data = np.array([x[0] for x in eval_dataset])
print(pd_model(np_test_data))
|
UCIHousing
|
python
|
mwaskom__seaborn
|
tests/_core/test_plot.py
|
{
"start": 49835,
"end": 59087
}
|
class ____:
def check_pair_grid(self, p, x, y):
xys = itertools.product(y, x)
for (y_i, x_j), subplot in zip(xys, p._subplots):
ax = subplot["ax"]
assert ax.get_xlabel() == "" if x_j is None else x_j
assert ax.get_ylabel() == "" if y_i is None else y_i
assert_gridspec_shape(subplot["ax"], len(y), len(x))
@pytest.mark.parametrize("vector_type", [list, pd.Index])
def test_all_numeric(self, long_df, vector_type):
x, y = ["x", "y", "z"], ["s", "f"]
p = Plot(long_df).pair(vector_type(x), vector_type(y)).plot()
self.check_pair_grid(p, x, y)
def test_single_variable_key_raises(self, long_df):
p = Plot(long_df)
err = "You must pass a sequence of variable keys to `y`"
with pytest.raises(TypeError, match=err):
p.pair(x=["x", "y"], y="z")
@pytest.mark.parametrize("dim", ["x", "y"])
def test_single_dimension(self, long_df, dim):
variables = {"x": None, "y": None}
variables[dim] = ["x", "y", "z"]
p = Plot(long_df).pair(**variables).plot()
variables = {k: [v] if v is None else v for k, v in variables.items()}
self.check_pair_grid(p, **variables)
def test_non_cross(self, long_df):
x = ["x", "y"]
y = ["f", "z"]
p = Plot(long_df).pair(x, y, cross=False).plot()
for i, subplot in enumerate(p._subplots):
ax = subplot["ax"]
assert ax.get_xlabel() == x[i]
assert ax.get_ylabel() == y[i]
assert_gridspec_shape(ax, 1, len(x))
root, *other = p._figure.axes
for axis in "xy":
shareset = getattr(root, f"get_shared_{axis}_axes")()
assert not any(shareset.joined(root, ax) for ax in other)
def test_list_of_vectors(self, long_df):
x_vars = ["x", "z"]
p = Plot(long_df, y="y").pair(x=[long_df[x] for x in x_vars]).plot()
assert len(p._figure.axes) == len(x_vars)
for ax, x_i in zip(p._figure.axes, x_vars):
assert ax.get_xlabel() == x_i
def test_with_no_variables(self, long_df):
p = Plot(long_df).pair().plot()
assert len(p._figure.axes) == 1
def test_with_facets(self, long_df):
x = "x"
y = ["y", "z"]
col = "a"
p = Plot(long_df, x=x).facet(col).pair(y=y).plot()
facet_levels = categorical_order(long_df[col])
dims = itertools.product(y, facet_levels)
for (y_i, col_i), subplot in zip(dims, p._subplots):
ax = subplot["ax"]
assert ax.get_xlabel() == x
assert ax.get_ylabel() == y_i
assert ax.get_title() == f"{col_i}"
assert_gridspec_shape(ax, len(y), len(facet_levels))
@pytest.mark.parametrize("variables", [("rows", "y"), ("columns", "x")])
def test_error_on_facet_overlap(self, long_df, variables):
facet_dim, pair_axis = variables
p = Plot(long_df).facet(**{facet_dim[:3]: "a"}).pair(**{pair_axis: ["x", "y"]})
expected = f"Cannot facet the {facet_dim} while pairing on `{pair_axis}`."
with pytest.raises(RuntimeError, match=expected):
p.plot()
@pytest.mark.parametrize("variables", [("columns", "y"), ("rows", "x")])
def test_error_on_wrap_overlap(self, long_df, variables):
facet_dim, pair_axis = variables
p = (
Plot(long_df)
.facet(wrap=2, **{facet_dim[:3]: "a"})
.pair(**{pair_axis: ["x", "y"]})
)
expected = f"Cannot wrap the {facet_dim} while pairing on `{pair_axis}``."
with pytest.raises(RuntimeError, match=expected):
p.plot()
def test_axis_sharing(self, long_df):
p = Plot(long_df).pair(x=["a", "b"], y=["y", "z"])
shape = 2, 2
p1 = p.plot()
axes_matrix = np.reshape(p1._figure.axes, shape)
for root, *other in axes_matrix: # Test row-wise sharing
x_shareset = getattr(root, "get_shared_x_axes")()
assert not any(x_shareset.joined(root, ax) for ax in other)
y_shareset = getattr(root, "get_shared_y_axes")()
assert all(y_shareset.joined(root, ax) for ax in other)
for root, *other in axes_matrix.T: # Test col-wise sharing
x_shareset = getattr(root, "get_shared_x_axes")()
assert all(x_shareset.joined(root, ax) for ax in other)
y_shareset = getattr(root, "get_shared_y_axes")()
assert not any(y_shareset.joined(root, ax) for ax in other)
p2 = p.share(x=False, y=False).plot()
root, *other = p2._figure.axes
for axis in "xy":
shareset = getattr(root, f"get_shared_{axis}_axes")()
assert not any(shareset.joined(root, ax) for ax in other)
def test_axis_sharing_with_facets(self, long_df):
p = Plot(long_df, y="y").pair(x=["a", "b"]).facet(row="c").plot()
shape = 2, 2
axes_matrix = np.reshape(p._figure.axes, shape)
for root, *other in axes_matrix: # Test row-wise sharing
x_shareset = getattr(root, "get_shared_x_axes")()
assert not any(x_shareset.joined(root, ax) for ax in other)
y_shareset = getattr(root, "get_shared_y_axes")()
assert all(y_shareset.joined(root, ax) for ax in other)
for root, *other in axes_matrix.T: # Test col-wise sharing
x_shareset = getattr(root, "get_shared_x_axes")()
assert all(x_shareset.joined(root, ax) for ax in other)
y_shareset = getattr(root, "get_shared_y_axes")()
assert all(y_shareset.joined(root, ax) for ax in other)
def test_x_wrapping(self, long_df):
x_vars = ["f", "x", "y", "z"]
wrap = 3
p = Plot(long_df, y="y").pair(x=x_vars, wrap=wrap).plot()
assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)
assert len(p._figure.axes) == len(x_vars)
for ax, var in zip(p._figure.axes, x_vars):
label = ax.xaxis.get_label()
assert label.get_visible()
assert label.get_text() == var
def test_y_wrapping(self, long_df):
y_vars = ["f", "x", "y", "z"]
wrap = 3
p = Plot(long_df, x="x").pair(y=y_vars, wrap=wrap).plot()
n_row, n_col = wrap, len(y_vars) // wrap + 1
assert_gridspec_shape(p._figure.axes[0], n_row, n_col)
assert len(p._figure.axes) == len(y_vars)
label_array = np.empty(n_row * n_col, object)
label_array[:len(y_vars)] = y_vars
label_array = label_array.reshape((n_row, n_col), order="F")
label_array = [y for y in label_array.flat if y is not None]
for i, ax in enumerate(p._figure.axes):
label = ax.yaxis.get_label()
assert label.get_visible()
assert label.get_text() == label_array[i]
def test_non_cross_wrapping(self, long_df):
x_vars = ["a", "b", "c", "t"]
y_vars = ["f", "x", "y", "z"]
wrap = 3
p = (
Plot(long_df, x="x")
.pair(x=x_vars, y=y_vars, wrap=wrap, cross=False)
.plot()
)
assert_gridspec_shape(p._figure.axes[0], len(x_vars) // wrap + 1, wrap)
assert len(p._figure.axes) == len(x_vars)
def test_cross_mismatched_lengths(self, long_df):
p = Plot(long_df)
with pytest.raises(ValueError, match="Lengths of the `x` and `y`"):
p.pair(x=["a", "b"], y=["x", "y", "z"], cross=False)
def test_orient_inference(self, long_df):
orient_list = []
class CaptureOrientMove(Move):
def __call__(self, data, groupby, orient, scales):
orient_list.append(orient)
return data
(
Plot(long_df, x="x")
.pair(y=["b", "z"])
.add(MockMark(), CaptureOrientMove())
.plot()
)
assert orient_list == ["y", "x"]
def test_computed_coordinate_orient_inference(self, long_df):
class MockComputeStat(Stat):
def __call__(self, df, groupby, orient, scales):
other = {"x": "y", "y": "x"}[orient]
return df.assign(**{other: df[orient] * 2})
m = MockMark()
Plot(long_df, y="y").add(m, MockComputeStat()).plot()
assert m.passed_orient == "y"
def test_two_variables_single_order_error(self, long_df):
p = Plot(long_df)
err = "When faceting on both col= and row=, passing `order`"
with pytest.raises(RuntimeError, match=err):
p.facet(col="a", row="b", order=["a", "b", "c"])
def test_limits(self, long_df):
lims = (-3, 10), (-2, 24)
p = Plot(long_df, y="y").pair(x=["x", "z"]).limit(x=lims[0], x1=lims[1]).plot()
for ax, lim in zip(p._figure.axes, lims):
assert ax.get_xlim() == lim
def test_labels(self, long_df):
label = "zed"
p = (
Plot(long_df, y="y")
.pair(x=["x", "z"])
.label(x=str.capitalize, x1=label)
)
ax0, ax1 = p.plot()._figure.axes
assert ax0.get_xlabel() == "X"
assert ax1.get_xlabel() == label
|
TestPairInterface
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/scheduler/execution.py
|
{
"start": 280,
"end": 424
}
|
class ____(
NamedTuple("_ScheduledExecutionSkipped", []), ScheduledExecutionResult
):
pass
@whitelist_for_serdes
|
ScheduledExecutionSkipped
|
python
|
pytorch__pytorch
|
benchmarks/operator_benchmark/pt/ternary_test.py
|
{
"start": 704,
"end": 1391
}
|
class ____(op_bench.TorchBenchmarkBase):
def init(self, M, N, device, dtype, op_func):
self.inputs = {
"input_": torch.rand((M, N), device=device).to(dtype=dtype),
"tensor1": torch.rand((M, N), device=device).to(dtype=dtype),
"tensor2": torch.rand((M, N), device=device).to(dtype=dtype),
}
self.op_func = op_func
def forward(self, input_, tensor1, tensor2):
return self.op_func(input_, tensor1, tensor2)
op_bench.generate_pt_tests_from_op_list(
ternary_ops, ternary_configs_short + ternary_configs_long, TernaryOpBenchmark
)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
|
TernaryOpBenchmark
|
python
|
python-poetry__poetry
|
tests/types.py
|
{
"start": 3884,
"end": 3983
}
|
class ____(Protocol):
def __call__(self, name: str) -> Path | None: ...
|
PackageDistributionLookup
|
python
|
MongoEngine__mongoengine
|
tests/fields/test_uuid_field.py
|
{
"start": 176,
"end": 1880
}
|
class ____(MongoDBTestCase):
def test_storage(self):
uid = uuid.uuid4()
person = Person(api_key=uid).save()
assert get_as_pymongo(person) == {"_id": person.id, "api_key": str(uid)}
def test_field_string(self):
"""Test UUID fields storing as String"""
Person.drop_collection()
uu = uuid.uuid4()
Person(api_key=uu).save()
assert 1 == Person.objects(api_key=uu).count()
assert uu == Person.objects.first().api_key
person = Person()
valid = (uuid.uuid4(), uuid.uuid1())
for api_key in valid:
person.api_key = api_key
person.validate()
invalid = (
"9d159858-549b-4975-9f98-dd2f987c113g",
"9d159858-549b-4975-9f98-dd2f987c113",
)
for api_key in invalid:
person.api_key = api_key
with pytest.raises(ValidationError):
person.validate()
def test_field_binary(self):
"""Test UUID fields storing as Binary object."""
Person.drop_collection()
uu = uuid.uuid4()
Person(api_key=uu).save()
assert 1 == Person.objects(api_key=uu).count()
assert uu == Person.objects.first().api_key
person = Person()
valid = (uuid.uuid4(), uuid.uuid1())
for api_key in valid:
person.api_key = api_key
person.validate()
invalid = (
"9d159858-549b-4975-9f98-dd2f987c113g",
"9d159858-549b-4975-9f98-dd2f987c113",
)
for api_key in invalid:
person.api_key = api_key
with pytest.raises(ValidationError):
person.validate()
|
TestUUIDField
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/slots1.py
|
{
"start": 393,
"end": 616
}
|
class ____:
# Only lists and tuples of simple strings are supported, so this
# will be treated as though there are no slots.
__slots__ = ("aaa", f"test{3 + 4}")
def __init__(self):
self.x = 1
|
NoSlots3
|
python
|
doocs__leetcode
|
solution/3600-3699/3696.Maximum Distance Between Unequal Words in Array I/Solution.py
|
{
"start": 0,
"end": 304
}
|
class ____:
def maxDistance(self, words: List[str]) -> int:
n = len(words)
ans = 0
for i in range(n):
if words[i] != words[0]:
ans = max(ans, i + 1)
if words[i] != words[-1]:
ans = max(ans, n - i)
return ans
|
Solution
|
python
|
optuna__optuna
|
optuna/storages/_grpc/client.py
|
{
"start": 16521,
"end": 16728
}
|
class ____:
def __init__(self) -> None:
self.trials: dict[int, FrozenTrial] = {}
self.unfinished_trial_ids: set[int] = set()
self.last_finished_trial_id: int = -1
|
GrpcClientCacheEntry
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.