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 | tensorflow__tensorflow | tensorflow/python/keras/optimizer_v1.py | {
"start": 16411,
"end": 20118
} | class ____(Optimizer):
"""Adam optimizer.
Default parameters follow those provided in the original paper.
Args:
lr: float >= 0. Learning rate.
beta_1: float, 0 < beta < 1. Generally close to 1.
beta_2: float, 0 < beta < 1. Generally close to 1.
epsilon: float >= 0. Fuzz factor.
If `None`, defaults to `backend.epsilon()`.
decay: float >= 0. Learning rate decay over each update.
amsgrad: boolean. Whether to apply the AMSGrad variant of this algorithm
from the paper "On the Convergence of Adam and Beyond".
"""
def __init__(self,
lr=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=None,
decay=0.,
amsgrad=False,
**kwargs):
super(Adam, self).__init__(**kwargs)
with backend.name_scope(self.__class__.__name__):
self.iterations = backend.variable(0, dtype='int64', name='iterations')
self.lr = backend.variable(lr, name='lr')
self.beta_1 = backend.variable(beta_1, name='beta_1')
self.beta_2 = backend.variable(beta_2, name='beta_2')
self.decay = backend.variable(decay, name='decay')
if epsilon is None:
epsilon = backend.epsilon()
self.epsilon = epsilon
self.initial_decay = decay
self.amsgrad = amsgrad
def _create_all_weights(self, params):
ms = [
backend.zeros(backend.int_shape(p), dtype=backend.dtype(p))
for p in params]
vs = [
backend.zeros(backend.int_shape(p), dtype=backend.dtype(p))
for p in params]
if self.amsgrad:
vhats = [
backend.zeros(backend.int_shape(p), dtype=backend.dtype(p))
for p in params]
else:
vhats = [backend.zeros(1) for _ in params]
self.weights = [self.iterations] + ms + vs + vhats
return ms, vs, vhats
def get_updates(self, loss, params):
grads = self.get_gradients(loss, params)
self.updates = []
lr = self.lr
if self.initial_decay > 0:
lr = lr * (
1. /
(1. +
self.decay * math_ops.cast(self.iterations,
backend.dtype(self.decay))))
with ops.control_dependencies([state_ops.assign_add(self.iterations, 1)]):
t = math_ops.cast(self.iterations, backend.floatx())
lr_t = lr * (
backend.sqrt(1. - math_ops.pow(self.beta_2, t)) /
(1. - math_ops.pow(self.beta_1, t)))
ms, vs, vhats = self._create_all_weights(params)
for p, g, m, v, vhat in zip(params, grads, ms, vs, vhats):
m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
v_t = (self.beta_2 * v) + (1. - self.beta_2) * math_ops.square(g)
if self.amsgrad:
vhat_t = math_ops.maximum(vhat, v_t)
p_t = p - lr_t * m_t / (backend.sqrt(vhat_t) + self.epsilon)
self.updates.append(state_ops.assign(vhat, vhat_t))
else:
p_t = p - lr_t * m_t / (backend.sqrt(v_t) + self.epsilon)
self.updates.append(state_ops.assign(m, m_t))
self.updates.append(state_ops.assign(v, v_t))
new_p = p_t
# Apply constraints.
if getattr(p, 'constraint', None) is not None:
new_p = p.constraint(new_p)
self.updates.append(state_ops.assign(p, new_p))
return self.updates
def get_config(self):
config = {
'lr': float(backend.get_value(self.lr)),
'beta_1': float(backend.get_value(self.beta_1)),
'beta_2': float(backend.get_value(self.beta_2)),
'decay': float(backend.get_value(self.decay)),
'epsilon': self.epsilon,
'amsgrad': self.amsgrad
}
base_config = super(Adam, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
| Adam |
python | ray-project__ray | python/ray/data/_internal/compute.py | {
"start": 1896,
"end": 7306
} | class ____(ComputeStrategy):
"""Specify the actor-based compute strategy for a Dataset transform.
ActorPoolStrategy specifies that an autoscaling pool of actors should be used
for a given Dataset transform. This is useful for stateful setup of callable
classes.
For a fixed-sized pool of size ``n``, use ``ActorPoolStrategy(size=n)``.
To autoscale from ``m`` to ``n`` actors, use
``ActorPoolStrategy(min_size=m, max_size=n)``.
To autoscale from ``m`` to ``n`` actors, with an initial size of ``initial``, use
``ActorPoolStrategy(min_size=m, max_size=n, initial_size=initial)``.
To increase opportunities for pipelining task dependency prefetching with
computation and avoiding actor startup delays, set max_tasks_in_flight_per_actor
to 2 or greater; to try to decrease the delay due to queueing of tasks on the worker
actors, set max_tasks_in_flight_per_actor to 1.
"""
def __init__(
self,
*,
size: Optional[int] = None,
min_size: Optional[int] = None,
max_size: Optional[int] = None,
initial_size: Optional[int] = None,
max_tasks_in_flight_per_actor: Optional[int] = None,
):
"""Construct ActorPoolStrategy for a Dataset transform.
Args:
size: Specify a fixed size actor pool of this size. It is an error to
specify both `size` and `min_size` or `max_size`.
min_size: The minimum size of the actor pool.
max_size: The maximum size of the actor pool.
initial_size: The initial number of actors to start with. If not specified,
defaults to min_size. Must be between min_size and max_size.
max_tasks_in_flight_per_actor: The maximum number of tasks to concurrently
send to a single actor worker. Increasing this will increase
opportunities for pipelining task dependency prefetching with
computation and avoiding actor startup delays, but will also increase
queueing delay.
"""
if size is not None:
if size < 1:
raise ValueError("size must be >= 1", size)
if max_size is not None or min_size is not None or initial_size is not None:
raise ValueError(
"min_size, max_size, and initial_size cannot be set at the same time as `size`"
)
min_size = size
max_size = size
initial_size = size
if min_size is not None and min_size < 1:
raise ValueError("min_size must be >= 1", min_size)
if max_size is not None:
if min_size is None:
min_size = 1 # Legacy default.
if min_size > max_size:
raise ValueError("min_size must be <= max_size", min_size, max_size)
if (
max_tasks_in_flight_per_actor is not None
and max_tasks_in_flight_per_actor < 1
):
raise ValueError(
"max_tasks_in_flight_per_actor must be >= 1, got: ",
max_tasks_in_flight_per_actor,
)
self.min_size = min_size or 1
self.max_size = max_size or float("inf")
# Validate and set initial_size
if initial_size is not None:
if initial_size < self.min_size:
raise ValueError(
f"initial_size ({initial_size}) must be >= min_size ({self.min_size})"
)
if self.max_size != float("inf") and initial_size > self.max_size:
raise ValueError(
f"initial_size ({initial_size}) must be <= max_size ({self.max_size})"
)
self.initial_size = initial_size or self.min_size
self.max_tasks_in_flight_per_actor = max_tasks_in_flight_per_actor
self.num_workers = 0
self.ready_to_total_workers_ratio = 0.8
def __eq__(self, other: Any) -> bool:
return isinstance(other, ActorPoolStrategy) and (
self.min_size == other.min_size
and self.max_size == other.max_size
and self.initial_size == other.initial_size
and self.max_tasks_in_flight_per_actor
== other.max_tasks_in_flight_per_actor
)
def __repr__(self) -> str:
return (
f"ActorPoolStrategy(min_size={self.min_size}, "
f"max_size={self.max_size}, "
f"initial_size={self.initial_size}, "
f"max_tasks_in_flight_per_actor={self.max_tasks_in_flight_per_actor})"
f"num_workers={self.num_workers}, "
f"ready_to_total_workers_ratio={self.ready_to_total_workers_ratio})"
)
def get_compute(compute_spec: Union[str, ComputeStrategy]) -> ComputeStrategy:
if not isinstance(compute_spec, (TaskPoolStrategy, ActorPoolStrategy)):
raise ValueError(
"In Ray 2.5, the compute spec must be either "
f"TaskPoolStrategy or ActorPoolStrategy, was: {compute_spec}."
)
elif not compute_spec or compute_spec == "tasks":
return TaskPoolStrategy()
elif compute_spec == "actors":
return ActorPoolStrategy()
elif isinstance(compute_spec, ComputeStrategy):
return compute_spec
else:
raise ValueError("compute must be one of [`tasks`, `actors`, ComputeStrategy]")
| ActorPoolStrategy |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/canonical/original.py | {
"start": 0,
"end": 158
} | class ____:
"""docstring"""
def meth(self):
"""docstring"""
def bar():
class Bar:
"""docstring"""
return Bar
Bar = bar()
| Foo |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 13458,
"end": 14520
} | class ____(PrefectBaseModel, OperatorMixin):
"""Filter task runs. Only task runs matching all criteria will be returned"""
id: Optional[TaskRunFilterId] = Field(
default=None, description="Filter criteria for `TaskRun.id`"
)
name: Optional[TaskRunFilterName] = Field(
default=None, description="Filter criteria for `TaskRun.name`"
)
tags: Optional[TaskRunFilterTags] = Field(
default=None, description="Filter criteria for `TaskRun.tags`"
)
state: Optional[TaskRunFilterState] = Field(
default=None, description="Filter criteria for `TaskRun.state`"
)
start_time: Optional[TaskRunFilterStartTime] = Field(
default=None, description="Filter criteria for `TaskRun.start_time`"
)
subflow_runs: Optional[TaskRunFilterSubFlowRuns] = Field(
default=None, description="Filter criteria for `TaskRun.subflow_run`"
)
flow_run_id: Optional[TaskRunFilterFlowRunId] = Field(
default=None, description="Filter criteria for `TaskRun.flow_run_id`"
)
| TaskRunFilter |
python | sqlalchemy__sqlalchemy | test/ext/asyncio/test_session.py | {
"start": 13433,
"end": 24347
} | class ____(AsyncFixture):
run_inserts = None
@async_test
async def test_interrupt_ctxmanager_connection(
self, async_trans_ctx_manager_fixture, async_session
):
fn = async_trans_ctx_manager_fixture
await fn(async_session, trans_on_subject=True, execute_on_subject=True)
@async_test
async def test_orm_sessionmaker_block_one(self, async_engine):
User = self.classes.User
maker = sessionmaker(async_engine, class_=AsyncSession)
session = maker()
async with session.begin():
u1 = User(name="u1")
assert session.in_transaction()
session.add(u1)
assert not session.in_transaction()
async with maker() as session:
result = await session.execute(
select(User).where(User.name == "u1")
)
u1 = result.scalar_one()
eq_(u1.name, "u1")
@async_test
async def test_orm_sessionmaker_block_two(self, async_engine):
User = self.classes.User
maker = sessionmaker(async_engine, class_=AsyncSession)
async with maker.begin() as session:
u1 = User(name="u1")
assert session.in_transaction()
session.add(u1)
assert not session.in_transaction()
async with maker() as session:
result = await session.execute(
select(User).where(User.name == "u1")
)
u1 = result.scalar_one()
eq_(u1.name, "u1")
@async_test
async def test_async_sessionmaker_block_one(self, async_engine):
User = self.classes.User
maker = async_sessionmaker(async_engine)
session = maker()
async with session.begin():
u1 = User(name="u1")
assert session.in_transaction()
session.add(u1)
assert not session.in_transaction()
async with maker() as session:
result = await session.execute(
select(User).where(User.name == "u1")
)
u1 = result.scalar_one()
eq_(u1.name, "u1")
@async_test
async def test_async_sessionmaker_block_two(self, async_engine):
User = self.classes.User
maker = async_sessionmaker(async_engine)
async with maker.begin() as session:
u1 = User(name="u1")
assert session.in_transaction()
session.add(u1)
assert not session.in_transaction()
async with maker() as session:
result = await session.execute(
select(User).where(User.name == "u1")
)
u1 = result.scalar_one()
eq_(u1.name, "u1")
@async_test
async def test_trans(self, async_session, async_engine):
async with async_engine.connect() as outer_conn:
User = self.classes.User
async with async_session.begin():
eq_(await outer_conn.scalar(select(func.count(User.id))), 0)
u1 = User(name="u1")
async_session.add(u1)
result = await async_session.execute(select(User))
eq_(result.scalar(), u1)
await outer_conn.rollback()
eq_(await outer_conn.scalar(select(func.count(User.id))), 1)
@async_test
async def test_commit_as_you_go(self, async_session, async_engine):
async with async_engine.connect() as outer_conn:
User = self.classes.User
eq_(await outer_conn.scalar(select(func.count(User.id))), 0)
u1 = User(name="u1")
async_session.add(u1)
result = await async_session.execute(select(User))
eq_(result.scalar(), u1)
await async_session.commit()
await outer_conn.rollback()
eq_(await outer_conn.scalar(select(func.count(User.id))), 1)
@async_test
async def test_trans_noctx(self, async_session, async_engine):
async with async_engine.connect() as outer_conn:
User = self.classes.User
trans = await async_session.begin()
try:
eq_(await outer_conn.scalar(select(func.count(User.id))), 0)
u1 = User(name="u1")
async_session.add(u1)
result = await async_session.execute(select(User))
eq_(result.scalar(), u1)
finally:
await trans.commit()
await outer_conn.rollback()
eq_(await outer_conn.scalar(select(func.count(User.id))), 1)
@async_test
async def test_delete(self, async_session):
User = self.classes.User
async with async_session.begin():
u1 = User(name="u1")
async_session.add(u1)
await async_session.flush()
conn = await async_session.connection()
eq_(await conn.scalar(select(func.count(User.id))), 1)
await async_session.delete(u1)
await async_session.flush()
eq_(await conn.scalar(select(func.count(User.id))), 0)
@async_test
async def test_flush(self, async_session):
User = self.classes.User
async with async_session.begin():
u1 = User(name="u1")
async_session.add(u1)
conn = await async_session.connection()
eq_(await conn.scalar(select(func.count(User.id))), 0)
await async_session.flush()
eq_(await conn.scalar(select(func.count(User.id))), 1)
@async_test
async def test_refresh(self, async_session):
User = self.classes.User
async with async_session.begin():
u1 = User(name="u1")
async_session.add(u1)
await async_session.flush()
conn = await async_session.connection()
await conn.execute(
update(User)
.values(name="u2")
.execution_options(synchronize_session=None)
)
eq_(u1.name, "u1")
await async_session.refresh(u1)
eq_(u1.name, "u2")
eq_(await conn.scalar(select(func.count(User.id))), 1)
@async_test
async def test_merge(self, async_session):
User = self.classes.User
async with async_session.begin():
u1 = User(id=1, name="u1")
async_session.add(u1)
async with async_session.begin():
new_u = User(id=1, name="new u1")
new_u_merged = await async_session.merge(new_u)
is_(new_u_merged, u1)
eq_(u1.name, "new u1")
@async_test
async def test_merge_loader_options(self, async_session):
User = self.classes.User
Address = self.classes.Address
async with async_session.begin():
u1 = User(id=1, name="u1", addresses=[Address(email_address="e1")])
async_session.add(u1)
await async_session.close()
async with async_session.begin():
new_u1 = User(id=1, name="new u1")
new_u_merged = await async_session.merge(
new_u1, options=[selectinload(User.addresses)]
)
eq_(new_u_merged.name, "new u1")
eq_(len(new_u_merged.__dict__["addresses"]), 1)
@async_test
async def test_join_to_external_transaction(self, async_engine):
User = self.classes.User
async with async_engine.connect() as conn:
t1 = await conn.begin()
async_session = AsyncSession(conn)
aconn = await async_session.connection()
eq_(aconn.get_transaction(), t1)
eq_(aconn, conn)
is_(aconn.sync_connection, conn.sync_connection)
u1 = User(id=1, name="u1")
async_session.add(u1)
await async_session.commit()
assert conn.in_transaction()
await conn.rollback()
async with AsyncSession(async_engine) as async_session:
result = await async_session.execute(select(User))
eq_(result.all(), [])
@testing.requires.savepoints
@async_test
async def test_join_to_external_transaction_with_savepoints(
self, async_engine
):
"""This is the full 'join to an external transaction' recipe
implemented for async using savepoints.
It's not particularly simple to understand as we have to switch between
async / sync APIs but it works and it's a start.
"""
User = self.classes.User
async with async_engine.connect() as conn:
await conn.begin()
await conn.begin_nested()
async_session = AsyncSession(conn)
@event.listens_for(
async_session.sync_session, "after_transaction_end"
)
def end_savepoint(session, transaction):
"""here's an event. inside the event we write blocking
style code. wow will this be fun to try to explain :)
"""
if conn.closed:
return
if not conn.in_nested_transaction():
conn.sync_connection.begin_nested()
aconn = await async_session.connection()
is_(aconn.sync_connection, conn.sync_connection)
u1 = User(id=1, name="u1")
async_session.add(u1)
await async_session.commit()
result = (await async_session.execute(select(User))).all()
eq_(len(result), 1)
u2 = User(id=2, name="u2")
async_session.add(u2)
await async_session.flush()
result = (await async_session.execute(select(User))).all()
eq_(len(result), 2)
# a rollback inside the session ultimately ends the savepoint
await async_session.rollback()
# but the previous thing we "committed" is still in the DB
result = (await async_session.execute(select(User))).all()
eq_(len(result), 1)
assert conn.in_transaction()
await conn.rollback()
async with AsyncSession(async_engine) as async_session:
result = await async_session.execute(select(User))
eq_(result.all(), [])
@async_test
@testing.requires.independent_connections
async def test_invalidate(self, async_session):
await async_session.execute(select(1))
conn = async_session.sync_session.connection()
fairy = conn.connection
connection_rec = fairy._connection_record
is_false(conn.closed)
is_false(connection_rec._is_hard_or_soft_invalidated())
await async_session.invalidate()
is_true(conn.closed)
is_true(connection_rec._is_hard_or_soft_invalidated())
eq_(async_session.in_transaction(), False)
| AsyncSessionTransactionTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style08.py | {
"start": 315,
"end": 1003
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style08.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename, {"excel2003_style": True})
worksheet = workbook.add_worksheet()
courier = workbook.add_format(
{"font_name": "Courier", "font_size": 8, "font_family": 3}
)
worksheet.write("A1", "Foo")
worksheet.write("A2", "Bar", courier)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/487. Max Consecutive Ones II/487-2.py | {
"start": 0,
"end": 348
} | class ____:
def findMaxConsecutiveOnes(self, nums: list[int]) -> int:
maxZeros = 1
ans = 0
q = collections.deque() # Store indices of zero.
l = 0
for r, num in enumerate(nums):
if num == 0:
q.append(r)
if len(q) > maxZeros:
l = q.popleft() + 1
ans = max(ans, r - l + 1)
return ans
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_scatter13.py | {
"start": 315,
"end": 1602
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_scatter12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart(
{"type": "scatter", "subtype": "straight_with_markers"}
)
chart.axis_ids = [69472640, 69216896]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
"marker": {"type": "none"},
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | keras-team__keras | keras/src/layers/core/einsum_dense.py | {
"start": 556,
"end": 60503
} | class ____(Layer):
"""A layer that uses `einsum` as the backing computation.
This layer can perform einsum calculations of arbitrary dimensionality.
Args:
equation: An equation describing the einsum to perform.
This equation must be a valid einsum string of the form
`ab,bc->ac`, `...ab,bc->...ac`, or
`ab...,bc->ac...` where 'ab', 'bc', and 'ac' can be any valid einsum
axis expression sequence.
output_shape: The expected shape of the output tensor
(excluding the batch dimension and any dimensions
represented by ellipses). You can specify `None` for any dimension
that is unknown or can be inferred from the input shape.
activation: Activation function to use. If you don't specify anything,
no activation is applied
(that is, a "linear" activation: `a(x) = x`).
bias_axes: A string containing the output dimension(s)
to apply a bias to. Each character in the `bias_axes` string
should correspond to a character in the output portion
of the `equation` string.
kernel_initializer: Initializer for the `kernel` weights matrix.
bias_initializer: Initializer for the bias vector.
kernel_regularizer: Regularizer function applied to the `kernel` weights
matrix.
bias_regularizer: Regularizer function applied to the bias vector.
kernel_constraint: Constraint function applied to the `kernel` weights
matrix.
bias_constraint: Constraint function applied to the bias vector.
lora_rank: Optional integer. If set, the layer's forward pass
will implement LoRA (Low-Rank Adaptation)
with the provided rank. LoRA sets the layer's kernel
to non-trainable and replaces it with a delta over the
original kernel, obtained via multiplying two lower-rank
trainable matrices
(the factorization happens on the last dimension).
This can be useful to reduce the
computation cost of fine-tuning large dense layers.
You can also enable LoRA on an existing
`EinsumDense` layer by calling `layer.enable_lora(rank)`.
lora_alpha: Optional integer. If set, this parameter scales the
low-rank adaptation delta (computed as the product of two lower-rank
trainable matrices) during the forward pass. The delta is scaled by
`lora_alpha / lora_rank`, allowing you to fine-tune the strength of
the LoRA adjustment independently of `lora_rank`.
**kwargs: Base layer keyword arguments, such as `name` and `dtype`.
Examples:
**Biased dense layer with einsums**
This example shows how to instantiate a standard Keras dense layer using
einsum operations. This example is equivalent to
`keras.layers.Dense(64, use_bias=True)`.
>>> layer = keras.layers.EinsumDense("ab,bc->ac",
... output_shape=64,
... bias_axes="c")
>>> input_tensor = keras.Input(shape=[32])
>>> output_tensor = layer(input_tensor)
>>> output_tensor.shape
(None, 64)
**Applying a dense layer to a sequence**
This example shows how to instantiate a layer that applies the same dense
operation to every element in a sequence. Here, the `output_shape` has two
values (since there are two non-batch dimensions in the output); the first
dimension in the `output_shape` is `None`, because the sequence dimension
`b` has an unknown shape.
>>> layer = keras.layers.EinsumDense("abc,cd->abd",
... output_shape=(None, 64),
... bias_axes="d")
>>> input_tensor = keras.Input(shape=[32, 128])
>>> output_tensor = layer(input_tensor)
>>> output_tensor.shape
(None, 32, 64)
**Applying a dense layer to a sequence using ellipses**
This example shows how to instantiate a layer that applies the same dense
operation to every element in a sequence, but uses the ellipsis notation
instead of specifying the batch and sequence dimensions.
Because we are using ellipsis notation and have specified only one axis, the
`output_shape` arg is a single value. When instantiated in this way, the
layer can handle any number of sequence dimensions - including the case
where no sequence dimension exists.
>>> layer = keras.layers.EinsumDense("...x,xy->...y",
... output_shape=64,
... bias_axes="y")
>>> input_tensor = keras.Input(shape=[32, 128])
>>> output_tensor = layer(input_tensor)
>>> output_tensor.shape
(None, 32, 64)
"""
def __init__(
self,
equation,
output_shape,
activation=None,
bias_axes=None,
kernel_initializer="glorot_uniform",
bias_initializer="zeros",
kernel_regularizer=None,
bias_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
lora_rank=None,
lora_alpha=None,
gptq_unpacked_column_size=None,
**kwargs,
):
super().__init__(**kwargs)
self.equation = equation
if isinstance(output_shape, int):
self.partial_output_shape = (output_shape,)
else:
self.partial_output_shape = tuple(output_shape)
self.bias_axes = bias_axes
self.activation = activations.get(activation)
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.lora_rank = lora_rank
self.lora_alpha = lora_alpha if lora_alpha is not None else lora_rank
self.lora_enabled = False
self.gptq_unpacked_column_size = gptq_unpacked_column_size
def build(self, input_shape):
shape_data = _analyze_einsum_string(
self.equation,
self.bias_axes,
input_shape,
self.partial_output_shape,
)
kernel_shape, bias_shape, full_output_shape = shape_data
self.full_output_shape = tuple(full_output_shape)
self.input_spec = InputSpec(ndim=len(input_shape))
if self.quantization_mode is not None:
self.quantized_build(
kernel_shape,
mode=self.quantization_mode,
)
# Skip creating a duplicate kernel variable when the layer is already
# quantized to int8 or int4, because `quantized_build` has created the
# appropriate kernel variable. For other modes (e.g., float8 or no
# quantization), we still need the floating-point kernel.
if self.quantization_mode not in ("int8", "int4", "gptq"):
# If the layer is quantized to int8, `self._kernel` will be added
# in `self._int8_build`. Therefore, we skip it here.
self._kernel = self.add_weight(
name="kernel",
shape=tuple(kernel_shape),
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
dtype=self.dtype,
trainable=True,
)
if bias_shape is not None:
self.bias = self.add_weight(
name="bias",
shape=tuple(bias_shape),
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint,
dtype=self.dtype,
trainable=True,
)
else:
self.bias = None
self.built = True
if self.lora_rank:
self.enable_lora(self.lora_rank, lora_alpha=self.lora_alpha)
@property
def kernel(self):
from keras.src.quantizers import gptq_core
if not self.built:
raise AttributeError(
"You must build the layer before accessing `kernel`."
)
mode = self.quantization_mode
is_gptq = mode == "gptq"
is_int4 = mode == "int4"
calibrated = bool(getattr(self, "is_gptq_calibrated", False))
gptq_bits = (
gptq_core.get_weight_bits_for_layer(self, None) if is_gptq else None
)
# Decide the source tensor first (packed vs already-quantized vs plain
# kernel)
if is_gptq and calibrated and gptq_bits != 4:
# calibrated GPTQ, not 4-bit, no unpacking needed
kernel = self.quantized_kernel
else:
# Start with the stored kernel
kernel = getattr(self, "_kernel", None)
# Handle int4 unpacking cases in one place
if is_int4:
kernel = quantizers.unpack_int4(
kernel,
self._orig_length_along_pack_axis,
self._int4_pack_axis,
)
elif is_gptq and calibrated and gptq_bits == 4:
kernel = quantizers.unpack_int4(
self.quantized_kernel,
orig_len=self.gptq_unpacked_column_size,
axis=0,
dtype="uint8",
)
# Apply LoRA if enabled
if self.lora_enabled:
kernel = kernel + (self.lora_alpha / self.lora_rank) * ops.matmul(
self.lora_kernel_a, self.lora_kernel_b
)
return kernel
def compute_output_shape(self, _):
return self.full_output_shape
def call(self, inputs, training=None):
x = ops.einsum(self.equation, inputs, self.kernel)
if self.bias is not None:
x = ops.add(x, self.bias)
if self.activation is not None:
x = self.activation(x)
return x
def enable_lora(
self,
rank,
lora_alpha=None,
a_initializer="he_uniform",
b_initializer="zeros",
):
if self.kernel_constraint:
raise ValueError(
"Lora is incompatible with kernel constraints. "
"In order to enable lora on this layer, remove the "
"`kernel_constraint` argument."
)
if not self.built:
raise ValueError(
"Cannot enable lora on a layer that isn't yet built."
)
if self.lora_enabled:
raise ValueError(
"lora is already enabled. This can only be done once per layer."
)
if self.quantization_mode == "gptq":
raise NotImplementedError(
"lora is not currently supported with GPTQ quantization."
)
self._tracker.unlock()
# Determine the appropriate (unpacked) kernel shape for LoRA.
if self.quantization_mode == "int4":
# When int4-quantized, `self._kernel` is packed along
# `self._int4_pack_axis` and its length equals
# `(orig_len + 1) // 2`. Recover the original length so that
# the LoRA matrices operate in the full-precision space.
kernel_shape_for_lora = list(self._kernel.shape)
pack_axis = getattr(self, "_int4_pack_axis", 0)
orig_len = getattr(self, "_orig_length_along_pack_axis", None)
if orig_len is not None:
kernel_shape_for_lora[pack_axis] = orig_len
kernel_shape_for_lora = tuple(kernel_shape_for_lora)
else:
kernel_shape_for_lora = self.kernel.shape
self.lora_kernel_a = self.add_weight(
name="lora_kernel_a",
shape=(kernel_shape_for_lora[:-1] + (rank,)),
initializer=initializers.get(a_initializer),
regularizer=self.kernel_regularizer,
)
self.lora_kernel_b = self.add_weight(
name="lora_kernel_b",
shape=(rank, self.kernel.shape[-1]),
initializer=initializers.get(b_initializer),
regularizer=self.kernel_regularizer,
)
self._kernel.trainable = False
self._tracker.lock()
self.lora_enabled = True
self.lora_rank = rank
self.lora_alpha = lora_alpha if lora_alpha is not None else rank
def save_own_variables(self, store):
# Do nothing if the layer isn't yet built
if not self.built:
return
mode = self.quantization_mode
if mode not in self.variable_serialization_spec:
raise self._quantization_mode_error(mode)
# Kernel plus optional merged LoRA-aware scale (returns (kernel, None)
# for None/gptq)
kernel_value, merged_kernel_scale = self._get_kernel_with_merged_lora()
idx = 0
for name in self.variable_serialization_spec[mode]:
if name == "kernel":
store[str(idx)] = kernel_value
elif name == "bias" and self.bias is None:
continue
elif name == "kernel_scale" and mode in ("int4", "int8"):
# For int4/int8, the merged LoRA scale (if any) comes from
# `_get_kernel_with_merged_lora()`
store[str(idx)] = merged_kernel_scale
else:
store[str(idx)] = getattr(self, name)
idx += 1
def load_own_variables(self, store):
if not self.lora_enabled:
self._check_load_own_variables(store)
# Do nothing if the layer isn't yet built
if not self.built:
return
mode = self.quantization_mode
if mode not in self.variable_serialization_spec:
raise self._quantization_mode_error(mode)
# A saved GPTQ quantized model will always be calibrated.
self.is_gptq_calibrated = mode == "gptq"
idx = 0
for name in self.variable_serialization_spec[mode]:
if name == "kernel":
self._kernel.assign(store[str(idx)])
elif name == "bias" and self.bias is None:
continue
else:
getattr(self, name).assign(store[str(idx)])
idx += 1
if self.lora_enabled:
self.lora_kernel_a.assign(ops.zeros(self.lora_kernel_a.shape))
self.lora_kernel_b.assign(ops.zeros(self.lora_kernel_b.shape))
def get_config(self):
base_config = super().get_config()
config = {
"output_shape": self.partial_output_shape,
"equation": self.equation,
"activation": activations.serialize(self.activation),
"bias_axes": self.bias_axes,
"kernel_initializer": initializers.serialize(
self.kernel_initializer
),
"bias_initializer": initializers.serialize(self.bias_initializer),
"kernel_regularizer": regularizers.serialize(
self.kernel_regularizer
),
"bias_regularizer": regularizers.serialize(self.bias_regularizer),
"activity_regularizer": regularizers.serialize(
self.activity_regularizer
),
"kernel_constraint": constraints.serialize(self.kernel_constraint),
"bias_constraint": constraints.serialize(self.bias_constraint),
}
if self.lora_rank:
config["lora_rank"] = self.lora_rank
config["lora_alpha"] = self.lora_alpha
if self.gptq_unpacked_column_size:
config["gptq_unpacked_column_size"] = self.gptq_unpacked_column_size
return {**base_config, **config}
@property
def variable_serialization_spec(self):
"""Returns a dict mapping quantization modes to variable names in order.
This spec is used by `save_own_variables` and `load_own_variables` to
determine the correct ordering of variables during serialization for
each quantization mode. `None` means no quantization.
"""
return {
None: [
"kernel",
"bias",
],
"int8": [
"kernel",
"bias",
"kernel_scale",
],
"int4": [
"kernel",
"bias",
"kernel_scale",
],
"float8": [
"kernel",
"bias",
"inputs_scale",
"inputs_amax_history",
"kernel_scale",
"kernel_amax_history",
"outputs_grad_scale",
"outputs_grad_amax_history",
],
"gptq": [
"bias",
"quantized_kernel",
"kernel_scale",
"kernel_zero",
"g_idx",
],
}
def quantized_build(self, kernel_shape, mode, config=None):
if mode == "int8":
self._int8_build(kernel_shape)
elif mode == "int4":
self._int4_build(kernel_shape)
elif mode == "float8":
self._float8_build()
elif mode == "gptq":
self._gptq_build(kernel_shape, config)
else:
raise self._quantization_mode_error(mode)
self._is_quantized = True
def _int8_build(self, kernel_shape):
self._set_quantization_info()
self.inputs_quantizer = quantizers.AbsMaxQuantizer(
axis=self._input_reduced_axes
)
self._kernel = self.add_weight(
name="kernel",
shape=kernel_shape,
initializer="zeros",
dtype="int8",
trainable=False,
)
kernel_scale_shape = self._get_kernel_scale_shape(kernel_shape)
self.kernel_scale = self.add_weight(
name="kernel_scale",
shape=kernel_scale_shape,
initializer="ones",
trainable=False,
)
def _gptq_build(self, kernel_shape, config):
"""
Allocate quantized kernel & params for EinsumDense.
Args:
kernel_shape: tuple/list; the layer's original kernel shape, e.g.
[in_features, out_features] or [in_features, heads, head_dim].
group_size: int; contiguous input-group size for quantization
(=-1 means per-output-channel with no grouping).
"""
from keras.src.quantizers import gptq_core
# Ensures the forward pass uses the original high-precision kernel
# until calibration has been performed.
self.is_gptq_calibrated = False
self.original_kernel_shape = kernel_shape
if len(kernel_shape) == 2:
rows = kernel_shape[0]
columns = kernel_shape[1]
elif len(kernel_shape) == 3:
shape = list(self.original_kernel_shape)
d_model_dim_index = shape.index(max(shape))
if d_model_dim_index == 0: # QKV projection case
in_features, heads, head_dim = shape
rows, columns = (
in_features,
heads * head_dim,
)
elif d_model_dim_index in [1, 2]: # Attention Output case
heads, head_dim, out_features = shape
rows, columns = (
heads * head_dim,
out_features,
)
else:
raise ValueError("Could not determine row/column split.")
group_size = gptq_core.get_group_size_for_layer(self, config)
n_groups = 1 if group_size == -1 else math.ceil(rows / group_size)
self.gptq_unpacked_column_size = columns
weight_bits = gptq_core.get_weight_bits_for_layer(self, config)
# For 4-bit weights, we pack two values per byte.
kernel_columns = (columns + 1) // 2 if weight_bits == 4 else columns
self._set_quantization_info()
self.quantized_kernel = self.add_weight(
name="kernel",
shape=(kernel_columns, rows),
initializer="zeros",
dtype="uint8",
trainable=False,
)
self.kernel_scale = self.add_weight(
name="kernel_scale",
shape=(columns, n_groups),
initializer="ones",
trainable=False,
)
self.kernel_zero = self.add_weight(
name="zero_point",
shape=(columns, n_groups),
initializer="zeros",
dtype="uint8",
trainable=False,
)
self.g_idx = self.add_weight(
name="g_idx",
shape=(rows,),
initializer="zeros",
dtype="float32",
trainable=False,
)
def _gptq_call(self, inputs, training=False):
from keras.src.quantizers import gptq_core
if not self.is_gptq_calibrated:
W = self._kernel
else:
should_unpack = (
gptq_core.get_weight_bits_for_layer(self, config=None) == 4
)
W = (
quantizers.unpack_int4(
self.quantized_kernel,
orig_len=self.gptq_unpacked_column_size,
axis=0,
dtype="uint8",
)
if should_unpack
else self.quantized_kernel
)
W = dequantize_with_sz_map(
W,
self.kernel_scale,
self.kernel_zero,
self.g_idx,
)
W = ops.transpose(W)
W = ops.reshape(W, self.original_kernel_shape)
y = ops.einsum(self.equation, inputs, W)
if self.bias is not None:
y = ops.add(y, self.bias)
if self.activation is not None:
y = self.activation(y)
return y
def _int4_build(self, kernel_shape):
"""Build variables for int4 quantization.
The packed int4 kernel stores two int4 values within a single int8
byte. Packing is performed along the first axis contained in
`self._kernel_reduced_axes` (which is the axis that gets reduced in
the einsum and thus analogous to the input-dim axis of a `Dense`
layer).
"""
self._set_quantization_info()
# Quantizer for the inputs (per the reduced axes)
self.inputs_quantizer = quantizers.AbsMaxQuantizer(
axis=self._input_reduced_axes
)
# Choose the axis to perform int4 packing - use the first reduced axis
# for the kernel (analogous to the input dimension of a Dense layer).
self._int4_pack_axis = (
self._kernel_reduced_axes[0] if self._kernel_reduced_axes else 0
)
# Original length along the packing axis (needed for unpacking).
self._orig_length_along_pack_axis = kernel_shape[self._int4_pack_axis]
# Packed length (ceil division by 2). Note: assumes static integer.
packed_len = (self._orig_length_along_pack_axis + 1) // 2
# Derive packed kernel shape by replacing the pack axis dimension.
packed_kernel_shape = list(kernel_shape)
packed_kernel_shape[self._int4_pack_axis] = packed_len
packed_kernel_shape = tuple(packed_kernel_shape)
# Add packed int4 kernel variable (stored as int8 dtype).
self._kernel = self.add_weight(
name="kernel",
shape=packed_kernel_shape,
initializer="zeros",
dtype="int8",
trainable=False,
)
# Kernel scale
kernel_scale_shape = self._get_kernel_scale_shape(kernel_shape)
self.kernel_scale = self.add_weight(
name="kernel_scale",
shape=kernel_scale_shape,
initializer="ones",
trainable=False,
)
def _float8_build(self):
from keras.src.dtype_policies import QuantizedFloat8DTypePolicy
# If `self.dtype_policy` is not QuantizedFloat8DTypePolicy, then set
# `amax_history_length` to its default value.
amax_history_length = getattr(
self.dtype_policy,
"amax_history_length",
QuantizedFloat8DTypePolicy.default_amax_history_length,
)
# We set `trainable=True` because we will use the gradients to overwrite
# these variables
scale_kwargs = {
"shape": (),
"initializer": "ones",
"dtype": "float32", # Always be float32
"trainable": True,
"autocast": False,
"overwrite_with_gradient": True,
}
amax_history_kwargs = {
"shape": (amax_history_length,),
"initializer": "zeros",
"dtype": "float32", # Always be float32
"trainable": True,
"autocast": False,
"overwrite_with_gradient": True,
}
self.inputs_scale = self.add_weight(name="inputs_scale", **scale_kwargs)
self.inputs_amax_history = self.add_weight(
name="inputs_amax_history", **amax_history_kwargs
)
self.kernel_scale = self.add_weight(name="kernel_scale", **scale_kwargs)
self.kernel_amax_history = self.add_weight(
name="kernel_amax_history", **amax_history_kwargs
)
self.outputs_grad_scale = self.add_weight(
name="outputs_grad_scale", **scale_kwargs
)
self.outputs_grad_amax_history = self.add_weight(
name="outputs_grad_amax_history", **amax_history_kwargs
)
def _int8_call(self, inputs, training=None):
@ops.custom_gradient
def einsum_with_inputs_gradient(inputs, kernel, kernel_scale):
"""Performs int8 quantized einsum with a custom gradient.
Computes the einsum operation with quantized inputs and a quantized
kernel, then de-quantizes the result.
Also computes the gradient with respect to the original,
full-precision inputs by using a de-quantized kernel.
Args:
inputs: The full-precision input tensor.
kernel: The int8 quantized kernel tensor.
kernel_scale: The float32 scale factor for the kernel.
Returns:
A tuple `(output, grad_fn)`:
`output`: The de-quantized result of the einsum operation.
`grad_fn`: The custom gradient function for the backward
pass.
Raises:
ValueError: If the quantization mode is not supported.
"""
def grad_fn(*args, upstream=None):
if upstream is None:
(upstream,) = args
# De-scale kernel
_kernel_scale = kernel_scale
_kernel_scale = self._adjust_scale_for_dequant(_kernel_scale)
float_kernel = ops.divide(
ops.cast(kernel, dtype=self.compute_dtype),
_kernel_scale,
)
# From https://stackoverflow.com/a/47609896
inputs_grad = ops.einsum(
self._custom_gradient_equation, upstream, float_kernel
)
return (inputs_grad, None, None)
inputs, inputs_scale = self.inputs_quantizer(inputs)
x = ops.einsum(self.equation, inputs, kernel)
# Deal with `inputs_scale`
inputs_scale = self._adjust_scale_for_quant(inputs_scale, "input")
# De-scale outputs
x = ops.cast(x, self.compute_dtype)
x = ops.divide(x, ops.multiply(inputs_scale, kernel_scale))
return x, grad_fn
x = einsum_with_inputs_gradient(
inputs,
ops.convert_to_tensor(self._kernel),
ops.convert_to_tensor(self.kernel_scale),
)
if self.lora_enabled:
lora_x = ops.einsum(self.equation, inputs, self.lora_kernel_a)
lora_x = ops.matmul(lora_x, self.lora_kernel_b)
x = ops.add(x, (self.lora_alpha / self.lora_rank) * lora_x)
if self.bias is not None:
x = ops.add(x, self.bias)
if self.activation is not None:
x = self.activation(x)
return x
def _int4_call(self, inputs, training=None):
"""Forward pass for int4 quantized `EinsumDense`."""
pack_axis = getattr(self, "_int4_pack_axis", 0)
orig_len = getattr(self, "_orig_length_along_pack_axis", None)
@ops.custom_gradient
def einsum_with_inputs_gradient(inputs, packed_kernel, kernel_scale):
"""Performs int4 quantized einsum with a custom gradient.
Computes the einsum operation with quantized inputs and a quantized
kernel, then de-quantizes the result.
Also computes the gradient with respect to the original,
full-precision inputs by using a de-quantized kernel.
Args:
inputs: The full-precision input tensor.
packed_kernel: The int4-packed kernel tensor.
kernel_scale: The float32 scale factor for the kernel.
Returns:
A tuple `(output, grad_fn)`:
`output`: The de-quantized result of the einsum operation.
`grad_fn`: The custom gradient function for the backward
pass.
Raises:
ValueError: If the quantization mode is not supported.
"""
# Unpack the int4-packed kernel back to int8 values [-8, 7].
unpacked_kernel = quantizers.unpack_int4(
packed_kernel, orig_len, axis=pack_axis
)
def grad_fn(*args, upstream=None):
if upstream is None:
(upstream,) = args
# Align `kernel_scale` to the same layout as `unpacked_kernel`.
_kernel_scale = kernel_scale
_kernel_scale = self._adjust_scale_for_dequant(_kernel_scale)
float_kernel = ops.divide(
ops.cast(unpacked_kernel, dtype=self.compute_dtype),
_kernel_scale,
)
inputs_grad = ops.einsum(
self._custom_gradient_equation, upstream, float_kernel
)
return (inputs_grad, None, None)
# Quantize inputs per `self.inputs_quantizer`.
inputs_q, inputs_scale = self.inputs_quantizer(inputs)
# Compute einsum on quantized inputs and unpacked int4 kernel.
x = ops.einsum(self.equation, inputs_q, unpacked_kernel)
# Align `inputs_scale` axes with the output for correct broadcasting
inputs_scale = self._adjust_scale_for_quant(inputs_scale, "input")
# De-scale outputs.
x = ops.cast(x, self.compute_dtype)
x = ops.divide(x, ops.multiply(inputs_scale, kernel_scale))
return x, grad_fn
x = einsum_with_inputs_gradient(
inputs,
ops.convert_to_tensor(self._kernel),
ops.convert_to_tensor(self.kernel_scale),
)
# Add LoRA contribution if enabled
if self.lora_enabled:
lora_x = ops.einsum(self.equation, inputs, self.lora_kernel_a)
lora_x = ops.matmul(lora_x, self.lora_kernel_b)
x = ops.add(x, (self.lora_alpha / self.lora_rank) * lora_x)
# Bias & activation
if self.bias is not None:
x = ops.add(x, self.bias)
if self.activation is not None:
x = self.activation(x)
return x
def _float8_call(self, inputs, training=None):
if self.lora_enabled:
raise NotImplementedError(
"Currently, `_float8_call` doesn't support LoRA"
)
@ops.custom_gradient
def quantized_dequantize_inputs(inputs, scale, amax_history):
if training:
new_scale = quantizers.compute_float8_scale(
ops.max(amax_history, axis=0),
scale,
ops.cast(
float(ml_dtypes.finfo("float8_e4m3fn").max), "float32"
),
)
new_amax_history = quantizers.compute_float8_amax_history(
inputs, amax_history
)
else:
new_scale = None
new_amax_history = None
qdq_inputs = quantizers.quantize_and_dequantize(
inputs, scale, "float8_e4m3fn", self.compute_dtype
)
def grad(*args, upstream=None, variables=None):
if upstream is None:
(upstream,) = args
return upstream, new_scale, new_amax_history
return qdq_inputs, grad
@ops.custom_gradient
def quantized_dequantize_outputs(outputs, scale, amax_history):
"""Quantize-dequantize the output gradient but not the output."""
def grad(*args, upstream=None, variables=None):
if upstream is None:
(upstream,) = args
new_scale = quantizers.compute_float8_scale(
ops.max(amax_history, axis=0),
scale,
ops.cast(
float(ml_dtypes.finfo("float8_e5m2").max), "float32"
),
)
qdq_upstream = quantizers.quantize_and_dequantize(
upstream, scale, "float8_e5m2", self.compute_dtype
)
new_amax_history = quantizers.compute_float8_amax_history(
upstream, amax_history
)
return qdq_upstream, new_scale, new_amax_history
return outputs, grad
x = ops.einsum(
self.equation,
quantized_dequantize_inputs(
inputs,
ops.convert_to_tensor(self.inputs_scale),
ops.convert_to_tensor(self.inputs_amax_history),
),
quantized_dequantize_inputs(
ops.convert_to_tensor(self._kernel),
ops.convert_to_tensor(self.kernel_scale),
ops.convert_to_tensor(self.kernel_amax_history),
),
)
# `quantized_dequantize_outputs` is placed immediately after
# `ops.einsum` for the sake of pattern matching in gemm_rewrite. That
# way, the qdq will be adjacent to the corresponding einsum_bprop in the
# bprop.
x = quantized_dequantize_outputs(
x,
ops.convert_to_tensor(self.outputs_grad_scale),
ops.convert_to_tensor(self.outputs_grad_amax_history),
)
if self.bias is not None:
# Under non-mixed precision cases, F32 bias has to be converted to
# BF16 first to get the biasAdd fusion support. ref. PR
# https://github.com/tensorflow/tensorflow/pull/60306
bias = self.bias
if self.dtype_policy.compute_dtype == "float32":
bias_bf16 = ops.cast(bias, "bfloat16")
bias = ops.cast(bias_bf16, bias.dtype)
x = ops.add(x, bias)
if self.activation is not None:
x = self.activation(x)
return x
def quantize(self, mode, type_check=True, config=None):
# Prevent quantization of the subclasses
if type_check and (type(self) is not EinsumDense):
raise self._not_implemented_error(self.quantize)
kernel_shape = self._kernel.shape
if mode in ("int8", "int4", "gptq"):
self._set_quantization_info()
if mode == "int8":
# Quantize `self._kernel` to int8 and compute corresponding scale
kernel_value, kernel_scale = quantizers.abs_max_quantize(
self._kernel, axis=self._kernel_reduced_axes, to_numpy=True
)
kernel_scale = self._adjust_scale_for_quant(kernel_scale, "kernel")
del self._kernel
elif mode == "int4":
# Quantize to int4 values (stored in int8 dtype, range [-8, 7])
kernel_value_int4, kernel_scale = quantizers.abs_max_quantize(
self._kernel,
axis=self._kernel_reduced_axes,
value_range=(-8, 7),
dtype="int8",
to_numpy=True,
)
kernel_scale = self._adjust_scale_for_quant(kernel_scale, "kernel")
# Pack along the first kernel-reduced axis.
pack_axis = self._kernel_reduced_axes[0]
packed_kernel_value, _, _ = quantizers.pack_int4(
kernel_value_int4, axis=pack_axis
)
kernel_value = packed_kernel_value
del self._kernel
self.quantized_build(kernel_shape, mode, config)
# Assign values to the newly created variables.
if mode in ("int8", "int4"):
self._kernel.assign(kernel_value)
self.kernel_scale.assign(kernel_scale)
# Set new dtype policy
if self.dtype_policy.quantization_mode is None:
policy_name = mode
if mode == "gptq":
policy_name = config.dtype_policy_string()
policy = dtype_policies.get(
f"{policy_name}_from_{self.dtype_policy.name}"
)
self.dtype_policy = policy
def _get_kernel_scale_shape(self, kernel_shape):
"""Get the shape of the kernel scale tensor.
The kernel scale tensor is used to scale the kernel tensor.
The shape of the kernel scale tensor is the same as the shape of the
kernel tensor, but with the reduced axes set to 1 and the transpose
axes set to the original axes
Args:
kernel_shape: The shape of the kernel tensor.
Returns:
The shape of the kernel scale tensor.
"""
kernel_scale_shape = np.array(kernel_shape)
kernel_scale_shape[self._kernel_reduced_axes] = 1
kernel_scale_shape = kernel_scale_shape[self._kernel_transpose_axes]
kernel_scale_shape = kernel_scale_shape.tolist()
for a in sorted(self._kernel_expand_axes):
kernel_scale_shape.insert(a, 1)
for a in sorted(self._kernel_squeeze_axes, reverse=True):
kernel_scale_shape.pop(a)
return kernel_scale_shape
def _get_kernel_with_merged_lora(self):
"""Returns the kernel with LoRA matrices merged, for serialization.
This method is called by `save_own_variables` to produce a single
kernel tensor that includes the adaptations from LoRA. This is useful
for deploying the model or for continuing training after permanently
applying the LoRA update.
If the layer is quantized (`int8` or `int4`), the process is:
1. Dequantize the base kernel to float.
2. Adjust the scale tensor layout for dequantization. This is the
reverse order of operations used when building the layer.
3. Compute the LoRA delta (`lora_kernel_a @ lora_kernel_b`) and add
it to the dequantized kernel.
4. Re-quantize the merged result back to the original quantized
type (`int8` or packed `int4`), calculating a new scale factor.
5. Adjust the scale tensor layout for quantization. This is the forward
order of operations used when building the layer.
If the layer is not quantized, this method returns the result of the
`kernel` property (which computes the merge in floating-point) and a
scale of `None`.
If LoRA is not enabled, it returns the original kernel and scale
without modification.
Returns:
A tuple `(kernel_value, kernel_scale)`:
`kernel_value`: The merged kernel. A quantized tensor if
quantization is active, otherwise a high precision tensor.
`kernel_scale`: The quantization scale for the merged kernel.
This is `None` if the layer is not quantized.
"""
# If not a quantized layer, return the full-precision kernel directly.
if self.dtype_policy.quantization_mode in (None, "gptq"):
return self.kernel, None
# If quantized but LoRA is not enabled, return the original quantized
# kernel.
if not self.lora_enabled:
return self._kernel, self.kernel_scale
# Dequantize, Merge, and Re-quantize
# 1. Dequantize the kernel
if self.quantization_mode == "int4":
unpacked_kernel = quantizers.unpack_int4(
self._kernel,
self._orig_length_along_pack_axis,
axis=self._int4_pack_axis,
)
# Adjust scale for dequantization (reverse the transformations).
adjusted_scale = self._adjust_scale_for_dequant(self.kernel_scale)
kernel_fp = ops.divide(unpacked_kernel, adjusted_scale)
elif self.quantization_mode == "int8":
adjusted_scale = self._adjust_scale_for_dequant(self.kernel_scale)
kernel_fp = ops.divide(self._kernel, adjusted_scale)
else:
raise ValueError(
f"Unsupported quantization mode: {self.quantization_mode}"
)
# 2. Merge the LoRA update in the float domain
lora_update = (self.lora_alpha / self.lora_rank) * ops.matmul(
self.lora_kernel_a, self.lora_kernel_b
)
merged_kernel_fp = ops.add(kernel_fp, lora_update)
# 3. Re-quantize the merged float kernel back to the target format
if self.quantization_mode == "int4":
kernel_quant, new_scale = quantizers.abs_max_quantize(
merged_kernel_fp,
axis=self._kernel_reduced_axes,
value_range=(-8, 7),
dtype="int8",
to_numpy=True,
)
# Pack back to int4
new_kernel, _, _ = quantizers.pack_int4(
kernel_quant, axis=self._int4_pack_axis
)
elif self.quantization_mode == "int8":
new_kernel, new_scale = quantizers.abs_max_quantize(
merged_kernel_fp,
axis=self._kernel_reduced_axes,
to_numpy=True,
)
# Adjust the new scale tensor to the required layout.
new_scale = self._adjust_scale_for_quant(new_scale, "kernel")
return new_kernel, new_scale
def _adjust_scale_for_dequant(self, scale):
"""Adjusts scale tensor layout for dequantization.
Helper method to handle scale adjustments before dequantization.
This is the reverse order of operations used when building the layer.
Args:
scale: The scale tensor to adjust.
Returns:
The adjusted scale tensor.
"""
if self._kernel_squeeze_axes:
scale = ops.expand_dims(scale, axis=self._kernel_squeeze_axes)
if self._kernel_expand_axes:
scale = ops.squeeze(scale, axis=self._kernel_expand_axes)
if self._kernel_transpose_axes:
# We need to reverse the transpose operation.
reverse_transpose = sorted(
range(len(self._kernel_transpose_axes)),
key=self._kernel_transpose_axes.__getitem__,
)
scale = ops.transpose(scale, axes=reverse_transpose)
return scale
def _adjust_scale_for_quant(self, scale, tensor_type="kernel"):
"""Adjusts scale tensor layout after quantization.
Helper method to handle scale adjustments after re-quantization.
This is the forward order of operations used when building the layer.
Args:
scale: The scale tensor to adjust.
tensor_type: The type of tensor to adjust the scale for.
"kernel" or "input".
Returns:
The adjusted scale tensor.
"""
if tensor_type == "kernel":
transpose_axes = self._kernel_transpose_axes
expand_axes = self._kernel_expand_axes
squeeze_axes = self._kernel_squeeze_axes
elif tensor_type == "input":
transpose_axes = self._input_transpose_axes
expand_axes = self._input_expand_axes
squeeze_axes = self._input_squeeze_axes
else:
raise ValueError(f"Invalid tensor type: {tensor_type}")
if transpose_axes:
scale = ops.transpose(scale, transpose_axes)
if expand_axes:
scale = ops.expand_dims(scale, axis=expand_axes)
if squeeze_axes:
scale = ops.squeeze(scale, axis=squeeze_axes)
return scale
def _set_quantization_info(self):
if hasattr(self, "_input_reduced_axes"):
# Already set.
return
(
self._input_reduced_axes,
self._kernel_reduced_axes,
self._input_transpose_axes,
self._kernel_transpose_axes,
self._input_expand_axes,
self._kernel_expand_axes,
self._input_squeeze_axes,
self._kernel_squeeze_axes,
self._custom_gradient_equation,
self._kernel_reverse_transpose_axes,
) = _analyze_quantization_info(self.equation, self.input_spec.ndim)
def _analyze_einsum_string(equation, bias_axes, input_shape, output_shape):
"""Parses an einsum string to determine the shapes of the weights.
This function is the main entry point for analyzing the einsum equation.
It handles equations with and without ellipses (`...`) by converting them
to a standard format and then delegating to `_analyze_split_string` for
the core logic.
Args:
equation: The einsum equation string, e.g., "ab,bc->ac" or
"...ab,bc->...ac".
bias_axes: A string indicating which output axes to apply a bias to.
input_shape: The shape of the input tensor.
output_shape: The user-specified shape of the output tensor (may be
partial).
Returns:
A tuple `(kernel_shape, bias_shape, full_output_shape)` where:
`kernel_shape`: The calculated shape of the einsum kernel.
`bias_shape`: The calculated shape of the bias, or `None`.
`full_output_shape`: The fully-resolved shape of the output tensor.
Raises:
ValueError: If the einsum `equation` is not in a supported format.
"""
dot_replaced_string = re.sub(r"\.\.\.", "0", equation)
# This is the case where no ellipses are present in the string.
split_string = re.match(
"([a-zA-Z]+),([a-zA-Z]+)->([a-zA-Z]+)", dot_replaced_string
)
if split_string:
return _analyze_split_string(
split_string, bias_axes, input_shape, output_shape
)
# This is the case where ellipses are present on the left.
split_string = re.match(
"0([a-zA-Z]+),([a-zA-Z]+)->0([a-zA-Z]+)", dot_replaced_string
)
if split_string:
return _analyze_split_string(
split_string, bias_axes, input_shape, output_shape, left_elided=True
)
# This is the case where ellipses are present on the right.
split_string = re.match(
"([a-zA-Z]{2,})0,([a-zA-Z]+)->([a-zA-Z]+)0", dot_replaced_string
)
if split_string:
return _analyze_split_string(
split_string, bias_axes, input_shape, output_shape
)
raise ValueError(
f"Invalid einsum equation '{equation}'. Equations must be in the form "
"[X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]...."
)
def _analyze_split_string(
split_string, bias_axes, input_shape, output_shape, left_elided=False
):
"""Computes kernel and bias shapes from a parsed einsum equation.
This function takes the components of an einsum equation, validates them,
and calculates the required shapes for the kernel and bias weights.
Args:
split_string: A regex match object containing the input, weight, and
output specifications.
bias_axes: A string indicating which output axes to apply a bias to.
input_shape: The shape of the input tensor.
output_shape: The user-specified partial shape of the output tensor.
left_elided: A boolean indicating if the ellipsis "..." was on the
left side of the equation.
Returns:
A tuple `(kernel_shape, bias_shape, full_output_shape)` where:
`kernel_shape`: The calculated shape of the einsum kernel.
`bias_shape`: The calculated shape of the bias, or `None`.
`full_output_shape`: The fully-resolved shape of the output tensor.
Raises:
ValueError: If there are inconsistencies between the input and output
shapes or if the equation specifications are invalid.
"""
input_spec = split_string.group(1)
weight_spec = split_string.group(2)
output_spec = split_string.group(3)
elided = len(input_shape) - len(input_spec)
if isinstance(output_shape, int):
output_shape = [output_shape]
else:
output_shape = list(output_shape)
output_shape.insert(0, input_shape[0])
if elided > 0 and left_elided:
for i in range(1, elided):
# We already inserted the 0th input dimension at dim 0, so we need
# to start at location 1 here.
output_shape.insert(1, input_shape[i])
elif elided > 0 and not left_elided:
for i in range(len(input_shape) - elided, len(input_shape)):
output_shape.append(input_shape[i])
if left_elided:
# If we have beginning dimensions elided, we need to use negative
# indexing to determine where in the input dimension our values are.
input_dim_map = {
dim: (i + elided) - len(input_shape)
for i, dim in enumerate(input_spec)
}
# Because we've constructed the full output shape already, we don't need
# to do negative indexing.
output_dim_map = {
dim: (i + elided) for i, dim in enumerate(output_spec)
}
else:
input_dim_map = {dim: i for i, dim in enumerate(input_spec)}
output_dim_map = {dim: i for i, dim in enumerate(output_spec)}
for dim in input_spec:
input_shape_at_dim = input_shape[input_dim_map[dim]]
if dim in output_dim_map:
output_shape_at_dim = output_shape[output_dim_map[dim]]
if (
output_shape_at_dim is not None
and output_shape_at_dim != input_shape_at_dim
):
raise ValueError(
"Input shape and output shape do not match at shared "
f"dimension '{dim}'. Input shape is {input_shape_at_dim}, "
"and output shape "
f"is {output_shape[output_dim_map[dim]]}."
)
for dim in output_spec:
if dim not in input_spec and dim not in weight_spec:
raise ValueError(
f"Dimension '{dim}' was specified in the output "
f"'{output_spec}' but has no corresponding dim in the input "
f"spec '{input_spec}' or weight spec '{output_spec}'"
)
weight_shape = []
for dim in weight_spec:
if dim in input_dim_map:
weight_shape.append(input_shape[input_dim_map[dim]])
elif dim in output_dim_map:
weight_shape.append(output_shape[output_dim_map[dim]])
else:
raise ValueError(
f"Weight dimension '{dim}' did not have a match in either "
f"the input spec '{input_spec}' or the output "
f"spec '{output_spec}'. For this layer, the weight must "
"be fully specified."
)
if bias_axes is not None:
num_left_elided = elided if left_elided else 0
idx_map = {
char: output_shape[i + num_left_elided]
for i, char in enumerate(output_spec)
}
for char in bias_axes:
if char not in output_spec:
raise ValueError(
f"Bias dimension '{char}' was requested, but is not part "
f"of the output spec '{output_spec}'"
)
first_bias_location = min(
[output_spec.find(char) for char in bias_axes]
)
bias_output_spec = output_spec[first_bias_location:]
bias_shape = [
idx_map[char] if char in bias_axes else 1
for char in bias_output_spec
]
if not left_elided:
for _ in range(elided):
bias_shape.append(1)
else:
bias_shape = None
return weight_shape, bias_shape, output_shape
def _analyze_quantization_info(equation, input_shape):
"""Analyzes an einsum equation to derive information for quantization.
This function canonicalizes the einsum equation (handling ellipses) and
determines the necessary tensor manipulations (reduction, transposition,
expansion, squeezing) required to correctly apply per-axis quantization
to the inputs and kernel. It also derives the einsum equation needed for
the custom gradient.
Args:
equation: The einsum equation string.
input_shape: The shape of the input tensor.
Returns:
A tuple containing metadata for quantization operations:
`input_reduced_axes`: Axes to reduce for input quantization.
`kernel_reduced_axes`: Axes to reduce for kernel quantization.
`input_transpose_axes`: Permutation for transposing the input scale.
`kernel_transpose_axes`: Permutation for transposing the kernel scale.
`input_expand_axes`: Axes to expand for the input scale.
`kernel_expand_axes`: Axes to expand for the kernel scale.
`input_squeeze_axes`: Axes to squeeze from the input scale.
`kernel_squeeze_axes`: Axes to squeeze from the kernel scale.
`custom_gradient_equation`: Einsum equation for the backward pass.
`kernel_reverse_transpose_axes`: Permutation to reverse the kernel
scale transpose.
"""
def get_specs(equation, input_shape):
possible_labels = string.ascii_letters
dot_replaced_string = re.sub(r"\.\.\.", "0", equation)
# This is the case where no ellipses are present in the string.
split_string = re.match(
"([a-zA-Z]+),([a-zA-Z]+)->([a-zA-Z]+)", dot_replaced_string
)
if split_string is not None:
input_spec = split_string.group(1)
weight_spec = split_string.group(2)
output_spec = split_string.group(3)
return input_spec, weight_spec, output_spec
# This is the case where ellipses are present on the left.
split_string = re.match(
"0([a-zA-Z]+),([a-zA-Z]+)->0([a-zA-Z]+)", dot_replaced_string
)
if split_string is not None:
input_spec = split_string.group(1)
weight_spec = split_string.group(2)
output_spec = split_string.group(3)
elided = len(input_shape) - len(input_spec)
possible_labels = sorted(
set(possible_labels)
- set(input_spec)
- set(weight_spec)
- set(output_spec)
)
# Pad labels on the left to `input_spec` and `output_spec`
for i in range(elided):
input_spec = possible_labels[i] + input_spec
output_spec = possible_labels[i] + output_spec
return input_spec, weight_spec, output_spec
# This is the case where ellipses are present on the right.
split_string = re.match(
"([a-zA-Z]{2,})0,([a-zA-Z]+)->([a-zA-Z]+)0", dot_replaced_string
)
if split_string is not None:
input_spec = split_string.group(1)
weight_spec = split_string.group(2)
output_spec = split_string.group(3)
elided = len(input_shape) - len(input_spec)
possible_labels = sorted(
set(possible_labels)
- set(input_spec)
- set(weight_spec)
- set(output_spec)
)
# Pad labels on the right to `input_spec` and `output_spec`
for i in range(elided):
input_spec = input_spec + possible_labels[i]
output_spec = output_spec + possible_labels[i]
return input_spec, weight_spec, output_spec
raise ValueError(
f"Invalid einsum equation '{equation}'. Equations must be in the "
"form [X],[Y]->[Z], ...[X],[Y]->...[Z], or [X]...,[Y]->[Z]...."
)
input_spec, weight_spec, output_spec = get_specs(equation, input_shape)
# Determine the axes that should be reduced by the quantizer
input_reduced_axes = []
weight_reduced_axes = []
for i, label in enumerate(input_spec):
index = output_spec.find(label)
if index == -1:
input_reduced_axes.append(i)
for i, label in enumerate(weight_spec):
index = output_spec.find(label)
if index == -1:
weight_reduced_axes.append(i)
# Determine the axes of `ops.expand_dims`
input_expand_axes = []
weight_expand_axes = []
for i, label in enumerate(output_spec):
index_input = input_spec.find(label)
index_weight = weight_spec.find(label)
if index_input == -1:
input_expand_axes.append(i)
if index_weight == -1:
weight_expand_axes.append(i)
# Determine the axes of `ops.transpose`
input_transpose_axes = []
weight_transpose_axes = []
for i, label in enumerate(output_spec):
index_input = input_spec.find(label)
index_weight = weight_spec.find(label)
if index_input != -1:
input_transpose_axes.append(index_input)
if index_weight != -1:
weight_transpose_axes.append(index_weight)
# Postprocess the information:
# 1. Add dummy axes (1) to transpose_axes
# 2. Add axis to squeeze_axes if 1. failed
input_squeeze_axes = []
weight_squeeze_axes = []
for ori_index in input_reduced_axes:
try:
index = input_expand_axes.pop(0)
except IndexError:
input_squeeze_axes.append(ori_index)
input_transpose_axes.insert(index, ori_index)
for ori_index in weight_reduced_axes:
try:
index = weight_expand_axes.pop(0)
except IndexError:
weight_squeeze_axes.append(ori_index)
weight_transpose_axes.insert(index, ori_index)
# Prepare equation for `einsum_with_inputs_gradient`
custom_gradient_equation = f"{output_spec},{weight_spec}->{input_spec}"
weight_reverse_transpose_axes = [
i
for (_, i) in sorted(
(v, i) for (i, v) in enumerate(weight_transpose_axes)
)
]
return (
input_reduced_axes,
weight_reduced_axes,
input_transpose_axes,
weight_transpose_axes,
input_expand_axes,
weight_expand_axes,
input_squeeze_axes,
weight_squeeze_axes,
custom_gradient_equation,
weight_reverse_transpose_axes,
)
| EinsumDense |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 743221,
"end": 744295
} | class ____(sgqlc.types.Type, Node, RepositoryNode):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"description",
"emoji",
"emoji_html",
"is_answerable",
"name",
"slug",
"updated_at",
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
description = sgqlc.types.Field(String, graphql_name="description")
emoji = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="emoji")
emoji_html = sgqlc.types.Field(sgqlc.types.non_null(HTML), graphql_name="emojiHTML")
is_answerable = sgqlc.types.Field(
sgqlc.types.non_null(Boolean), graphql_name="isAnswerable"
)
name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name")
slug = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="slug")
updated_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="updatedAt"
)
| DiscussionCategory |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg.py | {
"start": 11020,
"end": 11196
} | class ____(PGIdentifierPreparer):
pass
def _log_notices(diagnostic):
logger.info("%s: %s", diagnostic.severity, diagnostic.message_primary)
| PGIdentifierPreparer_psycopg |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/daemon.py | {
"start": 10693,
"end": 12653
} | class ____(DagsterDaemon):
def __init__(self, settings: Mapping[str, Any]) -> None:
super().__init__()
self._exit_stack = ExitStack()
self._threadpool_executor: Optional[InheritContextThreadPoolExecutor] = None
self._submit_threadpool_executor: Optional[InheritContextThreadPoolExecutor] = None
if settings.get("use_threads"):
self._threadpool_executor = self._exit_stack.enter_context(
InheritContextThreadPoolExecutor(
max_workers=settings.get("num_workers"),
thread_name_prefix="sensor_daemon_worker",
)
)
num_submit_workers = settings.get("num_submit_workers")
if num_submit_workers:
self._submit_threadpool_executor = self._exit_stack.enter_context(
InheritContextThreadPoolExecutor(
max_workers=settings.get("num_submit_workers"),
thread_name_prefix="sensor_submit_worker",
)
)
def instrument_elapsed(
self, sensor: RemoteSensor, elapsed: Optional[float], min_interval: int
) -> None:
pass
@classmethod
def daemon_type(cls) -> str:
return "SENSOR"
def __exit__(self, _exception_type, _exception_value, _traceback):
self._exit_stack.close()
super().__exit__(_exception_type, _exception_value, _traceback)
def core_loop(
self,
workspace_process_context: IWorkspaceProcessContext,
shutdown_event: Event,
) -> DaemonIterator:
yield from execute_sensor_iteration_loop(
workspace_process_context,
self._logger,
shutdown_event,
threadpool_executor=self._threadpool_executor,
submit_threadpool_executor=self._submit_threadpool_executor,
instrument_elapsed=self.instrument_elapsed,
)
| SensorDaemon |
python | pydantic__pydantic | pydantic/types.py | {
"start": 57603,
"end": 58064
} | class ____(str, Enum):
amex = 'American Express'
mastercard = 'Mastercard'
visa = 'Visa'
other = 'other'
def __str__(self) -> str:
return self.value
@deprecated(
'The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead. '
'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_payment/#pydantic_extra_types.payment.PaymentCardNumber.',
category=PydanticDeprecatedSince20,
)
| PaymentCardBrand |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_polymorphic_rel.py | {
"start": 69337,
"end": 74816
} | class ____(
_PolymorphicTestBase, _PolymorphicPolymorphic
):
__dialect__ = "default"
def test_with_polymorphic_two_future_default_wp(self):
"""test #7262
compare to
test_with_polymorphic_two_future_adhoc_wp
"""
sess = fixture_session()
def go():
wp = with_polymorphic(Person, "*")
eq_(
sess.query(wp).order_by(wp.person_id).all(),
self._emps_wo_relationships_fixture(),
)
self.assert_sql_count(testing.db, go, 1)
def test_aliased_not_polluted_by_join(self):
# aliased(polymorphic) will normally do the old-school
# "(SELECT * FROM a JOIN b ...) AS anon_1" thing.
# this is the safest
sess = fixture_session()
palias = aliased(Person)
self.assert_compile(
sess.query(palias, Company.name)
.order_by(palias.person_id)
.join(Person, Company.employees)
.filter(palias.name == "dilbert"),
"SELECT anon_1.people_person_id AS anon_1_people_person_id, "
"anon_1.people_company_id AS anon_1_people_company_id, "
"anon_1.people_name AS anon_1_people_name, "
"anon_1.people_type AS anon_1_people_type, "
"anon_1.engineers_person_id AS anon_1_engineers_person_id, "
"anon_1.engineers_status AS anon_1_engineers_status, "
"anon_1.engineers_engineer_name AS anon_1_engineers_engineer_name, " # noqa
"anon_1.engineers_primary_language AS "
"anon_1_engineers_primary_language, "
"anon_1.managers_person_id AS anon_1_managers_person_id, "
"anon_1.managers_status AS anon_1_managers_status, "
"anon_1.managers_manager_name AS anon_1_managers_manager_name, "
"anon_1.boss_boss_id AS anon_1_boss_boss_id, "
"anon_1.boss_golf_swing AS anon_1_boss_golf_swing, "
"companies.name AS companies_name "
"FROM companies JOIN "
"(people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id "
"LEFT OUTER JOIN boss ON managers.person_id = boss.boss_id) "
"ON companies.company_id = people.company_id, "
"(SELECT people.person_id AS people_person_id, "
"people.company_id AS people_company_id, "
"people.name AS people_name, people.type AS people_type, "
"engineers.person_id AS engineers_person_id, "
"engineers.status AS engineers_status, "
"engineers.engineer_name AS engineers_engineer_name, "
"engineers.primary_language AS engineers_primary_language, "
"managers.person_id AS managers_person_id, "
"managers.status AS managers_status, "
"managers.manager_name AS managers_manager_name, "
"boss.boss_id AS boss_boss_id, "
"boss.golf_swing AS boss_golf_swing "
"FROM people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id LEFT OUTER JOIN boss "
"ON managers.person_id = boss.boss_id) AS anon_1 "
"WHERE anon_1.people_name = :people_name_1 "
"ORDER BY anon_1.people_person_id",
)
def test_flat_aliased_w_select_from(self):
sess = fixture_session()
palias = aliased(Person, flat=True)
self.assert_compile(
sess.query(palias, Company.name)
.select_from(palias)
.order_by(palias.person_id)
.join(Person, Company.employees)
.filter(palias.name == "dilbert"),
"SELECT people_1.person_id AS people_1_person_id, "
"people_1.company_id AS people_1_company_id, "
"people_1.name AS people_1_name, people_1.type AS people_1_type, "
"engineers_1.person_id AS engineers_1_person_id, "
"engineers_1.status AS engineers_1_status, "
"engineers_1.engineer_name AS engineers_1_engineer_name, "
"engineers_1.primary_language AS engineers_1_primary_language, "
"managers_1.person_id AS managers_1_person_id, "
"managers_1.status AS managers_1_status, "
"managers_1.manager_name AS managers_1_manager_name, "
"boss_1.boss_id AS boss_1_boss_id, "
"boss_1.golf_swing AS boss_1_golf_swing, "
"companies.name AS companies_name "
"FROM people AS people_1 "
"LEFT OUTER JOIN engineers AS engineers_1 "
"ON people_1.person_id = engineers_1.person_id "
"LEFT OUTER JOIN managers AS managers_1 "
"ON people_1.person_id = managers_1.person_id "
"LEFT OUTER JOIN boss AS boss_1 "
"ON managers_1.person_id = boss_1.boss_id, "
"companies JOIN (people LEFT OUTER JOIN engineers "
"ON people.person_id = engineers.person_id "
"LEFT OUTER JOIN managers "
"ON people.person_id = managers.person_id "
"LEFT OUTER JOIN boss ON managers.person_id = boss.boss_id) "
"ON companies.company_id = people.company_id "
"WHERE people_1.name = :name_1 ORDER BY people_1.person_id",
)
| PolymorphicPolymorphicTest |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_tk.py | {
"start": 40595,
"end": 40954
} | class ____(backend_tools.RubberbandBase):
def draw_rubberband(self, x0, y0, x1, y1):
NavigationToolbar2Tk.draw_rubberband(
self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1)
def remove_rubberband(self):
NavigationToolbar2Tk.remove_rubberband(
self._make_classic_style_pseudo_toolbar())
| RubberbandTk |
python | getsentry__sentry | src/sentry/auth_v2/endpoints/user_login_view.py | {
"start": 300,
"end": 541
} | class ____(AuthV2Endpoint):
owner = ApiOwner.ENTERPRISE
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request) -> Response:
return Response({"message": "Hello world"})
| UserLoginView |
python | crytic__slither | slither/slithir/operations/phi.py | {
"start": 530,
"end": 1686
} | class ____(OperationWithLValue):
def __init__(
self, left_variable: Union[LocalIRVariable, StateIRVariable], nodes: Set["Node"]
) -> None:
# When Phi operations are created the
# correct indexes of the variables are not yet computed
# We store the nodes where the variables are written
# so we can update the rvalues of the Phi operation
# after its instantiation
assert is_valid_lvalue(left_variable)
assert isinstance(nodes, set)
super().__init__()
self._lvalue = left_variable
self._rvalues = []
self._nodes = nodes
@property
def read(
self,
) -> List[
Union[SolidityVariableComposed, LocalIRVariable, TemporaryVariableSSA, StateIRVariable]
]:
return self.rvalues
@property
def rvalues(self):
return self._rvalues
@rvalues.setter
def rvalues(self, vals):
self._rvalues = vals
@property
def nodes(self) -> Set["Node"]:
return self._nodes
def __str__(self):
return f"{self.lvalue}({self.lvalue.type}) := \u03D5({[str(v) for v in self._rvalues]})"
| Phi |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 5324,
"end": 5525
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
return np.log(metafeatures.get_value("NumberOfFeatures"))
@helper_functions.define("MissingValues")
| LogNumberOfFeatures |
python | getsentry__sentry | tests/sentry/rules/history/test_preview.py | {
"start": 33563,
"end": 36007
} | class ____(TestCase, SnubaTestCase):
def test_get_first_seen(self) -> None:
prev_hour = timezone.now() - timedelta(hours=1)
two_hours = timezone.now() - timedelta(hours=2)
self.store_event(project_id=self.project.id, data={"timestamp": prev_hour.isoformat()})
event = self.store_event(
project_id=self.project.id, data={"timestamp": two_hours.isoformat()}
)
event.group.update(first_seen=two_hours)
activity = {
event.group.id: [
ConditionActivity(
group_id=event.group.id,
type=ConditionActivityType.CREATE_ISSUE,
timestamp=prev_hour,
)
]
}
events = get_events(
self.project,
activity,
{Dataset.Events: []},
timezone.now() - timedelta(weeks=2),
timezone.now(),
)
assert len(events) == 1
assert event.event_id in events
assert activity[event.group.id][0].data["event_id"] == event.event_id
def test_get_activity(self) -> None:
prev_hour = timezone.now() - timedelta(hours=1)
group = Group.objects.create(project=self.project)
regression_event = self.store_event(
project_id=self.project.id, data={"timestamp": prev_hour.isoformat()}
)
reappeared_event = self.store_event(
project_id=self.project.id, data={"timestamp": prev_hour.isoformat()}
)
activity = {
group.id: [
ConditionActivity(
group_id=group.id,
type=ConditionActivityType.REGRESSION,
timestamp=prev_hour,
data={"event_id": regression_event.event_id},
),
ConditionActivity(
group_id=group.id,
type=ConditionActivityType.REAPPEARED,
timestamp=prev_hour,
data={"event_id": reappeared_event.event_id},
),
]
}
events = get_events(
self.project,
activity,
{Dataset.Events: []},
timezone.now() - timedelta(weeks=2),
timezone.now(),
)
assert len(events) == 2
assert all([event.event_id in events for event in (regression_event, reappeared_event)])
| GetEventsTest |
python | getsentry__sentry | tests/sentry/integrations/slack/tasks/test_tasks.py | {
"start": 989,
"end": 20338
} | class ____(TestCase):
def setUp(self) -> None:
self.integration = install_slack(self.organization)
self.uuid = uuid4().hex
@pytest.fixture(autouse=True)
def mock_chat_scheduleMessage(self):
with mock_slack_response(
"chat_scheduleMessage",
body={"ok": True, "channel": "chan-id", "scheduled_message_id": "Q1298393284"},
) as self.mock_schedule:
yield
@pytest.fixture(autouse=True)
def mock_chat_deleteScheduledMessage(self):
with mock_slack_response(
"chat_deleteScheduledMessage", body={"ok": True}
) as self.mock_delete:
yield
def metric_alert_data(self):
return {
"aggregate": "count()",
"query": "",
"timeWindow": "300",
"resolveThreshold": 100,
"thresholdType": 0,
"triggers": [
{
"label": "critical",
"alertThreshold": 200,
"actions": [
{
"type": "slack",
"targetIdentifier": "my-channel",
"targetType": "specific",
"integration": self.integration.id,
}
],
},
],
"projects": [self.project.slug],
"owner": self.user.id,
"name": "New Rule",
"organization_id": self.organization.id,
}
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
def test_task_new_rule(self, mock_set_value: MagicMock) -> None:
data = {
"name": "New Rule",
"environment": None,
"project_id": self.project.id,
"action_match": "all",
"filter_match": "all",
"conditions": [
{"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}
],
"actions": [
{
"channel": "#my-channel",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
],
"frequency": 5,
"uuid": self.uuid,
"user_id": self.user.id,
}
with self.tasks():
find_channel_id_for_rule(**data)
rule = Rule.objects.exclude(label__in=[DEFAULT_RULE_LABEL]).get(project_id=self.project.id)
mock_set_value.assert_called_with("success", rule.id)
assert rule.label == "New Rule"
# check that the channel_id got added
assert rule.data["actions"] == [
{
"channel": "#my-channel",
"channel_id": "chan-id",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
]
assert rule.created_by_id == self.user.id
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
def test_task_new_rule_project_id(self, mock_set_value: MagicMock) -> None:
# Task should work if project_id is passed instead of project
data = {
"name": "New Rule",
"environment": None,
"project_id": self.project.id,
"action_match": "all",
"filter_match": "all",
"conditions": [
{"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}
],
"actions": [
{
"channel": "#my-channel",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
],
"frequency": 5,
"uuid": self.uuid,
"user_id": self.user.id,
}
with self.tasks():
find_channel_id_for_rule(**data)
rule = Rule.objects.exclude(label__in=[DEFAULT_RULE_LABEL]).get(project_id=self.project.id)
mock_set_value.assert_called_with("success", rule.id)
assert rule.label == "New Rule"
# check that the channel_id got added
assert rule.data["actions"] == [
{
"channel": "#my-channel",
"channel_id": "chan-id",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
]
assert rule.created_by_id == self.user.id
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
def test_task_new_rule_with_owner(self, mock_set_value: MagicMock) -> None:
"""Test that owner identifier string is deserialized to Actor correctly."""
team = self.create_team(organization=self.organization)
owner_identifier = f"team:{team.id}"
data = {
"name": "New Rule with Owner",
"environment": None,
"project_id": self.project.id,
"action_match": "all",
"filter_match": "all",
"conditions": [
{"id": "sentry.rules.conditions.first_seen_event.FirstSeenEventCondition"}
],
"actions": [
{
"channel": "#my-channel",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
],
"frequency": 5,
"uuid": self.uuid,
"user_id": self.user.id,
"owner": owner_identifier,
}
with self.tasks():
find_channel_id_for_rule(**data)
rule = Rule.objects.exclude(label__in=[DEFAULT_RULE_LABEL]).get(project_id=self.project.id)
mock_set_value.assert_called_with("success", rule.id)
assert rule.label == "New Rule with Owner"
assert rule.owner_team_id == team.id
assert rule.owner_user_id is None
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
def test_task_existing_rule(self, mock_set_value: MagicMock) -> None:
action_data = {"id": "sentry.rules.actions.notify_event.NotifyEventAction"}
condition_data = {"id": "sentry.rules.conditions.every_event.EveryEventCondition"}
rule = Rule.objects.create(
project=self.project, data={"actions": [action_data], "conditions": [condition_data]}
)
data = {
"name": "Test Rule",
"environment": None,
"project_id": self.project.id,
"action_match": "all",
"filter_match": "all",
"conditions": [condition_data],
"actions": [
{
"channel": "#my-channel",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
],
"frequency": 5,
"uuid": self.uuid,
"rule_id": rule.id,
}
with self.tasks():
find_channel_id_for_rule(**data)
updated_rule = Rule.objects.get(id=rule.id)
mock_set_value.assert_called_with("success", rule.id)
assert updated_rule.label == "Test Rule"
# check that the channel_id got added
assert updated_rule.data["actions"] == [
{
"channel": "#my-channel",
"channel_id": "chan-id",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
]
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
def test_task_existing_rule_with_owner(self, mock_set_value: MagicMock) -> None:
"""Test that owner identifier string is deserialized to Actor correctly during update."""
action_data = {"id": "sentry.rules.actions.notify_event.NotifyEventAction"}
condition_data = {"id": "sentry.rules.conditions.every_event.EveryEventCondition"}
rule = Rule.objects.create(
project=self.project, data={"actions": [action_data], "conditions": [condition_data]}
)
owner_identifier = f"user:{self.user.id}"
data = {
"name": "Updated Rule with Owner",
"environment": None,
"project_id": self.project.id,
"action_match": "all",
"filter_match": "all",
"conditions": [condition_data],
"actions": [
{
"channel": "#my-channel",
"id": "sentry.integrations.slack.notify_action.SlackNotifyServiceAction",
"tags": "",
"workspace": self.integration.id,
}
],
"frequency": 5,
"uuid": self.uuid,
"rule_id": rule.id,
"owner": owner_identifier,
}
with self.tasks():
find_channel_id_for_rule(**data)
updated_rule = Rule.objects.get(id=rule.id)
mock_set_value.assert_called_with("success", rule.id)
assert updated_rule.label == "Updated Rule with Owner"
assert updated_rule.owner_user_id == self.user.id
assert updated_rule.owner_team_id is None
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", "chan-id", False),
)
def test_task_new_alert_rule(
self, mock_get_channel_id: MagicMock, mock_set_value: MagicMock
) -> None:
alert_rule_data = self.metric_alert_data()
data = {
"data": alert_rule_data,
"uuid": self.uuid,
"organization_id": self.organization.id,
"user_id": self.user.id,
}
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(**data)
rule = AlertRule.objects.get(name="New Rule")
assert rule.created_by_id == self.user.id
mock_set_value.assert_called_with("success", rule.id)
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration), "my-channel", 180
)
trigger_action = AlertRuleTriggerAction.objects.get(integration_id=self.integration.id)
assert trigger_action.target_identifier == "chan-id"
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", None, False),
)
def test_task_failed_id_lookup(
self, mock_get_channel_id: MagicMock, mock_set_value: MagicMock
) -> None:
alert_rule_data = self.metric_alert_data()
data = {
"data": alert_rule_data,
"uuid": self.uuid,
"organization_id": self.organization.id,
}
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(**data)
assert not AlertRule.objects.filter(name="New Rule").exists()
mock_set_value.assert_called_with("failed")
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration), "my-channel", 180
)
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", None, True),
)
def test_task_timeout_id_lookup(
self, mock_get_channel_id: MagicMock, mock_set_value: MagicMock
) -> None:
alert_rule_data = self.metric_alert_data()
data = {
"data": alert_rule_data,
"uuid": self.uuid,
"organization_id": self.organization.id,
}
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(**data)
assert not AlertRule.objects.filter(name="New Rule").exists()
mock_set_value.assert_called_with("failed")
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration), "my-channel", 180
)
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", "channel", False),
)
@patch(
"sentry.integrations.slack.tasks.find_channel_id_for_alert_rule.AlertRuleSerializer",
side_effect=Exception("something broke!"),
)
def test_task_encounters_serialization_exception(
self, mock_serializer, mock_get_channel_id, mock_set_value
):
data = self.metric_alert_data()
# Ensure this field is removed, to avoid known serialization issue
data["triggers"][0]["actions"][0]["inputChannelId"] = ""
# Catch the exception we've side-effected in the serializer
with pytest.raises(Exception, match="something broke!"):
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(
data=data,
uuid=self.uuid,
organization_id=self.organization.id,
user_id=self.user.id,
)
assert not AlertRule.objects.filter(name="New Rule").exists()
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration),
data["triggers"][0]["actions"][0]["targetIdentifier"],
180,
)
# Ensure the field has been removed
assert "inputChannelId" not in data["triggers"][0]["actions"][0]
mock_serializer.assert_called_with(context=ANY, data=data, instance=ANY)
# If we failed at serialization, don't stay in pending.
mock_set_value.assert_called_with("failed")
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", "chan-id", False),
)
def test_task_existing_metric_alert(
self, mock_get_channel_id: MagicMock, mock_set_value: MagicMock
) -> None:
alert_rule_data = self.metric_alert_data()
alert_rule = self.create_alert_rule(
organization=self.organization, projects=[self.project], name="New Rule", user=self.user
)
data = {
"data": alert_rule_data,
"uuid": self.uuid,
"organization_id": self.organization.id,
"alert_rule_id": alert_rule.id,
}
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(**data)
rule = AlertRule.objects.get(name="New Rule")
mock_set_value.assert_called_with("success", rule.id)
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration), "my-channel", 180
)
trigger_action = AlertRuleTriggerAction.objects.get(integration_id=self.integration.id)
assert trigger_action.target_identifier == "chan-id"
assert AlertRule.objects.get(id=alert_rule.id)
@responses.activate
@patch.object(RedisRuleStatus, "set_value", return_value=None)
@patch(
"sentry.integrations.slack.utils.channel.get_channel_id_with_timeout",
return_value=SlackChannelIdData("#", "chan-id", False),
)
def test_task_existing_metric_alert_with_sdk(
self, mock_get_channel_id: MagicMock, mock_set_value: MagicMock
) -> None:
alert_rule_data = self.metric_alert_data()
alert_rule = self.create_alert_rule(
organization=self.organization, projects=[self.project], name="New Rule", user=self.user
)
data = {
"data": alert_rule_data,
"uuid": self.uuid,
"organization_id": self.organization.id,
"alert_rule_id": alert_rule.id,
}
with self.tasks():
with self.feature(["organizations:incidents"]):
find_channel_id_for_alert_rule(**data)
rule = AlertRule.objects.get(name="New Rule")
mock_set_value.assert_called_with("success", rule.id)
mock_get_channel_id.assert_called_with(
serialize_integration(self.integration), "my-channel", 180
)
trigger_action = AlertRuleTriggerAction.objects.get(integration_id=self.integration.id)
assert trigger_action.target_identifier == "chan-id"
assert AlertRule.objects.get(id=alert_rule.id)
@patch("sentry.integrations.slack.sdk_client.metrics")
@patch("slack_sdk.web.client.WebClient._perform_urllib_http_request")
@responses.activate
def test_post_message_success(self, mock_api_call: MagicMock, mock_metrics: MagicMock) -> None:
mock_api_call.return_value = {
"body": orjson.dumps({"ok": True}).decode(),
"headers": {},
"status": 200,
}
with self.tasks():
post_message.apply_async(
kwargs={
"integration_id": self.integration.id,
"payload": {"blocks": ["hello"], "text": "text", "channel": "channel"},
"log_error_message": "my_message",
"log_params": {"log_key": "log_value"},
}
)
mock_metrics.incr.assert_called_with(
SLACK_DATADOG_METRIC,
sample_rate=1.0,
tags={"ok": True, "status": 200},
)
@patch("sentry.integrations.slack.sdk_client.metrics")
@responses.activate
def test_post_message_failure_sdk(self, mock_metrics: MagicMock) -> None:
with self.tasks():
post_message.apply_async(
kwargs={
"integration_id": self.integration.id,
"payload": {
"blocks": ["hello"],
"text": "text",
"channel": "channel",
"callback_id": "123",
},
"log_error_message": "my_message",
"log_params": {"log_key": "log_value"},
}
)
mock_metrics.incr.assert_called_with(
SLACK_DATADOG_METRIC,
sample_rate=1.0,
tags={"ok": False, "status": 200},
)
| SlackTasksTest |
python | sympy__sympy | bin/test_optional_dependencies.py | {
"start": 276,
"end": 2802
} | class ____(Exception):
pass
test_list = [
# numpy
'*numpy*',
'sympy/core/',
'sympy/matrices/',
'sympy/physics/quantum/',
'sympy/utilities/tests/test_lambdify.py',
'sympy/physics/control/',
# scipy
'*scipy*',
# matplotlib
'sympy/plotting/',
# llvmlite
'*llvm*',
# jax
'*jax*',
# gmpy
'sympy/ntheory',
'sympy/polys',
# gmpy, numpy, scipy, autowrap, matplotlib
'sympy/external',
# autowrap
'*autowrap*',
# ipython
'*ipython*',
# antlr, lfortran, clang
'sympy/parsing/',
# codegen
'sympy/codegen/',
'sympy/utilities/tests/test_codegen',
'sympy/utilities/_compilation/tests/test_compilation',
'sympy/external/tests/test_codegen.py',
# cloudpickle
'pickling',
# pycosat
'sympy/logic',
'sympy/assumptions',
# stats
'sympy/stats',
# lxml
"sympy/utilities/tests/test_mathml.py",
]
blacklist = [
'sympy/physics/quantum/tests/test_circuitplot.py',
]
doctest_list = [
# numpy
'sympy/matrices/',
'sympy/utilities/lambdify.py',
# scipy
'*scipy*',
# matplotlib
'sympy/plotting/',
# llvmlite
'*llvm*',
# gmpy
'sympy/ntheory',
'sympy/polys',
# autowrap
'*autowrap*',
# ipython
'*ipython*',
# antlr, lfortran, clang
'sympy/parsing/',
# codegen
'sympy/codegen/',
# pycosat
'sympy/logic',
'sympy/assumptions',
#stats
'sympy/stats',
# lxml
"sympy/utilities/mathml/",
]
# This is just needed for the numpy nightly job which does not have matplotlib
# Otherwise these could be added to doctest_list above
try:
import matplotlib # noqa: F401
doctest_list.extend([
'doc/src/tutorials/biomechanics/biomechanical-model-example.rst',
'doc/src/tutorials/biomechanics/biomechanics.rst',
])
except ImportError:
pass
print('Testing optional dependencies')
from sympy import test, doctest
tests_passed = test(*test_list, blacklist=blacklist, force_colors=True)
if tests_passed is True:
tests_passed = pytest.ExitCode.OK
doctests_passed = doctest(*doctest_list, force_colors=True)
if (tests_passed != pytest.ExitCode.OK) and not doctests_passed:
raise TestsFailedError('Tests and doctests failed')
elif tests_passed != pytest.ExitCode.OK:
raise TestsFailedError('Doctests passed but tests failed')
elif not doctests_passed:
raise TestsFailedError('Tests passed but doctests failed')
| TestsFailedError |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 40706,
"end": 41859
} | class ____(ColumnConstraint):
"""A column constraint that ensures all values in a pandas column are unique.
Args:
ignore_missing_vals (bool): If true, this constraint will enforce the constraint on non missing values.
"""
def __init__(self, ignore_missing_vals):
description = "Column must be unique."
self.ignore_missing_vals = check.bool_param(ignore_missing_vals, "ignore_missing_vals")
super().__init__(error_description=description, markdown_description=description)
def validate(self, dataframe, column_name):
invalid = dataframe[column_name].duplicated()
if self.ignore_missing_vals:
invalid = apply_ignore_missing_data_to_mask(invalid, dataframe[column_name])
rows_with_duplicated_values = dataframe[invalid]
if not rows_with_duplicated_values.empty:
raise ColumnConstraintViolationException(
constraint_name=self.name,
constraint_description=self.error_description,
column_name=column_name,
offending_rows=rows_with_duplicated_values,
)
| UniqueColumnConstraint |
python | pytorch__pytorch | torch/ao/quantization/observer.py | {
"start": 65286,
"end": 65865
} | class ____(Granularity):
"""
Represents per-channel group granularity in quantization.
This granularity type calculates different quantization parameters
for each group of <group_size> elements.
For example if the input tensor is shape [8, 16], and the group size is 4, then
the input tensor is reshaped to [64, 4]
quantization parameters are calculated for each group of 4 elements,
giving a total of 64 quantization parameters.
Attributes:
group_size (int): The size of each quantization group
"""
group_size: int
| PerGroup |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 990,
"end": 1111
} | class ____(BaseModel):
class Config:
extra = 1 # type: ignore[pydantic-config]
extra = 1
| BadExtraModel |
python | great-expectations__great_expectations | great_expectations/core/data_context_key.py | {
"start": 2073,
"end": 2502
} | class ____(DataContextKey):
"""A simple DataContextKey with just a single string value"""
def __init__(self, key) -> None:
self._key = key
@override
def to_tuple(self):
return (self._key,)
@override
def to_fixed_length_tuple(self):
return self.to_tuple()
@classmethod
@override
def from_fixed_length_tuple(cls, tuple_):
return cls.from_tuple(tuple_)
| StringKey |
python | joke2k__faker | faker/providers/date_time/nl_NL/__init__.py | {
"start": 46,
"end": 782
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "zondag",
"1": "maandag",
"2": "dinsdag",
"3": "woensdag",
"4": "donderdag",
"5": "vrijdag",
"6": "zaterdag",
}
MONTH_NAMES = {
"01": "januari",
"02": "februari",
"03": "maart",
"04": "april",
"05": "mei",
"06": "juni",
"07": "juli",
"08": "augustus",
"09": "september",
"10": "oktober",
"11": "november",
"12": "december",
}
def day_of_week(self):
day = self.date("%w")
return self.DAY_NAMES[day]
def month_name(self):
month = self.month()
return self.MONTH_NAMES[month]
| Provider |
python | tensorflow__tensorflow | tensorflow/python/ops/io_ops.py | {
"start": 14749,
"end": 15675
} | class ____(ReaderBase):
"""A Reader that outputs the entire contents of a file as a value.
To use, enqueue filenames in a Queue. The output of Read will
be a filename (key) and the contents of that file (value).
See ReaderBase for supported methods.
@compatibility(eager)
Readers are not compatible with eager execution. Instead, please
use `tf.data` to get data into your model.
@end_compatibility
"""
@deprecation.deprecated(
None, "Queue-based input pipelines have been replaced by `tf.data`. Use "
"`tf.data.Dataset.map(tf.read_file)`.")
def __init__(self, name=None):
"""Create a WholeFileReader.
Args:
name: A name for the operation (optional).
"""
rr = gen_io_ops.whole_file_reader_v2(name=name)
super(WholeFileReader, self).__init__(rr, supports_serialize=True)
ops.NotDifferentiable("WholeFileReader")
@tf_export(v1=["TextLineReader"])
| WholeFileReader |
python | pennersr__django-allauth | allauth/mfa/webauthn/views.py | {
"start": 3616,
"end": 4691
} | class ____(RedirectAuthenticatedUserMixin, FormView):
form_class = LoginWebAuthnForm
def get(self, request, *args, **kwargs):
if get_account_adapter().is_ajax(request):
request_options = auth.begin_authentication(user=None)
data = {"request_options": request_options}
return JsonResponse(data)
return HttpResponseRedirect(reverse("account_login"))
def form_invalid(self, form):
for message in form.errors.get("credential", []):
get_account_adapter().add_message(
self.request, messages.ERROR, message=message
)
return HttpResponseRedirect(reverse("account_login"))
def form_valid(self, form):
authenticator = form.cleaned_data["credential"]
redirect_url = None
login = Login(user=authenticator.user, redirect_url=redirect_url)
return flows.perform_passwordless_login(self.request, authenticator, login)
login_webauthn = LoginWebAuthnView.as_view()
@method_decorator(login_required, name="dispatch")
| LoginWebAuthnView |
python | coleifer__peewee | tests/regressions.py | {
"start": 34446,
"end": 34864
} | class ____(ModelTestCase):
requires = [NoPK]
def test_no_pk_hash_regression(self):
npk = NoPK.create(data=1)
npk_db = NoPK.get(NoPK.data == 1)
# When a model does not define a primary key, we cannot test equality.
self.assertTrue(npk != npk_db)
# Their hash is the same, though they are not equal.
self.assertEqual(hash(npk), hash(npk_db))
| TestNoPKHashRegression |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 58357,
"end": 59070
} | class ____(_LoopTypesTester):
_ufuncs = [np.reciprocal] # issue #757
_required_types = 'bBhHiIlLqQfdFD'
_skip_types = 'mMO' + _LoopTypesTester._skip_types
def _arg_for_type(self, a_letter_type, index=0):
res = super(self.__class__, self)._arg_for_type(a_letter_type,
index=index)
if a_letter_type in 'bBhHiIlLqQ':
# For integer reciprocal, avoid 0 as argument, as it triggers
# undefined behavior that may differ in results from Numba
# to the compiler used to compile NumPy.
res[res == 0] = 42
return res
TestLoopTypesReciprocal.autogenerate()
| TestLoopTypesReciprocal |
python | pytorch__pytorch | test/dynamo/test_streams.py | {
"start": 868,
"end": 15635
} | class ____(torch._dynamo.test_case.TestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
@classmethod
def tearDownClass(cls):
super().tearDownClass()
@requires_cuda
def test_stream_weakref(self):
s = torch.Stream()
weakref.ref(s)
@requires_cuda
def test_event_weakref(self):
e = torch.Event()
weakref.ref(e)
@requires_cuda
def test_stream_enter_exit(self):
def fn(x, y, s1, s2):
with s1:
z1 = torch.add(x, y)
with s2:
z = torch.add(x, y)
y = z + 2 + z1
return y
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2), torch.Stream(), torch.Stream())
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
class <lambda>(torch.nn.Module):
def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2, 2]"):
# Annotation: {'stream': 0}
add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1)
# Annotation: {'stream': 1}
add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1); arg0_1 = arg1_1 = None
# Annotation: {'stream': 1}
add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_1, 2); add_1 = None
add_3: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_2, add); add_2 = add = None
return (add_3,)
""",
)
@requires_cuda
@unittest.skip("Needs graph break support with annotation context")
def test_stream_context_graph_break(self):
def fn(x, y):
s2 = torch.Stream()
s1 = torch.Stream()
with s1:
z1 = torch.add(x, y)
with s2:
z = torch.add(x, y)
y = z + 2 + z1
torch._dynamo.graph_break()
y = y + 1
return y
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2))
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(expected, actual)
self.assertEqual(len(fw_graphs), 2)
self.assertExpectedInline(print_graph(fw_graphs[0]), """""")
self.assertExpectedInline(print_graph(fw_graphs[1]), """""")
@requires_cuda
def test_stream_input(self):
def fn(x, y, s):
z = torch.add(x, y)
y = z + 2
return y, s
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2), torch.Stream(device="cuda"))
expected = fn(*inp)
fn_opt = torch.compile(fn, fullgraph=True)
actual = fn_opt(*inp)
self.assertEqual(expected, actual)
@requires_cuda
def test_local_stream_return(self):
def fn(x, y):
s = torch.Stream()
z = torch.add(x, y)
y = z + 2
return y, s
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2))
fn_opt = torch.compile(fn, fullgraph=True)
_, s0 = fn_opt(*inp)
_, s1 = fn_opt(*inp)
# Streams will be different values for each invocation
# so don't check for equality
self.assertIsInstance(s0, torch.Stream)
# Stream should be newly allocated on each call
self.assertNotEqual(s0, s1)
@requires_cuda
def test_get_current_stream_return(self):
def fn(x, s):
with s:
s0 = torch.accelerator.current_stream()
return x, s0
s_inp = torch.Stream(device="cuda")
inp = (torch.ones(2, 2) + 1, s_inp)
fn_opt = torch.compile(fn, fullgraph=True)
_, s0 = fn_opt(*inp)
_, s1 = fn_opt(*inp)
self.assertEqual(s_inp, s0)
self.assertEqual(s0, s1)
@requires_cuda
@requires_multigpu()
def test_get_current_stream_return_different_device(self):
def fn(x, s0, s1):
with s1:
with s0:
s = torch.accelerator.current_stream(torch.device("cuda:1"))
return s
s0 = torch.Stream(device="cuda:0")
s1 = torch.Stream(device="cuda:1")
inp = (torch.ones(2, 2) + 1, s0, s1)
fn_opt = torch.compile(fn, fullgraph=True)
s_act = fn_opt(*inp)
s_exp = fn(*inp)
self.assertEqual(s_act, s_exp)
@requires_cuda
@requires_multigpu()
def test_get_current_stream_return_no_index(self):
def fn(x, s0, s1):
with s1:
with s0:
s = torch.accelerator.current_stream(torch.device("cuda"))
return s
s0 = torch.Stream(device="cuda:0")
s1 = torch.Stream(device="cuda:1")
inp = (torch.ones(2, 2) + 1, s0, s1)
fn_opt = torch.compile(fn, fullgraph=True)
s_act = fn_opt(*inp)
s_exp = fn(*inp)
self.assertEqual(s_act, s_exp)
@requires_cuda
def test_nested_stream_enter_exit(self):
def fn(x, y, s0, s1, s2):
with s1:
with s2:
z1 = torch.add(x, y)
with s0:
z0 = torch.add(x, y)
with s2:
y = 2 + z1
return z0, y
inp = (
torch.ones(2, 2) + 1,
torch.ones(2, 2),
torch.Stream(),
torch.Stream(),
torch.Stream(),
)
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
class <lambda>(torch.nn.Module):
def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2, 2]"):
# Annotation: {'stream': 1}
add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1)
# Annotation: {'stream': 2}
add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1); arg0_1 = arg1_1 = None
# Annotation: {'stream': 1}
add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(add, 2); add = None
return (add_1, add_2)
""",
)
@unittest.skip("Needs graph break support with annotation context")
def test_stream_enter_exit_graph_break(self):
pass
@unittest.skip("Needs graph break support with annotation context")
def test_nested_stream_enter_exit_graph_break(self):
pass
@requires_cuda
def test_local_stream_enter_exit(self):
def fn(x, y):
s2 = torch.Stream()
s1 = torch.Stream()
with s1:
z1 = torch.add(x, y)
with s2:
z = torch.add(x, y)
y = z + 2 + z1
return y
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2))
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
class <lambda>(torch.nn.Module):
def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2, 2]"):
# Annotation: {'stream': 1}
add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1)
# Annotation: {'stream': 0}
add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1); arg0_1 = arg1_1 = None
# Annotation: {'stream': 0}
add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_1, 2); add_1 = None
add_3: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_2, add); add_2 = add = None
return (add_3,)
""",
)
@requires_cuda
def test_local_stream_nested_enter_exit(self):
def fn(x, y):
s2 = torch.Stream()
s1 = torch.Stream()
s0 = torch.Stream()
with s1:
with s2:
z1 = torch.add(x, y)
with s0:
z0 = torch.add(x, y)
with s2:
y = 2 + z1
return z0, y
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2))
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
class <lambda>(torch.nn.Module):
def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2, 2]"):
# Annotation: {'stream': 0}
add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1)
# Annotation: {'stream': 2}
add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1); arg0_1 = arg1_1 = None
# Annotation: {'stream': 0}
add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(add, 2); add = None
return (add_1, add_2)
""",
)
@requires_cuda
@requires_multigpu()
def test_new_event_api(self) -> None:
from torch._dynamo.graph_bytecode_inputs import get_external_object_by_index
from torch._dynamo.variables.streams import new_event
def event_generation_backend(gm, *args, **kwargs): # type: ignore[no-untyped-def]
e0_ind = new_event()
with torch.Stream(device="cuda:1"):
get_external_object_by_index(e0_ind).record()
e1_ind = new_event()
self.assertNotEqual(e0_ind, e1_ind)
self.assertNotEqual(
get_external_object_by_index(e0_ind),
get_external_object_by_index(e1_ind),
)
with gm.graph.inserting_after(next(iter(gm.graph.nodes))):
gm.graph.call_function(
get_external_object_by_index, args=(1,), kwargs={}
)
return gm
@torch.compile(backend=event_generation_backend)
def fn(x):
return x + 1
fn(torch.ones(2, 2, device="cuda:0"))
@requires_cuda
def test_new_stream_api(self) -> None:
from torch._dynamo.graph_bytecode_inputs import get_external_object_by_index
from torch._dynamo.variables.streams import new_stream
def stream_generation_backend(gm, *args, **kwargs): # type: ignore[no-untyped-def]
s0_ind = new_stream()
s1_ind = new_stream()
self.assertNotEqual(s0_ind, s1_ind)
self.assertNotEqual(
get_external_object_by_index(s0_ind),
get_external_object_by_index(s1_ind),
)
with gm.graph.inserting_after(next(iter(gm.graph.nodes))):
gm.graph.call_function(
get_external_object_by_index, args=(1,), kwargs={}
)
return gm
@torch.compile(backend=stream_generation_backend)
def fn(x):
return x + 1
fn(torch.ones(2, 2, device="cuda:0"))
@requires_cuda
def test_current_stream_api(self) -> None:
from torch._dynamo.graph_bytecode_inputs import get_external_object_by_index
from torch._dynamo.variables.streams import get_current_stream
cur_stream = torch.accelerator.current_stream()
s0 = None
def stream_generation_backend(gm, *args, **kwargs): # type: ignore[no-untyped-def]
nonlocal s0
s0_ind = get_current_stream(torch.device("cuda:0"))
self.assertEqual(get_external_object_by_index(s0_ind), cur_stream)
with gm.graph.inserting_after(next(iter(gm.graph.nodes))):
gm.graph.call_function(
get_external_object_by_index, args=(s0_ind,), kwargs={}
)
gm.graph.call_function(
lambda x: self.assertEqual(
cur_stream, get_external_object_by_index(x)
),
args=(s0_ind,),
kwargs={},
)
return gm
@torch.compile(backend=stream_generation_backend)
def fn(x):
return x + 1
fn(torch.ones(2, 2, device="cuda:0"))
@requires_cuda
def test_stream_with_mutation(self):
def fn(x, y):
s2 = torch.Stream()
s1 = torch.Stream()
s0 = torch.Stream()
with s1:
with s2:
x.add_(y)
with s0:
z1 = torch.add(y, y)
z0 = torch.add(z1, y)
with s2:
y = 2 + z1
return z0, y
inp = (torch.ones(2, 2) + 1, torch.ones(2, 2))
expected = fn(*inp)
(
actual,
_,
fw_graphs,
_,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
class <lambda>(torch.nn.Module):
def forward(self, arg0_1: "f32[2, 2]", arg1_1: "f32[2, 2]"):
# Annotation: {'stream': 0}
add: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg0_1, arg1_1)
# Annotation: {'stream': 2}
add_1: "f32[2, 2]" = torch.ops.aten.add.Tensor(arg1_1, arg1_1)
# Annotation: {'stream': 2}
add_2: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_1, arg1_1); arg1_1 = None
# Annotation: {'stream': 0}
add_3: "f32[2, 2]" = torch.ops.aten.add.Tensor(add_1, 2); add_1 = None
#
copy_: "f32[2, 2]" = torch.ops.aten.copy_.default(arg0_1, add); arg0_1 = add = copy_ = None
return (add_2, add_3)
""",
)
@requires_cuda
def test_stream_backward_simple(self) -> None:
def fn(x, y):
s2 = torch.Stream()
s0 = torch.Stream()
with s0:
y0 = 2 * x + y
with s2:
z = 2 * x + y
return y0, z
inp = (
torch.ones(2, 2, requires_grad=True) + 1,
torch.ones(2, 2, requires_grad=True),
)
expected = fn(*inp)
(
actual,
_,
fw_graphs,
bw_graphs,
) = extract_graph(fn, *inp)
self.assertEqual(len(fw_graphs), 1)
self.assertEqual(expected, actual)
self.assertExpectedInline(
print_graph(fw_graphs[0]),
"""\
| TestStreams |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/traversals.py | {
"start": 2069,
"end": 5929
} | class ____(HasTraverseInternals):
"""attribute-wide operations that are useful for classes that use
__slots__ and therefore can't operate on their attributes in a dictionary.
"""
__slots__ = ()
if typing.TYPE_CHECKING:
def _generated_shallow_copy_traversal(self, other: Self) -> None: ...
def _generated_shallow_from_dict_traversal(
self, d: Dict[str, Any]
) -> None: ...
def _generated_shallow_to_dict_traversal(self) -> Dict[str, Any]: ...
@classmethod
def _generate_shallow_copy(
cls,
internal_dispatch: _TraverseInternalsType,
method_name: str,
) -> Callable[[Self, Self], None]:
code = "\n".join(
f" other.{attrname} = self.{attrname}"
for attrname, _ in internal_dispatch
)
meth_text = f"def {method_name}(self, other):\n{code}\n"
return langhelpers._exec_code_in_env(meth_text, {}, method_name)
@classmethod
def _generate_shallow_to_dict(
cls,
internal_dispatch: _TraverseInternalsType,
method_name: str,
) -> Callable[[Self], Dict[str, Any]]:
code = ",\n".join(
f" '{attrname}': self.{attrname}"
for attrname, _ in internal_dispatch
)
meth_text = f"def {method_name}(self):\n return {{{code}}}\n"
return langhelpers._exec_code_in_env(meth_text, {}, method_name)
@classmethod
def _generate_shallow_from_dict(
cls,
internal_dispatch: _TraverseInternalsType,
method_name: str,
) -> Callable[[Self, Dict[str, Any]], None]:
code = "\n".join(
f" self.{attrname} = d['{attrname}']"
for attrname, _ in internal_dispatch
)
meth_text = f"def {method_name}(self, d):\n{code}\n"
return langhelpers._exec_code_in_env(meth_text, {}, method_name)
def _shallow_from_dict(self, d: Dict[str, Any]) -> None:
cls = self.__class__
shallow_from_dict: Callable[[HasShallowCopy, Dict[str, Any]], None]
try:
shallow_from_dict = cls.__dict__[
"_generated_shallow_from_dict_traversal"
]
except KeyError:
shallow_from_dict = self._generate_shallow_from_dict(
cls._traverse_internals,
"_generated_shallow_from_dict_traversal",
)
cls._generated_shallow_from_dict_traversal = shallow_from_dict # type: ignore # noqa: E501
shallow_from_dict(self, d)
def _shallow_to_dict(self) -> Dict[str, Any]:
cls = self.__class__
shallow_to_dict: Callable[[HasShallowCopy], Dict[str, Any]]
try:
shallow_to_dict = cls.__dict__[
"_generated_shallow_to_dict_traversal"
]
except KeyError:
shallow_to_dict = self._generate_shallow_to_dict(
cls._traverse_internals, "_generated_shallow_to_dict_traversal"
)
cls._generated_shallow_to_dict_traversal = shallow_to_dict # type: ignore # noqa: E501
return shallow_to_dict(self)
def _shallow_copy_to(self, other: Self) -> None:
cls = self.__class__
shallow_copy: Callable[[Self, Self], None]
try:
shallow_copy = cls.__dict__["_generated_shallow_copy_traversal"]
except KeyError:
shallow_copy = self._generate_shallow_copy(
cls._traverse_internals, "_generated_shallow_copy_traversal"
)
cls._generated_shallow_copy_traversal = shallow_copy # type: ignore # noqa: E501
shallow_copy(self, other)
def _clone(self, **kw: Any) -> Self:
"""Create a shallow copy"""
c = self.__class__.__new__(self.__class__)
self._shallow_copy_to(c)
return c
| HasShallowCopy |
python | Textualize__textual | tests/input/test_input_key_movement_actions.py | {
"start": 177,
"end": 6772
} | class ____(App[None]):
"""Input widget testing app."""
def compose(self) -> ComposeResult:
for value, input_id in (
("", "empty"),
("Shiny", "single-word"),
("Curse your sudden but inevitable betrayal", "multi-no-punctuation"),
(
"We have done the impossible, and that makes us mighty.",
"multi-punctuation",
),
("Long as she does it quiet-like", "multi-and-hyphenated"),
):
yield Input(value, id=input_id)
async def test_input_home() -> None:
"""Going home should always land at position zero."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_home()
assert input.cursor_position == 0
async def test_input_end() -> None:
"""Going end should always land at the last position."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_end()
assert input.cursor_position == len(input.value)
async def test_input_right_from_home() -> None:
"""Going right should always land at the next position, if there is one."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.cursor_position = 0
input.action_cursor_right()
assert input.cursor_position == (1 if input.value else 0)
async def test_input_right_from_end() -> None:
"""Going right should always stay put if doing so from the end."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_end()
input.action_cursor_right()
assert input.cursor_position == len(input.value)
async def test_input_left_from_home() -> None:
"""Going left from home should stay put."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.cursor_position = 0
input.action_cursor_left()
assert input.cursor_position == 0
async def test_input_left_from_end() -> None:
"""Going left from the end should go back one place, where possible."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_end()
input.action_cursor_left()
assert input.cursor_position == (len(input.value) - 1 if input.value else 0)
async def test_input_left_word_from_home() -> None:
"""Going left one word from the start should do nothing."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.cursor_position = 0
input.action_cursor_left_word()
assert input.cursor_position == 0
async def test_input_left_word_from_end() -> None:
"""Going left one word from the end should land correctly.."""
async with InputTester().run_test() as pilot:
expected_at: dict[str | None, int] = {
"empty": 0,
"single-word": 0,
"multi-no-punctuation": 33,
"multi-punctuation": 47,
"multi-and-hyphenated": 26,
}
for input in pilot.app.query(Input):
input.action_end()
input.action_cursor_left_word()
assert input.cursor_position == expected_at[input.id]
async def test_password_input_left_word_from_end() -> None:
"""Going left one word from the end in a password field should land at home."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_end()
input.password = True
input.action_cursor_left_word()
assert input.cursor_position == 0
async def test_input_right_word_from_home() -> None:
"""Going right one word from the start should land correctly.."""
async with InputTester().run_test() as pilot:
expected_at: dict[str | None, int] = {
"empty": 0,
"single-word": 5,
"multi-no-punctuation": 6,
"multi-punctuation": 3,
"multi-and-hyphenated": 5,
}
for input in pilot.app.query(Input):
input.cursor_position = 0
input.action_cursor_right_word()
assert input.cursor_position == expected_at[input.id]
async def test_password_input_right_word_from_home() -> None:
"""Going right one word from the start of a password input should go to the end."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.password = True
input.action_cursor_right_word()
assert input.cursor_position == len(input.value)
async def test_input_right_word_from_end() -> None:
"""Going right one word from the end should do nothing."""
async with InputTester().run_test() as pilot:
for input in pilot.app.query(Input):
input.action_end()
input.action_cursor_right_word()
assert input.cursor_position == len(input.value)
async def test_input_right_word_to_the_end() -> None:
"""Using right-word to get to the end should hop the correct number of times."""
async with InputTester().run_test() as pilot:
expected_hops: dict[str | None, int] = {
"empty": 0,
"single-word": 1,
"multi-no-punctuation": 6,
"multi-punctuation": 10,
"multi-and-hyphenated": 7,
}
for input in pilot.app.query(Input):
input.cursor_position = 0
hops = 0
while input.cursor_position < len(input.value):
input.action_cursor_right_word()
hops += 1
assert hops == expected_hops[input.id]
async def test_input_left_word_from_the_end() -> None:
"""Using left-word to get home from the end should hop the correct number of times."""
async with InputTester().run_test() as pilot:
expected_hops: dict[str | None, int] = {
"empty": 0,
"single-word": 1,
"multi-no-punctuation": 6,
"multi-punctuation": 10,
"multi-and-hyphenated": 7,
}
for input in pilot.app.query(Input):
input.action_end()
hops = 0
while input.cursor_position:
input.action_cursor_left_word()
hops += 1
assert hops == expected_hops[input.id]
# TODO: more tests.
| InputTester |
python | ipython__ipython | IPython/core/completer.py | {
"start": 18740,
"end": 19079
} | class ____(_MatcherResultBase, TypedDict):
"""Result of new-style completion matcher."""
# note: TypedDict is added again to the inheritance chain
# in order to get __orig_bases__ for documentation
#: List of candidate completions
completions: Sequence[SimpleCompletion] | Iterator[SimpleCompletion]
| SimpleMatcherResult |
python | has2k1__plotnine | plotnine/scales/limits.py | {
"start": 3578,
"end": 3660
} | class ____(_lim):
"""
Color limits
"""
aesthetic = "color"
| colorlim |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 14754,
"end": 16345
} | class ____(NameModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"PruneDuplicatePaths: {self.name}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories = prune_duplicate_paths(
[path_to_os_path(os.path.normpath(x)).pop() for x in directories]
)
env[self.name] = self.separator.join(directories)
def _validate_path_value(name: str, value: Any) -> Union[str, pathlib.PurePath]:
"""Ensure the value for an env variable is string or path"""
types = (str, pathlib.PurePath)
if isinstance(value, types):
return value
types_str = " or ".join([f"`{t.__name__}`" for t in types])
warnings.warn(
f"when setting environment variable {name}={value}: value is of type "
f"`{type(value).__name__}`, but {types_str} was expected. This is deprecated and will be "
f"an error in Spack v1.0",
spack.error.SpackAPIWarning,
stacklevel=3,
)
return str(value)
def _validate_value(name: str, value: Any) -> str:
"""Ensure the value for an env variable is a string"""
if isinstance(value, str):
return value
warnings.warn(
f"when setting environment variable {name}={value}: value is of type "
f"`{type(value).__name__}`, but `str` was expected. This is deprecated and will be an "
"error in Spack v1.0",
spack.error.SpackAPIWarning,
stacklevel=3,
)
return str(value)
| PruneDuplicatePaths |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/mirror_gnu_broken/package.py | {
"start": 299,
"end": 598
} | class ____(AutotoolsPackage, GNUMirrorPackage):
"""Simple GNU package"""
homepage = "https://www.gnu.org/software/make/"
url = "https://ftpmirror.gnu.org/make/make-4.2.1.tar.gz"
version("4.2.1", sha256="e40b8f018c1da64edd1cc9a6fce5fa63b2e707e404e20cad91fbae337c98a5b7")
| MirrorGnuBroken |
python | huggingface__transformers | src/transformers/utils/hub.py | {
"start": 1884,
"end": 26461
} | class ____(TypedDict, total=False):
cache_dir: str | os.PathLike | None
force_download: bool
proxies: dict[str, str] | None
local_files_only: bool
token: str | bool | None
revision: str | None
subfolder: str
commit_hash: str | None
def is_offline_mode():
# Import inside the function so test patches on `huggingface_hub.constants` are picked up.
from huggingface_hub import constants as hf_hub_constants
return hf_hub_constants.HF_HUB_OFFLINE
# Determine default cache directory.
# The best way to set the cache path is with the environment variable HF_HOME. For more details, check out this
# documentation page: https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables.
HF_MODULES_CACHE = os.getenv("HF_MODULES_CACHE", os.path.join(constants.HF_HOME, "modules"))
TRANSFORMERS_DYNAMIC_MODULE_NAME = "transformers_modules"
SESSION_ID = uuid4().hex
S3_BUCKET_PREFIX = "https://s3.amazonaws.com/models.huggingface.co/bert"
CLOUDFRONT_DISTRIB_PREFIX = "https://cdn.huggingface.co"
def _get_cache_file_to_return(
path_or_repo_id: str,
full_filename: str,
cache_dir: str | Path | None = None,
revision: str | None = None,
repo_type: str | None = None,
):
# We try to see if we have a cached version (not up to date):
resolved_file = try_to_load_from_cache(
path_or_repo_id, full_filename, cache_dir=cache_dir, revision=revision, repo_type=repo_type
)
if resolved_file is not None and resolved_file != _CACHED_NO_EXIST:
return resolved_file
return None
def list_repo_templates(
repo_id: str,
*,
local_files_only: bool,
revision: str | None = None,
cache_dir: str | None = None,
token: str | bool | None = None,
) -> list[str]:
"""List template files from a repo.
A template is a jinja file located under the `additional_chat_templates/` folder.
If working in offline mode or if internet is down, the method will list jinja template from the local cache - if any.
"""
if not local_files_only:
try:
return [
entry.path.removeprefix(f"{CHAT_TEMPLATE_DIR}/")
for entry in list_repo_tree(
repo_id=repo_id,
revision=revision,
path_in_repo=CHAT_TEMPLATE_DIR,
recursive=False,
token=token,
)
if entry.path.endswith(".jinja")
]
except (GatedRepoError, RepositoryNotFoundError, RevisionNotFoundError):
raise # valid errors => do not catch
except (HfHubHTTPError, OfflineModeIsEnabled, httpx.NetworkError):
pass # offline mode, internet down, etc. => try local files
# check local files
try:
snapshot_dir = snapshot_download(
repo_id=repo_id, revision=revision, cache_dir=cache_dir, local_files_only=True
)
except LocalEntryNotFoundError: # No local repo means no local files
return []
templates_dir = Path(snapshot_dir, CHAT_TEMPLATE_DIR)
if not templates_dir.is_dir():
return []
return [entry.stem for entry in templates_dir.iterdir() if entry.is_file() and entry.name.endswith(".jinja")]
def define_sagemaker_information():
try:
instance_data = httpx.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
dlc_container_used = instance_data["Image"]
dlc_tag = instance_data["Image"].split(":")[1]
except Exception:
dlc_container_used = None
dlc_tag = None
sagemaker_params = json.loads(os.getenv("SM_FRAMEWORK_PARAMS", "{}"))
runs_distributed_training = "sagemaker_distributed_dataparallel_enabled" in sagemaker_params
account_id = os.getenv("TRAINING_JOB_ARN").split(":")[4] if "TRAINING_JOB_ARN" in os.environ else None
sagemaker_object = {
"sm_framework": os.getenv("SM_FRAMEWORK_MODULE", None),
"sm_region": os.getenv("AWS_REGION", None),
"sm_number_gpu": os.getenv("SM_NUM_GPUS", "0"),
"sm_number_cpu": os.getenv("SM_NUM_CPUS", "0"),
"sm_distributed_training": runs_distributed_training,
"sm_deep_learning_container": dlc_container_used,
"sm_deep_learning_container_tag": dlc_tag,
"sm_account_id": account_id,
}
return sagemaker_object
def http_user_agent(user_agent: dict | str | None = None) -> str:
"""
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{get_torch_version()}"
if constants.HF_HUB_DISABLE_TELEMETRY:
return ua + "; telemetry/off"
if is_training_run_on_sagemaker():
ua += "; " + "; ".join(f"{k}/{v}" for k, v in define_sagemaker_information().items())
# CI will set this value to True
if os.environ.get("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES:
ua += "; is_ci/true"
if isinstance(user_agent, dict):
ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
elif isinstance(user_agent, str):
ua += "; " + user_agent
return ua
def extract_commit_hash(resolved_file: str | None, commit_hash: str | None) -> str | None:
"""
Extracts the commit hash from a resolved filename toward a cache file.
"""
if resolved_file is None or commit_hash is not None:
return commit_hash
resolved_file = str(Path(resolved_file).as_posix())
search = re.search(r"snapshots/([^/]+)/", resolved_file)
if search is None:
return None
commit_hash = search.groups()[0]
return commit_hash if REGEX_COMMIT_HASH.match(commit_hash) else None
def cached_file(
path_or_repo_id: str | os.PathLike,
filename: str,
**kwargs,
) -> str | None:
"""
Tries to locate a file in a local folder and repo, downloads and cache it if necessary.
Args:
path_or_repo_id (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a model repo on huggingface.co.
- a path to a *directory* potentially containing the file.
filename (`str`):
The name of the file to locate in `path_or_repo`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the configuration files and override the cached versions if they
exist.
proxies (`dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `hf auth login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
specify the folder name here.
repo_type (`str`, *optional*):
Specify the repo type (useful when downloading from a space for instance).
<Tip>
Passing `token=True` is required when you want to use a private model.
</Tip>
Returns:
`Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).
Examples:
```python
# Download a model weight from the Hub and cache it.
model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin")
```
"""
file = cached_files(path_or_repo_id=path_or_repo_id, filenames=[filename], **kwargs)
file = file[0] if file is not None else file
return file
def cached_files(
path_or_repo_id: str | os.PathLike,
filenames: list[str],
cache_dir: str | os.PathLike | None = None,
force_download: bool = False,
proxies: dict[str, str] | None = None,
token: bool | str | None = None,
revision: str | None = None,
local_files_only: bool = False,
subfolder: str = "",
repo_type: str | None = None,
user_agent: str | dict[str, str] | None = None,
_raise_exceptions_for_gated_repo: bool = True,
_raise_exceptions_for_missing_entries: bool = True,
_raise_exceptions_for_connection_errors: bool = True,
_commit_hash: str | None = None,
**deprecated_kwargs,
) -> str | None:
"""
Tries to locate several files in a local folder and repo, downloads and cache them if necessary.
Args:
path_or_repo_id (`str` or `os.PathLike`):
This can be either:
- a string, the *model id* of a model repo on huggingface.co.
- a path to a *directory* potentially containing the file.
filenames (`list[str]`):
The name of all the files to locate in `path_or_repo`.
cache_dir (`str` or `os.PathLike`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force to (re-)download the configuration files and override the cached versions if they
exist.
proxies (`dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `hf auth login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, will only try to load the tokenizer configuration from local files.
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
specify the folder name here.
repo_type (`str`, *optional*):
Specify the repo type (useful when downloading from a space for instance).
Private args:
_raise_exceptions_for_gated_repo (`bool`):
if False, do not raise an exception for gated repo error but return None.
_raise_exceptions_for_missing_entries (`bool`):
if False, do not raise an exception for missing entries but return None.
_raise_exceptions_for_connection_errors (`bool`):
if False, do not raise an exception for connection errors but return None.
_commit_hash (`str`, *optional*):
passed when we are chaining several calls to various files (e.g. when loading a tokenizer or
a pipeline). If files are cached for this commit hash, avoid calls to head and get from the cache.
<Tip>
Passing `token=True` is required when you want to use a private model.
</Tip>
Returns:
`Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).
Examples:
```python
# Download a model weight from the Hub and cache it.
model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin")
```
"""
if is_offline_mode() and not local_files_only:
logger.info("Offline mode: forcing local_files_only=True")
local_files_only = True
if subfolder is None:
subfolder = ""
# Add folder to filenames
full_filenames = [os.path.join(subfolder, file) for file in filenames]
path_or_repo_id = str(path_or_repo_id)
existing_files = []
for filename in full_filenames:
if os.path.isdir(path_or_repo_id):
resolved_file = os.path.join(path_or_repo_id, filename)
if not os.path.isfile(resolved_file):
if _raise_exceptions_for_missing_entries and filename != os.path.join(subfolder, "config.json"):
revision_ = "main" if revision is None else revision
raise OSError(
f"{path_or_repo_id} does not appear to have a file named {filename}. Checkout "
f"'https://huggingface.co/{path_or_repo_id}/tree/{revision_}' for available files."
)
else:
continue
existing_files.append(resolved_file)
if os.path.isdir(path_or_repo_id):
return existing_files if existing_files else None
if cache_dir is None:
cache_dir = constants.HF_HUB_CACHE
if isinstance(cache_dir, Path):
cache_dir = str(cache_dir)
existing_files = []
file_counter = 0
if _commit_hash is not None and not force_download:
for filename in full_filenames:
# If the file is cached under that commit hash, we return it directly.
resolved_file = try_to_load_from_cache(
path_or_repo_id, filename, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
)
if resolved_file is not None:
if resolved_file is not _CACHED_NO_EXIST:
file_counter += 1
existing_files.append(resolved_file)
elif not _raise_exceptions_for_missing_entries:
file_counter += 1
else:
raise OSError(f"Could not locate {filename} inside {path_or_repo_id}.")
# Either all the files were found, or some were _CACHED_NO_EXIST but we do not raise for missing entries
if file_counter == len(full_filenames):
return existing_files if len(existing_files) > 0 else None
user_agent = http_user_agent(user_agent)
# download the files if needed
try:
if len(full_filenames) == 1:
# This is slightly better for only 1 file
hf_hub_download(
path_or_repo_id,
filenames[0],
subfolder=None if len(subfolder) == 0 else subfolder,
repo_type=repo_type,
revision=revision,
cache_dir=cache_dir,
user_agent=user_agent,
force_download=force_download,
proxies=proxies,
token=token,
local_files_only=local_files_only,
)
else:
snapshot_download(
path_or_repo_id,
allow_patterns=full_filenames,
repo_type=repo_type,
revision=revision,
cache_dir=cache_dir,
user_agent=user_agent,
force_download=force_download,
proxies=proxies,
token=token,
local_files_only=local_files_only,
)
except Exception as e:
# We cannot recover from them
if isinstance(e, RepositoryNotFoundError) and not isinstance(e, GatedRepoError):
raise OSError(
f"{path_or_repo_id} is not a local folder and is not a valid model identifier "
"listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token "
"having permission to this repo either by logging in with `hf auth login` or by passing "
"`token=<your_token>`"
) from e
elif isinstance(e, RevisionNotFoundError):
raise OSError(
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists "
"for this model name. Check the model page at "
f"'https://huggingface.co/{path_or_repo_id}' for available revisions."
) from e
elif isinstance(e, PermissionError):
raise OSError(
f"PermissionError at {e.filename} when downloading {path_or_repo_id}. "
"Check cache directory permissions. Common causes: 1) another user is downloading the same model (please wait); "
"2) a previous download was canceled and the lock file needs manual removal."
) from e
elif isinstance(e, ValueError):
raise OSError(f"{e}") from e
# Now we try to recover if we can find all files correctly in the cache
resolved_files = [
_get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision, repo_type)
for filename in full_filenames
]
if all(file is not None for file in resolved_files):
return resolved_files
# Raise based on the flags. Note that we will raise for missing entries at the very end, even when
# not entering this Except block, as it may also happen when `snapshot_download` does not raise
if isinstance(e, GatedRepoError):
if not _raise_exceptions_for_gated_repo:
return None
raise OSError(
"You are trying to access a gated repo.\nMake sure to have access to it at "
f"https://huggingface.co/{path_or_repo_id}.\n{str(e)}"
) from e
elif isinstance(e, LocalEntryNotFoundError):
if not _raise_exceptions_for_connection_errors:
return None
# Here we only raise if both flags for missing entry and connection errors are True (because it can be raised
# even when `local_files_only` is True, in which case raising for connections errors only would not make sense)
elif _raise_exceptions_for_missing_entries:
raise OSError(
f"We couldn't connect to '{constants.ENDPOINT}' to load the files, and couldn't find them in the"
f" cached files.\nCheck your internet connection or see how to run the library in offline mode at"
" 'https://huggingface.co/docs/transformers/installation#offline-mode'."
) from e
# snapshot_download will not raise EntryNotFoundError, but hf_hub_download can. If this is the case, it will be treated
# later on anyway and re-raised if needed
elif isinstance(e, HfHubHTTPError) and not isinstance(e, EntryNotFoundError):
if not _raise_exceptions_for_connection_errors:
return None
raise OSError(f"There was a specific connection error when trying to load {path_or_repo_id}:\n{e}") from e
# Any other Exception type should now be re-raised, in order to provide helpful error messages and break the execution flow
# (EntryNotFoundError will be treated outside this block and correctly re-raised if needed)
elif not isinstance(e, EntryNotFoundError):
raise e
resolved_files = [
_get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision) for filename in full_filenames
]
# If there are any missing file and the flag is active, raise
if any(file is None for file in resolved_files) and _raise_exceptions_for_missing_entries:
missing_entries = [original for original, resolved in zip(full_filenames, resolved_files) if resolved is None]
# Last escape
if len(resolved_files) == 1 and missing_entries[0] == os.path.join(subfolder, "config.json"):
return None
# Now we raise for missing entries
revision_ = "main" if revision is None else revision
msg = (
f"a file named {missing_entries[0]}" if len(missing_entries) == 1 else f"files named {(*missing_entries,)}"
)
raise OSError(
f"{path_or_repo_id} does not appear to have {msg}. Checkout 'https://huggingface.co/{path_or_repo_id}/tree/{revision_}'"
" for available files."
)
# Remove potential missing entries (we can silently remove them at this point based on the flags)
resolved_files = [file for file in resolved_files if file is not None]
# Return `None` if the list is empty, coherent with other Exception when the flag is not active
resolved_files = None if len(resolved_files) == 0 else resolved_files
return resolved_files
def has_file(
path_or_repo: str | os.PathLike,
filename: str,
revision: str | None = None,
proxies: dict[str, str] | None = None,
token: bool | str | None = None,
*,
local_files_only: bool = False,
cache_dir: str | Path | None = None,
repo_type: str | None = None,
**deprecated_kwargs,
):
"""
Checks if a repo contains a given file without downloading it. Works for remote repos and local folders.
If offline mode is enabled, checks if the file exists in the cache.
<Tip warning={false}>
This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for
this repo, but will return False for regular connection errors.
</Tip>
"""
# If path to local directory, check if the file exists
if os.path.isdir(path_or_repo):
return os.path.isfile(os.path.join(path_or_repo, filename))
# Else it's a repo => let's check if the file exists in local cache or on the Hub
# Check if file exists in cache
# This information might be outdated so it's best to also make a HEAD call (if allowed).
cached_path = try_to_load_from_cache(
repo_id=path_or_repo,
filename=filename,
revision=revision,
repo_type=repo_type,
cache_dir=cache_dir,
)
has_file_in_cache = isinstance(cached_path, str)
# If local_files_only, don't try the HEAD call
if local_files_only:
return has_file_in_cache
# Check if the file exists
try:
response = get_session().head(
hf_hub_url(path_or_repo, filename=filename, revision=revision, repo_type=repo_type),
headers=build_hf_headers(token=token, user_agent=http_user_agent()),
follow_redirects=False,
timeout=10,
)
except httpx.ProxyError:
# Actually raise for those subclasses of ConnectionError
raise
except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled):
return has_file_in_cache
try:
hf_raise_for_status(response)
return True
except GatedRepoError as e:
logger.error(e)
raise OSError(
f"{path_or_repo} is a gated repository. Make sure to request access at "
f"https://huggingface.co/{path_or_repo} and pass a token having permission to this repo either by "
"logging in with `hf auth login` or by passing `token=<your_token>`."
) from e
except RepositoryNotFoundError as e:
logger.error(e)
raise OSError(f"{path_or_repo} is not a local folder or a valid repository name on 'https://hf.co'.") from e
except RevisionNotFoundError as e:
logger.error(e)
raise OSError(
f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
f"model name. Check the model page at 'https://huggingface.co/{path_or_repo}' for available revisions."
) from e
except EntryNotFoundError:
return False # File does not exist
except HfHubHTTPError:
# Any authentication/authorization error will be caught here => default to cache
return has_file_in_cache
| DownloadKwargs |
python | sanic-org__sanic | sanic/worker/restarter.py | {
"start": 175,
"end": 3038
} | class ____:
def restart(
self,
transient_processes: list[WorkerProcess],
durable_processes: list[WorkerProcess],
process_names: Optional[list[str]] = None,
restart_order=RestartOrder.SHUTDOWN_FIRST,
**kwargs,
) -> None:
"""Restart the worker processes.
Args:
process_names (Optional[List[str]], optional): The names of the processes to restart.
If `None`, then all processes will be restarted. Defaults to `None`.
restart_order (RestartOrder, optional): The order in which to restart the processes.
Defaults to `RestartOrder.SHUTDOWN_FIRST`.
""" # noqa: E501
restarted = self._restart_transient(
transient_processes,
process_names or [],
restart_order,
**kwargs,
)
restarted |= self._restart_durable(
durable_processes,
process_names or [],
restart_order,
**kwargs,
)
if process_names and not restarted:
error_logger.error(
f"Failed to restart processes: {', '.join(process_names)}"
)
def _restart_transient(
self,
processes: list[WorkerProcess],
process_names: list[str],
restart_order: RestartOrder,
**kwargs,
) -> set[str]:
restarted: set[str] = set()
for process in processes:
if not process.restartable or (
process_names and process.name not in process_names
):
continue
self._restart_process(process, restart_order, **kwargs)
restarted.add(process.name)
return restarted
def _restart_durable(
self,
processes: list[WorkerProcess],
process_names: list[str],
restart_order: RestartOrder,
**kwargs,
) -> set[str]:
restarted: set[str] = set()
if not process_names:
return restarted
for process in processes:
if not process.restartable or process.name not in process_names:
continue
if process.state not in (
ProcessState.COMPLETED,
ProcessState.FAILED,
ProcessState.NONE,
):
error_logger.error(
f"Cannot restart process {process.name} because "
"it is not in a final state. Current state is: "
f"{process.state.name}."
)
continue
self._restart_process(process, restart_order, **kwargs)
restarted.add(process.name)
return restarted
def _restart_process(self, process, restart_order, **kwargs):
process.restart(restart_order=restart_order, **kwargs)
| Restarter |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/links/test_base_aws.py | {
"start": 1471,
"end": 3921
} | class ____:
@pytest.mark.parametrize(
("region_name", "aws_partition", "keywords", "expected_value"),
[
("eu-central-1", "aws", {}, {"region_name": "eu-central-1", "aws_domain": "aws.amazon.com"}),
("cn-north-1", "aws-cn", {}, {"region_name": "cn-north-1", "aws_domain": "amazonaws.cn"}),
(
"us-gov-east-1",
"aws-us-gov",
{},
{"region_name": "us-gov-east-1", "aws_domain": "amazonaws-us-gov.com"},
),
(
"eu-west-1",
"aws",
CUSTOM_KEYS,
{"region_name": "eu-west-1", "aws_domain": "aws.amazon.com", **CUSTOM_KEYS},
),
],
)
def test_persist(self, region_name, aws_partition, keywords, expected_value):
mock_context = mock.MagicMock()
SimpleBaseAwsLink.persist(
context=mock_context,
operator=MockOperator(task_id="test_task_id"),
region_name=region_name,
aws_partition=aws_partition,
**keywords,
)
ti = mock_context["ti"]
ti.xcom_push.assert_called_once_with(
key=XCOM_KEY,
value=expected_value,
)
def test_disable_xcom_push(self):
mock_context = mock.MagicMock()
SimpleBaseAwsLink.persist(
context=mock_context,
operator=MockOperator(task_id="test_task_id", do_xcom_push=False),
region_name="eu-east-1",
aws_partition="aws",
)
ti = mock_context["ti"]
ti.xcom_push.assert_not_called()
def test_suppress_error_on_xcom_push(self):
mock_context = mock.MagicMock()
mock_context["ti"].xcom_push.side_effect = PermissionError("FakeError")
SimpleBaseAwsLink.persist(
context=mock_context,
operator=MockOperator(task_id="test_task_id"),
region_name="eu-east-1",
aws_partition="aws",
)
mock_context["ti"].xcom_push.assert_called_once_with(
key="test_xcom_key",
value={"region_name": "eu-east-1", "aws_domain": "aws.amazon.com"},
)
def link_test_operator(*links):
"""Helper for create mock operator class with extra links"""
class LinkTestOperator(MockOperator):
operator_extra_links = tuple(c() for c in links)
return LinkTestOperator
| TestBaseAwsLink |
python | OmkarPathak__pygorithm | tests/test_math.py | {
"start": 687,
"end": 1111
} | class ____(unittest.TestCase):
def test_dec_to_bin(self):
self.assertEqual(conversion.decimal_to_binary(2), '10')
def test_bin_to_dec(self):
self.assertEqual(conversion.binary_to_decimal('1010'), 10)
def test_dec_to_hex(self):
self.assertEqual(conversion.decimal_to_hex(30), '1E')
def test_hex_to_dex(self):
self.assertEqual(conversion.hex_to_decimal('1E'), 30)
| TestConversion |
python | ApeWorX__ape | src/ape/contracts/base.py | {
"start": 34742,
"end": 35722
} | class ____:
"""
A wrapper used when multiple events have the same so that
you can still create mock-logs.
"""
def __init__(self, events: list[ContractEvent]):
self.events = events
def __call__(self, *args, **kwargs) -> MockContractLog:
"""
Create a mock contract log using the first working ABI.
Args:
*args: Positional arguments for the event.
**kwargs: Key-word arguments for the event.
Returns:
:class:`~ape.types.events.MockContractLog`
"""
# TODO: Use composite error.
errors = []
for evt in self.events:
try:
return evt(*args, **kwargs)
except ValueError as err:
errors.append(err)
continue # not a match
error_str = ", ".join([f"{e}" for e in errors])
raise ValueError(f"Could not make a mock contract log. Errors: {error_str}")
| ContractEventWrapper |
python | wandb__wandb | wandb/old/summary.py | {
"start": 383,
"end": 5877
} | class ____:
"""Nested dict-like object that proxies read and write operations through a root object.
This lets us do synchronous serialization and lazy loading of large values.
"""
def __init__(self, root=None, path=()):
self._path = tuple(path)
if root is None:
self._root = self
self._json_dict = {}
else:
self._root = root
json_dict = root._json_dict
for k in path:
json_dict = json_dict.get(k, {})
self._json_dict = json_dict
self._dict = {}
# We use this to track which keys the user has set explicitly
# so that we don't automatically overwrite them when we update
# the summary from the history.
self._locked_keys = set()
def __setattr__(self, k, v):
k = k.strip()
if k.startswith("_"):
object.__setattr__(self, k, v)
else:
self[k] = v
def __getattr__(self, k):
k = k.strip()
if k.startswith("_"):
return object.__getattribute__(self, k)
else:
return self[k]
def _root_get(self, path, child_dict):
"""Load a value at a particular path from the root.
This should only be implemented by the "_root" child class.
We pass the child_dict so the item can be set on it or not as
appropriate. Returning None for a nonexistent path wouldn't be
distinguishable from that path being set to the value None.
"""
raise NotImplementedError
def _root_set(self, path, new_keys_values):
"""Set a value at a particular path in the root.
This should only be implemented by the "_root" child class.
"""
raise NotImplementedError
def _root_del(self, path):
"""Delete a value at a particular path in the root.
This should only be implemented by the "_root" child class.
"""
raise NotImplementedError
def _write(self, commit=False):
# should only be implemented on the root summary
raise NotImplementedError
def keys(self):
# _json_dict has the full set of keys, including those for h5 objects
# that may not have been loaded yet
return self._json_dict.keys()
def get(self, k, default=None):
if isinstance(k, str):
k = k.strip()
if k not in self._dict:
self._root._root_get(self._path + (k,), self._dict)
return self._dict.get(k, default)
def items(self):
# not all items may be loaded into self._dict, so we
# have to build the sequence of items from scratch
for k in self.keys():
yield k, self[k]
def __getitem__(self, k):
if isinstance(k, str):
k = k.strip()
self.get(k) # load the value into _dict if it should be there
res = self._dict[k]
return res
def __contains__(self, k):
if isinstance(k, str):
k = k.strip()
return k in self._json_dict
def __setitem__(self, k, v):
if isinstance(k, str):
k = k.strip()
path = self._path
if isinstance(v, dict):
self._dict[k] = SummarySubDict(self._root, path + (k,))
self._root._root_set(path, [(k, {})])
self._dict[k].update(v)
else:
self._dict[k] = v
self._root._root_set(path, [(k, v)])
self._locked_keys.add(k)
self._root._write()
return v
def __delitem__(self, k):
k = k.strip()
del self._dict[k]
self._root._root_del(self._path + (k,))
self._root._write()
def __repr__(self):
# use a copy of _dict, except add placeholders for h5 objects, etc.
# that haven't been loaded yet
repr_dict = dict(self._dict)
for k in self._json_dict:
v = self._json_dict[k]
if (
k not in repr_dict
and isinstance(v, dict)
and v.get("_type") in H5_TYPES
):
# unloaded h5 objects may be very large. use a placeholder for them
# if we haven't already loaded them
repr_dict[k] = "..."
else:
repr_dict[k] = self[k]
return repr(repr_dict)
def update(self, key_vals=None, overwrite=True):
"""Locked keys will be overwritten unless overwrite=False.
Otherwise, written keys will be added to the "locked" list.
"""
if key_vals:
write_items = self._update(key_vals, overwrite)
self._root._root_set(self._path, write_items)
self._root._write(commit=True)
def _update(self, key_vals, overwrite):
if not key_vals:
return
key_vals = {k.strip(): v for k, v in key_vals.items()}
if overwrite:
write_items = list(key_vals.items())
self._locked_keys.update(key_vals.keys())
else:
write_keys = set(key_vals.keys()) - self._locked_keys
write_items = [(k, key_vals[k]) for k in write_keys]
for key, value in write_items:
if isinstance(value, dict):
self._dict[key] = SummarySubDict(self._root, self._path + (key,))
self._dict[key]._update(value, overwrite)
else:
self._dict[key] = value
return write_items
| SummarySubDict |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 40024,
"end": 41842
} | class ____:
"""semi-serializable loader object used by LazyLoader
Historically, this object would be carried along with instances that
needed to run lazyloaders, so it had to be serializable to support
cached instances.
this is no longer a general requirement, and the case where this object
is used is exactly the case where we can't really serialize easily,
which is when extra criteria in the loader option is present.
We can't reliably serialize that as it refers to mapped entities and
AliasedClass objects that are local to the current process, which would
need to be matched up on deserialize e.g. the sqlalchemy.ext.serializer
approach.
"""
def __init__(self, key, initiating_strategy, loadopt, extra_criteria):
self.key = key
self.strategy_key = initiating_strategy.strategy_key
self.loadopt = loadopt
self.extra_criteria = extra_criteria
def __getstate__(self):
if self.extra_criteria is not None:
util.warn(
"Can't reliably serialize a lazyload() option that "
"contains additional criteria; please use eager loading "
"for this case"
)
return {
"key": self.key,
"strategy_key": self.strategy_key,
"loadopt": self.loadopt,
"extra_criteria": (),
}
def __call__(self, state, passive=attributes.PASSIVE_OFF):
key = self.key
instance_mapper = state.manager.mapper
prop = instance_mapper._props[key]
strategy = prop._strategies[self.strategy_key]
return strategy._load_for_state(
state,
passive,
loadopt=self.loadopt,
extra_criteria=self.extra_criteria,
)
| _LoadLazyAttribute |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 28620,
"end": 29744
} | class ____(unittest.TestCase):
def do_test(self, factory_string):
ds = SyntheticDataset(32, 1000, 100, 10)
index = faiss.index_factory(ds.d, factory_string)
index.train(ds.get_train())
index.add(ds.get_database())
index.nprobe
index.nprobe = 10
Dref, Iref = index.search(ds.get_queries(), 10)
D, I, codes = index.search_and_return_codes(
ds.get_queries(), 10, include_listnos=True)
np.testing.assert_array_equal(I, Iref)
np.testing.assert_array_equal(D, Dref)
# verify that we get the same distances when decompressing from
# returned codes (the codes are compatible with sa_decode)
for qi in range(ds.nq):
q = ds.get_queries()[qi]
xbi = index.sa_decode(codes[qi])
D2 = ((q - xbi) ** 2).sum(1)
np.testing.assert_allclose(D2, D[qi], rtol=1e-5)
def test_ivfpq(self):
self.do_test("IVF20,PQ4x4np")
def test_ivfsq(self):
self.do_test("IVF20,SQ8")
def test_ivfrq(self):
self.do_test("IVF20,RQ3x4")
| TestSearchAndGetCodes |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 3487,
"end": 3570
} | class ____:
def mixed(self, first, second, *, third, fourth):
pass
| Mixed |
python | kamyu104__LeetCode-Solutions | Python/backspace-string-compare.py | {
"start": 52,
"end": 587
} | class ____(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
def findNextChar(S):
skip = 0
for i in reversed(xrange(len(S))):
if S[i] == '#':
skip += 1
elif skip:
skip -= 1
else:
yield S[i]
return all(x == y for x, y in
itertools.izip_longest(findNextChar(S), findNextChar(T)))
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/workflow/react_agent.py | {
"start": 1343,
"end": 11861
} | class ____(BaseWorkflowAgent):
"""React agent implementation."""
reasoning_key: str = "current_reasoning"
output_parser: ReActOutputParser = Field(
default_factory=ReActOutputParser, description="The react output parser"
)
formatter: ReActChatFormatter = Field(
default_factory=default_formatter,
description="The react chat formatter to format the reasoning steps and chat history into an llm input.",
)
@model_validator(mode="after")
def validate_formatter(self) -> "ReActAgent":
"""Validate the formatter."""
if (
self.formatter.context
and self.system_prompt
and self.system_prompt not in self.formatter.context
):
self.formatter.context = (
self.system_prompt + "\n\n" + self.formatter.context.strip()
)
elif not self.formatter.context and self.system_prompt:
self.formatter.context = self.system_prompt
return self
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
# TODO: the ReAct formatter does not explicitly specify PromptTemplate
# objects, but wrap it in this to obey the interface
react_header = self.formatter.system_header
return {"react_header": PromptTemplate(react_header)}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
if "react_header" in prompts:
react_header = prompts["react_header"]
if isinstance(react_header, str):
react_header = PromptTemplate(react_header)
self.formatter.system_header = react_header.format()
async def _get_response(self, current_llm_input: List[ChatMessage]) -> ChatResponse:
return await self.llm.achat(current_llm_input)
async def _get_streaming_response(
self, ctx: Context, current_llm_input: List[ChatMessage]
) -> ChatResponse:
response = await self.llm.astream_chat(
current_llm_input,
)
# last_chat_response will be used later, after the loop.
# We initialize it so it's valid even when 'response' is empty
last_chat_response = ChatResponse(message=ChatMessage())
async for last_chat_response in response:
raw = (
last_chat_response.raw.model_dump()
if isinstance(last_chat_response.raw, BaseModel)
else last_chat_response.raw
)
# some code paths (namely react agent via llm.predict_and_call for non function calling llms) pass through a context without starting the workflow.
# They do so in order to conform to the interface, and share state between tools, however the events are discarded and not exposed to the caller,
# so just don't write events if the context is not running.
if ctx.is_running:
ctx.write_event_to_stream(
AgentStream(
delta=last_chat_response.delta or "",
response=last_chat_response.message.content or "",
raw=raw,
current_agent_name=self.name,
thinking_delta=last_chat_response.additional_kwargs.get(
"thinking_delta", None
),
)
)
return last_chat_response
async def take_step(
self,
ctx: Context,
llm_input: List[ChatMessage],
tools: Sequence[AsyncBaseTool],
memory: BaseMemory,
) -> AgentOutput:
"""Take a single step with the React agent."""
# remove system prompt, since the react prompt will be combined with it
if llm_input[0].role == "system":
system_prompt = llm_input[0].content or ""
llm_input = llm_input[1:]
else:
system_prompt = ""
output_parser = self.output_parser
react_chat_formatter = self.formatter
# Format initial chat input
current_reasoning: list[BaseReasoningStep] = await ctx.store.get(
self.reasoning_key, default=[]
)
input_chat = react_chat_formatter.format(
tools,
chat_history=llm_input,
current_reasoning=current_reasoning,
)
# some code paths (namely react agent via llm.predict_and_call for non function calling llms) pass through a context without starting the workflow.
# They do so in order to conform to the interface, and share state between tools, however the events are discarded and not exposed to the caller,
# so just don't write events if the context is not running.
if ctx.is_running:
ctx.write_event_to_stream(
AgentInput(input=input_chat, current_agent_name=self.name)
)
# Initial LLM call
if self.streaming:
last_chat_response = await self._get_streaming_response(ctx, input_chat)
else:
last_chat_response = await self._get_response(input_chat)
# Parse reasoning step and check if done
message_content = last_chat_response.message.content
if not message_content:
raise ValueError("Got empty message")
try:
reasoning_step = output_parser.parse(message_content, is_streaming=False)
except ValueError as e:
error_msg = (
f"Error while parsing the output: {e!s}\n\n"
"The output should be in one of the following formats:\n"
"1. To call a tool:\n"
"```\n"
"Thought: <thought>\n"
"Action: <action>\n"
"Action Input: <action_input>\n"
"```\n"
"2. To answer the question:\n"
"```\n"
"Thought: <thought>\n"
"Answer: <answer>\n"
"```\n"
)
raw = (
last_chat_response.raw.model_dump()
if isinstance(last_chat_response.raw, BaseModel)
else last_chat_response.raw
)
# Return with retry messages to let the LLM fix the error
return AgentOutput(
response=last_chat_response.message,
raw=raw,
current_agent_name=self.name,
retry_messages=[
last_chat_response.message,
ChatMessage(role="user", content=error_msg),
],
)
# add to reasoning if not a handoff
current_reasoning.append(reasoning_step)
await ctx.store.set(self.reasoning_key, current_reasoning)
# If response step, we're done
raw = (
last_chat_response.raw.model_dump()
if isinstance(last_chat_response.raw, BaseModel)
else last_chat_response.raw
)
if reasoning_step.is_done:
return AgentOutput(
response=last_chat_response.message,
raw=raw,
current_agent_name=self.name,
)
reasoning_step = cast(ActionReasoningStep, reasoning_step)
if not isinstance(reasoning_step, ActionReasoningStep):
raise ValueError(f"Expected ActionReasoningStep, got {reasoning_step}")
# Create tool call
tool_calls = [
ToolSelection(
tool_id=str(uuid.uuid4()),
tool_name=reasoning_step.action,
tool_kwargs=reasoning_step.action_input,
)
]
return AgentOutput(
response=last_chat_response.message,
tool_calls=tool_calls,
raw=raw,
current_agent_name=self.name,
)
async def handle_tool_call_results(
self, ctx: Context, results: List[ToolCallResult], memory: BaseMemory
) -> None:
"""Handle tool call results for React agent."""
current_reasoning: list[BaseReasoningStep] = await ctx.store.get(
self.reasoning_key, default=[]
)
for tool_call_result in results:
obs_step = ObservationReasoningStep(
observation=str(tool_call_result.tool_output.content),
return_direct=tool_call_result.return_direct,
)
current_reasoning.append(obs_step)
if (
tool_call_result.return_direct
and tool_call_result.tool_name != "handoff"
):
current_reasoning.append(
ResponseReasoningStep(
thought=obs_step.observation,
response=obs_step.observation,
is_streaming=False,
)
)
break
await ctx.store.set(self.reasoning_key, current_reasoning)
async def finalize(
self, ctx: Context, output: AgentOutput, memory: BaseMemory
) -> AgentOutput:
"""Finalize the React agent."""
current_reasoning: list[BaseReasoningStep] = await ctx.store.get(
self.reasoning_key, default=[]
)
if len(current_reasoning) > 0 and isinstance(
current_reasoning[-1], ResponseReasoningStep
):
reasoning_str = "\n".join([x.get_content() for x in current_reasoning])
if reasoning_str:
reasoning_msg = ChatMessage(role="assistant", content=reasoning_str)
await memory.aput(reasoning_msg)
await ctx.store.set(self.reasoning_key, [])
# Find the text block in the response to modify it directly
text_block = None
for block in output.response.blocks:
if isinstance(block, TextBlock):
text_block = block
break
# remove "Answer:" from the response (now checking text_block.text)
if text_block and "Answer:" in text_block.text:
start_idx = text_block.text.find("Answer:")
if start_idx != -1:
# Modify the .text attribute of the block, NOT response.content
text_block.text = text_block.text[
start_idx + len("Answer:") :
].strip()
# clear scratchpad
await ctx.store.set(self.reasoning_key, [])
return output
| ReActAgent |
python | pennersr__django-allauth | allauth/socialaccount/providers/frontier/provider.py | {
"start": 322,
"end": 683
} | class ____(ProviderAccount):
def get_profile_url(self):
return None
def get_avatar_url(self):
return "https://www.gravatar.com/avatar/%s?%s" % (
hashlib.sha256(
self.account.extra_data.get("email").lower().encode("utf-8")
).hexdigest(),
urlencode({"d": "mp"}),
)
| FrontierAccount |
python | scipy__scipy | scipy/fft/tests/test_basic.py | {
"start": 17201,
"end": 19076
} | class ____:
threads = 16
input_shape = (800, 200)
def _test_mtsame(self, func, *args, xp=None):
def worker(args, q):
q.put(func(*args))
q = queue.Queue()
expected = func(*args)
# Spin off a bunch of threads to call the same function simultaneously
t = [threading.Thread(target=worker, args=(args, q))
for i in range(self.threads)]
[x.start() for x in t]
[x.join() for x in t]
# Make sure all threads returned the correct value
for i in range(self.threads):
xp_assert_equal(
q.get(timeout=5), expected,
err_msg='Function returned wrong value in multithreaded context'
)
def test_fft(self, xp):
a = xp.ones(self.input_shape, dtype=xp.complex128)
self._test_mtsame(fft.fft, a, xp=xp)
def test_ifft(self, xp):
a = xp.full(self.input_shape, 1+0j)
self._test_mtsame(fft.ifft, a, xp=xp)
def test_rfft(self, xp):
a = xp.ones(self.input_shape)
self._test_mtsame(fft.rfft, a, xp=xp)
def test_irfft(self, xp):
a = xp.full(self.input_shape, 1+0j)
self._test_mtsame(fft.irfft, a, xp=xp)
def test_hfft(self, xp):
a = xp.ones(self.input_shape, dtype=xp.complex64)
self._test_mtsame(fft.hfft, a, xp=xp)
def test_ihfft(self, xp):
a = xp.ones(self.input_shape)
self._test_mtsame(fft.ihfft, a, xp=xp)
@skip_xp_backends(np_only=True)
@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft])
def test_multiprocess(func, xp):
# Test that fft still works after fork (gh-10422)
with multiprocessing.Pool(2) as p:
res = p.map(func, [np.ones(100) for _ in range(4)])
expect = func(np.ones(100))
for x in res:
assert_allclose(x, expect)
| TestFFTThreadSafe |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/plugin_success.py | {
"start": 7543,
"end": 7774
} | class ____(BaseModel):
model_config = ConfigDict(populate_by_name=True)
my_field: str = Field(alias='my_alias')
m5 = Model5(my_field='foo')
# MYPY: error: Unexpected keyword argument "my_field" for "Model5" [call-arg]
| Model5 |
python | joke2k__faker | faker/providers/passport/__init__.py | {
"start": 187,
"end": 1507
} | class ____(BaseProvider):
"""Implement default Passport provider for Faker."""
passport_number_formats: ElementsType = ()
def passport_dob(self) -> datetime.date:
"""Generate a datetime date of birth."""
birthday = self.generator.date_of_birth()
return birthday
def passport_owner(self, gender: SexLiteral = "X") -> Tuple[str, str]:
"""Generate a given_name and surname for a passport owner
The ``gender`` argument is the gender marker of a passport owner, which is a one character string
that is either male, female, or non-binary.
"""
if gender == "M":
given_name = self.generator.parse("{{first_name_male}}")
elif gender == "F":
given_name = self.generator.parse("{{first_name_female}}")
else:
given_name = self.generator.parse("{{first_name_nonbinary}}")
surname = self.generator.parse("{{last_name}}")
return given_name, surname
def passport_number(self) -> str:
"""Generate a passport number by replacing tokens to be alphanumeric"""
temp = re.sub(
r"\?",
lambda x: self.random_element(ascii_uppercase),
self.random_element(self.passport_number_formats),
)
return self.numerify(temp)
| Provider |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/test_app.py | {
"start": 1753,
"end": 4386
} | class ____:
def test_correlation_id_echoed_in_response_headers(self, client):
"""Test that correlation-id from request is echoed back in response headers."""
correlation_id = "test-correlation-id-12345"
response = client.get("/execution/health", headers={"correlation-id": correlation_id})
assert response.status_code == 200
assert response.headers["correlation-id"] == correlation_id
def test_correlation_id_in_error_response_content(self, client):
"""Test that correlation-id is included in error response content."""
correlation_id = "error-test-correlation-id-67890"
# Force an error by calling a non-existent endpoint
response = client.get("/execution/non-existent-endpoint", headers={"correlation-id": correlation_id})
assert response.status_code == 404
# Correlation-id should still be in response headers from middleware
assert response.headers.get("correlation-id") == correlation_id
def test_correlation_id_propagates_through_request_lifecycle(self, client):
"""Test that correlation-id propagates through the entire request lifecycle."""
correlation_id = "lifecycle-test-correlation-id"
# Make a successful request
response = client.get("/execution/health", headers={"correlation-id": correlation_id})
assert response.status_code == 200
assert response.headers["correlation-id"] == correlation_id
# Make an error request (404)
response = client.get("/execution/nonexistent", headers={"correlation-id": correlation_id})
assert response.status_code == 404
assert response.headers["correlation-id"] == correlation_id
def test_multiple_requests_with_different_correlation_ids(self, client):
"""Test that different requests maintain their own correlation-ids."""
correlation_id_1 = "request-1-correlation-id"
correlation_id_2 = "request-2-correlation-id"
# Make first request
response1 = client.get("/execution/health", headers={"correlation-id": correlation_id_1})
assert response1.status_code == 200
assert response1.headers["correlation-id"] == correlation_id_1
# Make second request with different correlation-id
response2 = client.get("/execution/health", headers={"correlation-id": correlation_id_2})
assert response2.status_code == 200
assert response2.headers["correlation-id"] == correlation_id_2
# Verify they didn't interfere with each other
assert correlation_id_1 != correlation_id_2
| TestCorrelationIdMiddleware |
python | openai__openai-python | src/openai/types/responses/web_search_preview_tool.py | {
"start": 241,
"end": 917
} | class ____(BaseModel):
type: Literal["approximate"]
"""The type of location approximation. Always `approximate`."""
city: Optional[str] = None
"""Free text input for the city of the user, e.g. `San Francisco`."""
country: Optional[str] = None
"""
The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of
the user, e.g. `US`.
"""
region: Optional[str] = None
"""Free text input for the region of the user, e.g. `California`."""
timezone: Optional[str] = None
"""
The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the
user, e.g. `America/Los_Angeles`.
"""
| UserLocation |
python | huggingface__transformers | src/transformers/models/textnet/modeling_textnet.py | {
"start": 7949,
"end": 8111
} | class ____(PreTrainedModel):
config: TextNetConfig
base_model_prefix = "textnet"
main_input_name = "pixel_values"
@auto_docstring
| TextNetPreTrainedModel |
python | django__django | tests/distinct_on_fields/tests.py | {
"start": 393,
"end": 7866
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.t1 = Tag.objects.create(name="t1")
cls.t2 = Tag.objects.create(name="t2", parent=cls.t1)
cls.t3 = Tag.objects.create(name="t3", parent=cls.t1)
cls.t4 = Tag.objects.create(name="t4", parent=cls.t3)
cls.t5 = Tag.objects.create(name="t5", parent=cls.t3)
cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1")
cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1")
cls.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1")
cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2")
cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1)
cls.st1 = StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1)
StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1)
cls.celeb1 = Celebrity.objects.create(name="c1")
cls.celeb2 = Celebrity.objects.create(name="c2")
cls.fan1 = Fan.objects.create(fan_of=cls.celeb1)
cls.fan2 = Fan.objects.create(fan_of=cls.celeb1)
cls.fan3 = Fan.objects.create(fan_of=cls.celeb2)
def test_basic_distinct_on(self):
"""QuerySet.distinct('field', ...) works"""
# (qset, expected) tuples
qsets = (
(
Staff.objects.distinct().order_by("name"),
[self.p1_o1, self.p1_o2, self.p2_o1, self.p3_o1],
),
(
Staff.objects.distinct("name").order_by("name"),
[self.p1_o1, self.p2_o1, self.p3_o1],
),
(
Staff.objects.distinct("organisation").order_by("organisation", "name"),
[self.p1_o1, self.p1_o2],
),
(
Staff.objects.distinct("name", "organisation").order_by(
"name", "organisation"
),
[self.p1_o1, self.p1_o2, self.p2_o1, self.p3_o1],
),
(
Celebrity.objects.filter(fan__in=[self.fan1, self.fan2, self.fan3])
.distinct("name")
.order_by("name"),
[self.celeb1, self.celeb2],
),
# Does combining querysets work?
(
(
Celebrity.objects.filter(fan__in=[self.fan1, self.fan2])
.distinct("name")
.order_by("name")
| Celebrity.objects.filter(fan__in=[self.fan3])
.distinct("name")
.order_by("name")
),
[self.celeb1, self.celeb2],
),
(StaffTag.objects.distinct("staff", "tag"), [self.st1]),
(
Tag.objects.order_by("parent__pk", "pk").distinct("parent"),
(
[self.t2, self.t4, self.t1]
if connection.features.nulls_order_largest
else [self.t1, self.t2, self.t4]
),
),
(
StaffTag.objects.select_related("staff")
.distinct("staff__name")
.order_by("staff__name"),
[self.st1],
),
# Fetch the alphabetically first coworker for each worker
(
(
Staff.objects.distinct("id")
.order_by("id", "coworkers__name")
.values_list("id", "coworkers__name")
),
[(1, "p2"), (2, "p1"), (3, "p1"), (4, None)],
),
)
for qset, expected in qsets:
self.assertSequenceEqual(qset, expected)
self.assertEqual(qset.count(), len(expected))
# Combining queries with non-unique query is not allowed.
base_qs = Celebrity.objects.all()
msg = "Cannot combine a unique query with a non-unique query."
with self.assertRaisesMessage(TypeError, msg):
base_qs.distinct("id") & base_qs
# Combining queries with different distinct_fields is not allowed.
msg = "Cannot combine queries with different distinct fields."
with self.assertRaisesMessage(TypeError, msg):
base_qs.distinct("id") & base_qs.distinct("name")
# Test join unreffing
c1 = Celebrity.objects.distinct("greatest_fan__id", "greatest_fan__fan_of")
self.assertIn("OUTER JOIN", str(c1.query))
c2 = c1.distinct("pk")
self.assertNotIn("OUTER JOIN", str(c2.query))
def test_sliced_queryset(self):
msg = "Cannot create distinct fields once a slice has been taken."
with self.assertRaisesMessage(TypeError, msg):
Staff.objects.all()[0:5].distinct("name")
def test_transform(self):
new_name = self.t1.name.upper()
self.assertNotEqual(self.t1.name, new_name)
Tag.objects.create(name=new_name)
with register_lookup(CharField, Lower):
self.assertCountEqual(
Tag.objects.order_by().distinct("name__lower"),
[self.t1, self.t2, self.t3, self.t4, self.t5],
)
def test_distinct_not_implemented_checks(self):
# distinct + annotate not allowed
msg = "annotate() + distinct(fields) is not implemented."
with self.assertRaisesMessage(NotImplementedError, msg):
Celebrity.objects.annotate(Max("id")).distinct("id")[0]
with self.assertRaisesMessage(NotImplementedError, msg):
Celebrity.objects.distinct("id").annotate(Max("id"))[0]
# However this check is done only when the query executes, so you
# can use distinct() to remove the fields before execution.
Celebrity.objects.distinct("id").annotate(Max("id")).distinct()[0]
# distinct + aggregate not allowed
msg = "aggregate() + distinct(fields) not implemented."
with self.assertRaisesMessage(NotImplementedError, msg):
Celebrity.objects.distinct("id").aggregate(Max("id"))
def test_distinct_on_in_ordered_subquery(self):
qs = Staff.objects.distinct("name").order_by("name", "id")
qs = Staff.objects.filter(pk__in=qs).order_by("name")
self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1])
qs = Staff.objects.distinct("name").order_by("name", "-id")
qs = Staff.objects.filter(pk__in=qs).order_by("name")
self.assertSequenceEqual(qs, [self.p1_o2, self.p2_o1, self.p3_o1])
def test_distinct_on_get_ordering_preserved(self):
"""
Ordering shouldn't be cleared when distinct on fields are specified.
refs #25081
"""
staff = (
Staff.objects.distinct("name")
.order_by("name", "-organisation")
.get(name="p1")
)
self.assertEqual(staff.organisation, "o2")
def test_distinct_on_mixed_case_annotation(self):
qs = (
Staff.objects.annotate(
nAmEAlIaS=F("name"),
)
.distinct("nAmEAlIaS")
.order_by("nAmEAlIaS")
)
self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1])
def test_disallowed_update_distinct_on(self):
qs = Staff.objects.distinct("organisation").order_by("organisation")
msg = "Cannot call update() after .distinct(*fields)."
with self.assertRaisesMessage(TypeError, msg):
qs.update(name="p4")
| DistinctOnTests |
python | bokeh__bokeh | release/action.py | {
"start": 1225,
"end": 1326
} | class ____(ActionReturn):
""""""
kind = ActionResult.SKIP
ui = staticmethod(skipped)
| SKIPPED |
python | doocs__leetcode | solution/3000-3099/3095.Shortest Subarray With OR at Least K I/Solution.py | {
"start": 0,
"end": 674
} | class ____:
def minimumSubarrayLength(self, nums: List[int], k: int) -> int:
n = len(nums)
cnt = [0] * 32
ans = n + 1
s = i = 0
for j, x in enumerate(nums):
s |= x
for h in range(32):
if x >> h & 1:
cnt[h] += 1
while s >= k and i <= j:
ans = min(ans, j - i + 1)
y = nums[i]
for h in range(32):
if y >> h & 1:
cnt[h] -= 1
if cnt[h] == 0:
s ^= 1 << h
i += 1
return -1 if ans > n else ans
| Solution |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modular_qwen2_5_vl.py | {
"start": 3542,
"end": 3710
} | class ____(Qwen2VLConfig):
model_type = "qwen2_5_vl"
sub_configs = {"vision_config": Qwen2_5_VLVisionConfig, "text_config": Qwen2_5_VLTextConfig}
| Qwen2_5_VLConfig |
python | scikit-image__scikit-image | benchmarks/benchmark_filters.py | {
"start": 245,
"end": 536
} | class ____:
"""Benchmark for filter routines in scikit-image."""
def setup(self):
self.image = np.random.random((4000, 4000))
self.image[:2000, :2000] += 1
self.image[3000:, 3000] += 0.5
def time_sobel(self):
filters.sobel(self.image)
| FiltersSuite |
python | tensorflow__tensorflow | tensorflow/python/eager/benchmarks/resnet50/hvp_test.py | {
"start": 2868,
"end": 4375
} | class ____(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(
("forward_over_back_eager", _forward_over_back_hvp),
("forward_over_back_function", tf.function(_forward_over_back_hvp)),
("tf_gradients", tf.function(_tf_gradients_forward_over_back_hvp)),
("back_over_back_eager", _back_over_back_hvp),
("back_over_back_function", tf.function(_back_over_back_hvp)),
("back_over_forward_eager", _back_over_forward_hvp),
("back_over_forward_function", tf.function(_back_over_forward_hvp)))
def test_hvp_shapes(self, hvp_function):
device, data_format = resnet50_test_util.device_and_data_format()
model = resnet50.ResNet50(data_format)
with tf.device(device):
images, labels = resnet50_test_util.random_batch(2, data_format)
images = tf.constant(images)
labels = tf.constant(labels)
model.build(images.shape)
vector = [tf.ones_like(v) for v in model.trainable_variables]
# Note that numerical differences build up to quite large differences here
# in the final hvp. tensorflow/python/eager:forwardprop_test has a
# smaller-scale test that the computations are close on a much smaller but
# otherwise similar model.
hvp = hvp_function(model, images, labels, vector)
for hvp_component, variable in zip(hvp, model.trainable_variables):
self.assertEqual(hvp_component.shape, variable.shape)
self.assertEqual(hvp_component.dtype, variable.dtype)
| HVPTest |
python | django__django | tests/admin_filters/models.py | {
"start": 1699,
"end": 1917
} | class ____(models.Model):
code = models.CharField(max_length=4, unique=True)
description = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return self.description
| Department |
python | kamyu104__LeetCode-Solutions | Python/kth-largest-element-in-an-array.py | {
"start": 160,
"end": 1594
} | class ____(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
while mid <= right:
if nums[mid] == target:
mid += 1
elif compare(nums[mid], target):
nums[left], nums[mid] = nums[mid], nums[left]
left += 1
mid += 1
else:
nums[mid], nums[right] = nums[right], nums[mid]
right -= 1
return left, right
left, right = 0, len(nums)-1
while left <= right:
pivot_idx = randint(left, right)
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
if pivot_left <= n <= pivot_right:
return
elif pivot_left > n:
right = pivot_left-1
else: # pivot_right < n.
left = pivot_right+1
nth_element(nums, k-1, compare=lambda a, b: a > b)
return nums[k-1]
# Time: O(n) on average, using Median of Medians could achieve O(n) (Intro Select)
# Space: O(1)
| Solution |
python | doocs__leetcode | solution/1600-1699/1631.Path With Minimum Effort/Solution.py | {
"start": 639,
"end": 1330
} | class ____:
def minimumEffortPath(self, heights: List[List[int]]) -> int:
m, n = len(heights), len(heights[0])
uf = UnionFind(m * n)
e = []
dirs = (0, 1, 0)
for i in range(m):
for j in range(n):
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n:
e.append(
(abs(heights[i][j] - heights[x][y]), i * n + j, x * n + y)
)
e.sort()
for h, a, b in e:
uf.union(a, b)
if uf.connected(0, m * n - 1):
return h
return 0
| Solution |
python | getsentry__sentry | tests/sentry/core/endpoints/scim/test_scim_user_index.py | {
"start": 20737,
"end": 22023
} | class ____(SCIMAzureTestCase):
def test_user_index_get_no_active(self) -> None:
member = self.create_member(organization=self.organization, email="test.user@okta.local")
url = reverse("sentry-api-0-organization-scim-member-index", args=[self.organization.slug])
response = self.client.get(
f"{url}?startIndex=1&count=100&filter=userName%20eq%20%22test.user%40okta.local%22"
)
assert response.status_code == 200, response.content
assert response.data == {
"schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
"totalResults": 1,
"startIndex": 1,
"itemsPerPage": 1,
"Resources": [
{
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": str(member.id),
"userName": "test.user@okta.local",
"emails": [{"primary": True, "value": "test.user@okta.local", "type": "work"}],
"name": {"familyName": "N/A", "givenName": "N/A"},
"meta": {"resourceType": "User"},
"sentryOrgRole": self.organization.default_role,
}
],
}
@all_silo_test
| SCIMMemberIndexAzureTests |
python | getsentry__sentry | tests/sentry/api/endpoints/test_user_subscriptions.py | {
"start": 481,
"end": 2518
} | class ____(APITestCase):
endpoint = "sentry-api-0-user-subscriptions"
method = "put"
@pytest.fixture(autouse=True)
def enable_newsletter(self) -> Generator[None]:
with newsletter.backend.test_only__downcast_to(DummyNewsletter).enable():
yield
def setUp(self) -> None:
self.user = self.create_user(email="foo@example.com")
self.login_as(self.user)
def test_get_subscriptions(self) -> None:
self.get_success_response(self.user.id, method="get")
def test_subscribe(self) -> None:
self.get_success_response(self.user.id, listId="123", subscribed=True, status_code=204)
results = newsletter.backend.get_subscriptions(self.user)["subscriptions"]
assert len(results) == 1
assert results[0].list_id == 123
assert results[0].subscribed
assert results[0].verified
def test_requires_subscribed(self) -> None:
self.get_error_response(self.user.id, listId="123", status_code=400)
def test_unverified_emails(self) -> None:
UserEmail.objects.get(email=self.user.email).update(is_verified=False)
self.get_success_response(self.user.id, listId="123", subscribed=True, status_code=204)
def test_unsubscribe(self) -> None:
self.get_success_response(self.user.id, listId="123", subscribed=False, status_code=204)
results = newsletter.backend.get_subscriptions(self.user)["subscriptions"]
assert len(results) == 1
assert results[0].list_id == 123
assert not results[0].subscribed
assert results[0].verified
def test_default_subscription(self) -> None:
self.get_success_response(self.user.id, method="post", subscribed=True, status_code=204)
results = newsletter.backend.get_subscriptions(self.user)["subscriptions"]
assert len(results) == 1
assert results[0].list_id == newsletter.backend.get_default_list_id()
assert results[0].subscribed
assert results[0].verified
| UserSubscriptionsNewsletterTest |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 231656,
"end": 240818
} | class ____(torch.nn.Module):
def forward(self, L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_0_: "f32[3, 3, 3]", L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_1_: "f32[3, 3, 3]", L_flat_tangents_1_: "f32[3, 3, 3]"):
l_self_modules_fx_const_folded_attrs_parameters_0_ = L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_0_
l_self_modules_fx_const_folded_attrs_parameters_1_ = L_self_modules_FX_CONST_FOLDED_ATTRS_parameters_1_
l_flat_tangents_1_ = L_flat_tangents_1_
_new_zeros_with_same_feature_meta_default: "f32[3, 3, 3]" = torch.ops.aten._new_zeros_with_same_feature_meta.default(l_flat_tangents_1_, l_self_modules_fx_const_folded_attrs_parameters_0_); l_self_modules_fx_const_folded_attrs_parameters_0_ = None
copy__default: "f32[3, 3, 3]" = torch.ops.aten.copy_.default(_new_zeros_with_same_feature_meta_default, l_flat_tangents_1_); _new_zeros_with_same_feature_meta_default = l_flat_tangents_1_ = None
mul_tensor: "f32[3, 3, 3]" = torch.ops.aten.mul.Tensor(copy__default, l_self_modules_fx_const_folded_attrs_parameters_1_); copy__default = l_self_modules_fx_const_folded_attrs_parameters_1_ = None
return (mul_tensor,)
""",
)
@config.patch(error_on_recompile=True)
def test_vmap_recompile(self):
@torch.compile(backend="eager")
def fn(x):
return torch.vmap(lambda x: x.sin())(x)
x = torch.zeros(3, 3, 4, 5)
torch.vmap(fn)(x)
# should not recompile on second call. See Pytorch issue #118493
torch.vmap(fn)(x)
@xfailIfTorchDynamo
@config.patch(error_on_recompile=True)
def test_vmap_recompile_different_config(self):
@torch.compile(backend="eager")
def fn(x):
return torch.vmap(lambda x: x.sin())(x)
x = torch.zeros(3, 3, 4, 5)
torch.vmap(fn)(x)
with self.assertRaises(torch._dynamo.exc.RecompileError):
fn(x)
@config.patch(error_on_recompile=True)
def test_vmap_recompile_same_config(self):
@torch.compile(backend="eager")
def fn(x):
return torch.vmap(lambda x: x.sin())(x)
x = torch.zeros(3, 3, 4, 5)
torch.vmap(torch.vmap(fn, randomness="same"), randomness="same")(x)
with self.assertRaises(torch._dynamo.exc.RecompileError):
torch.vmap(torch.vmap(fn, randomness="same"), randomness="error")(x)
@config.patch(error_on_recompile=True)
def test_vmap_recompile_with_randomness(self):
@torch.compile(backend="eager")
def fn(x):
return torch.vmap(lambda x: x.sin())(x)
x = torch.zeros(3, 3, 4, 5)
torch.vmap(fn, randomness="same")(x)
with self.assertRaises(torch._dynamo.exc.RecompileError):
torch.vmap(fn, randomness="different")(x)
def test_vmap_call_torch_compile_fn(self):
def wrapped_fn(x):
return x.sin()
x = torch.randn(3, 4)
fn = torch.compile(backend="aot_eager", fullgraph=True)(wrapped_fn)
with self.assertRaisesRegex(
torch._dynamo.exc.Unsupported,
"Calling torch.func.vmap\\(compiled_fn\\) function from eager mode is not supported",
):
torch.func.vmap(fn)(x)
def test_vmap_call_compiled_backward_fn(self):
# See PyTorch issue #138422
@torch.compile
def f(x):
return x**2
x = torch.randn(2, requires_grad=True)
y = f(x)
def get_vjp(v):
return torch.autograd.grad(y, x, v)
with self.assertRaisesRegex(
RuntimeError,
"It looks like you're trying to call a compiled backward function within vmap/grad/vjp, which isn't supported",
):
torch.func.vjp(get_vjp, x)
def test_vjp_call_compiled_backward_fn(self):
# See PyTorch issue #138422
@torch.compile
def f(x):
return x**2
x = torch.randn(2, requires_grad=True)
y = f(x)
def get_vjp(v):
return torch.autograd.grad(y, x, v)
with self.assertRaisesRegex(
RuntimeError,
"It looks like you're trying to call a compiled backward function within vmap/grad/vjp, which isn't supported",
):
torch.func.vjp(get_vjp, x)
def test_grad_call_compiled_backward_fn(self):
# See PyTorch issue #138422
@torch.compile
def f(x):
return x**2
x = torch.randn(2, requires_grad=True)
y = f(x)
def get_vjp(v):
return torch.autograd.grad(y, x, v)
with self.assertRaisesRegex(
RuntimeError,
"It looks like you're trying to call a compiled backward function within vmap/grad/vjp, which isn't supported",
):
torch.func.grad(get_vjp)(x)
def test_grad_call_torch_compile_fn(self):
def wrapped_fn(x):
return x.sin().sum()
x = torch.randn(3, 4)
fn = torch.compile(backend="aot_eager", fullgraph=True)(wrapped_fn)
with self.assertRaisesRegex(
torch._dynamo.exc.Unsupported,
"Calling torch.func.grad\\(compiled_fn\\) function from eager mode is not supported",
):
torch.func.grad(fn)(x)
def test_jvp_call_torch_compile_fn(self):
def wrapped_fn(x):
return x.sin().sum()
x = torch.randn(3, 4)
fn = torch.compile(backend="aot_eager", fullgraph=True)(wrapped_fn)
with self.assertRaisesRegex(
torch._dynamo.exc.Unsupported,
"Calling torch.func.jvp\\(compiled_fn\\) function from eager mode is not supported",
):
torch.func.jvp(fn, (x,), (x,))
@config.patch(error_on_recompile=True)
def test_grad_recompile(self):
@torch.compile(backend="eager")
def fn(x):
return torch.func.grad(torch.sin)(x)
x = torch.randn([])
torch.func.grad(fn)(x)
# should not recompile on second call
torch.func.grad(fn)(x)
def test_vmap_get_wrapped(self):
counters.clear()
def g(x):
return x.sin()
@torch.compile(backend="aot_eager", fullgraph=True)
def fn():
return torch.vmap(g)
x = torch.randn(3, 4)
expected = torch.vmap(g)(x)
wrapper = fn()
got = wrapper(x)
self.assertEqual(expected, got)
def test_vmap_with_conditional_graph_break(self):
def g(x):
if len(x.shape) < 2:
torch._dynamo.graph_break()
return x.sin()
else:
return x.cos()
@torch.compile(backend="aot_eager")
def fn(x):
return torch.vmap(g)(x)
counters.clear()
x = torch.randn(2, 3)
expected = x.sin()
got = fn(x)
self.assertEqual(expected, got)
self.assertEqual(len(counters["graph_break"]), 1)
counters.clear()
y = torch.randn(2, 3, 4)
expected = y.cos()
got = fn(y)
self.assertEqual(expected, got)
self.assertEqual(len(counters["graph_break"]), 0)
def test_vmap_with_graph_break(self):
counters.clear()
def g(x):
y = x.cos()
print("hi")
return y.sin()
def fn(x):
return torch.vmap(g)(x)
x = torch.randn(3, 4)
opt = torch.compile(fn, backend="aot_eager", fullgraph=False)
expected = fn(x)
got = opt(x)
self.assertEqual(len(counters["graph_break"]), 1)
self.assertEqual(expected, got)
def test_vmap_with_graph_break_2(self):
counters.clear()
def cos(x):
print("cos")
return x.cos()
def sin(x):
print("sin")
return x.sin()
def g(x):
y = cos(x)
return sin(y)
def fn(x):
return torch.vmap(g, randomness="same")(x)
x = torch.randn(3, 4)
opt = torch.compile(fn, backend="aot_eager", fullgraph=False)
expected = fn(x)
got = opt(x)
self.assertEqual(len(counters["graph_break"]), 1)
self.assertEqual(expected, got)
def test_vmap_with_graph_break_lambda(self):
counters.clear()
def sin(x):
print("sin")
return x.sin()
def fn(x):
return torch.vmap(lambda x: sin(x))(x)
x = torch.randn(3, 4)
opt = torch.compile(fn, backend="aot_eager", fullgraph=False)
expected = fn(x)
got = opt(x)
self.assertEqual(len(counters["graph_break"]), 1)
self.assertEqual(expected, got)
def test_vmap(self):
def fn(x):
return torch.func.vmap(lambda x: x.sum(0) + x.sum(1))(x)
x = torch.randn(3, 3, 3)
wrapped_gm = self._compile_check(fn, (x,))
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | pypa__pip | src/pip/_vendor/urllib3/util/timeout.py | {
"start": 459,
"end": 10168
} | class ____(object):
"""Timeout configuration.
Timeouts can be defined as a default for a pool:
.. code-block:: python
timeout = Timeout(connect=2.0, read=7.0)
http = PoolManager(timeout=timeout)
response = http.request('GET', 'http://example.com/')
Or per-request (which overrides the default for the pool):
.. code-block:: python
response = http.request('GET', 'http://example.com/', timeout=Timeout(10))
Timeouts can be disabled by setting all the parameters to ``None``:
.. code-block:: python
no_timeout = Timeout(connect=None, read=None)
response = http.request('GET', 'http://example.com/, timeout=no_timeout)
:param total:
This combines the connect and read timeouts into one; the read timeout
will be set to the time leftover from the connect attempt. In the
event that both a connect timeout and a total are specified, or a read
timeout and a total are specified, the shorter timeout will be applied.
Defaults to None.
:type total: int, float, or None
:param connect:
The maximum amount of time (in seconds) to wait for a connection
attempt to a server to succeed. Omitting the parameter will default the
connect timeout to the system default, probably `the global default
timeout in socket.py
<http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
None will set an infinite timeout for connection attempts.
:type connect: int, float, or None
:param read:
The maximum amount of time (in seconds) to wait between consecutive
read operations for a response from the server. Omitting the parameter
will default the read timeout to the system default, probably `the
global default timeout in socket.py
<http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.
None will set an infinite timeout.
:type read: int, float, or None
.. note::
Many factors can affect the total amount of time for urllib3 to return
an HTTP response.
For example, Python's DNS resolver does not obey the timeout specified
on the socket. Other factors that can affect total request time include
high CPU load, high swap, the program running at a low priority level,
or other behaviors.
In addition, the read and total timeouts only measure the time between
read operations on the socket connecting the client and the server,
not the total amount of time for the request to return a complete
response. For most requests, the timeout is raised because the server
has not sent the first byte in the specified time. This is not always
the case; if a server streams one byte every fifteen seconds, a timeout
of 20 seconds will not trigger, even though the request will take
several minutes to complete.
If your goal is to cut off any request after a set amount of wall clock
time, consider having a second "watcher" thread to cut off a slow
request.
"""
#: A sentinel object representing the default timeout value
DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT
def __init__(self, total=None, connect=_Default, read=_Default):
self._connect = self._validate_timeout(connect, "connect")
self._read = self._validate_timeout(read, "read")
self.total = self._validate_timeout(total, "total")
self._start_connect = None
def __repr__(self):
return "%s(connect=%r, read=%r, total=%r)" % (
type(self).__name__,
self._connect,
self._read,
self.total,
)
# __str__ provided for backwards compatibility
__str__ = __repr__
@classmethod
def resolve_default_timeout(cls, timeout):
return getdefaulttimeout() if timeout is cls.DEFAULT_TIMEOUT else timeout
@classmethod
def _validate_timeout(cls, value, name):
"""Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated and casted version of the given value.
:raises ValueError: If it is a numeric value less than or equal to
zero, or the type is not an integer, float, or None.
"""
if value is _Default:
return cls.DEFAULT_TIMEOUT
if value is None or value is cls.DEFAULT_TIMEOUT:
return value
if isinstance(value, bool):
raise ValueError(
"Timeout cannot be a boolean value. It must "
"be an int, float or None."
)
try:
float(value)
except (TypeError, ValueError):
raise ValueError(
"Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value)
)
try:
if value <= 0:
raise ValueError(
"Attempted to set %s timeout to %s, but the "
"timeout cannot be set to a value less "
"than or equal to 0." % (name, value)
)
except TypeError:
# Python 3
raise ValueError(
"Timeout value %s was %s, but it must be an "
"int, float or None." % (name, value)
)
return value
@classmethod
def from_float(cls, timeout):
"""Create a new Timeout from a legacy timeout value.
The timeout value used by httplib.py sets the same timeout on the
connect(), and recv() socket requests. This creates a :class:`Timeout`
object that sets the individual timeouts to the ``timeout`` value
passed to this function.
:param timeout: The legacy timeout value.
:type timeout: integer, float, sentinel default object, or None
:return: Timeout object
:rtype: :class:`Timeout`
"""
return Timeout(read=timeout, connect=timeout)
def clone(self):
"""Create a copy of the timeout object
Timeout properties are stored per-pool but each request needs a fresh
Timeout object to ensure each one has its own start/stop configured.
:return: a copy of the timeout object
:rtype: :class:`Timeout`
"""
# We can't use copy.deepcopy because that will also create a new object
# for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to
# detect the user default.
return Timeout(connect=self._connect, read=self._read, total=self.total)
def start_connect(self):
"""Start the timeout clock, used during a connect() attempt
:raises urllib3.exceptions.TimeoutStateError: if you attempt
to start a timer that has been started already.
"""
if self._start_connect is not None:
raise TimeoutStateError("Timeout timer has already been started.")
self._start_connect = current_time()
return self._start_connect
def get_connect_duration(self):
"""Gets the time elapsed since the call to :meth:`start_connect`.
:return: Elapsed time in seconds.
:rtype: float
:raises urllib3.exceptions.TimeoutStateError: if you attempt
to get duration for a timer that hasn't been started.
"""
if self._start_connect is None:
raise TimeoutStateError(
"Can't get connect duration for timer that has not started."
)
return current_time() - self._start_connect
@property
def connect_timeout(self):
"""Get the value to use when setting a connection timeout.
This will be a positive float or integer, the value None
(never timeout), or the default system timeout.
:return: Connect timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
"""
if self.total is None:
return self._connect
if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:
return self.total
return min(self._connect, self.total)
@property
def read_timeout(self):
"""Get the value for the read timeout.
This assumes some time has elapsed in the connection timeout and
computes the read timeout appropriately.
If self.total is set, the read timeout is dependent on the amount of
time taken by the connect timeout. If the connection time has not been
established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be
raised.
:return: Value to use for the read timeout.
:rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
:raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`
has not yet been called on this object.
"""
if (
self.total is not None
and self.total is not self.DEFAULT_TIMEOUT
and self._read is not None
and self._read is not self.DEFAULT_TIMEOUT
):
# In case the connect timeout has not yet been established.
if self._start_connect is None:
return self._read
return max(0, min(self.total - self.get_connect_duration(), self._read))
elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:
return max(0, self.total - self.get_connect_duration())
else:
return self._read
| Timeout |
python | dagster-io__dagster | python_modules/libraries/dagster-sling/dagster_sling/dagster_sling_translator.py | {
"start": 384,
"end": 21428
} | class ____:
target_prefix: str = "target"
@public
def get_asset_spec(self, stream_definition: Mapping[str, Any]) -> AssetSpec:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetSpec.
The stream definition is a dictionary key/value pair where the key is the stream name and
the value is a dictionary representing the Sling Replication Stream Config.
"""
return AssetSpec(
key=self._resolve_back_compat_method(
"get_asset_key", self._default_asset_key_fn, stream_definition
),
deps=self._resolve_back_compat_method(
"get_deps_asset_key", self._default_deps_fn, stream_definition
),
description=self._resolve_back_compat_method(
"get_description", self._default_description_fn, stream_definition
),
metadata=self._resolve_back_compat_method(
"get_metadata", self._default_metadata_fn, stream_definition
),
tags=self._resolve_back_compat_method(
"get_tags", self._default_tags_fn, stream_definition
),
kinds=self._resolve_back_compat_method(
"get_kinds", self._default_kinds_fn, stream_definition
),
group_name=self._resolve_back_compat_method(
"get_group_name", self._default_group_name_fn, stream_definition
),
auto_materialize_policy=self._resolve_back_compat_method(
"get_auto_materialize_policy",
self._default_auto_materialize_policy_fn,
stream_definition,
),
)
def _resolve_back_compat_method(
self,
method_name: str,
default_fn: Callable[[Mapping[str, Any]], Any],
stream_definition: Mapping[str, Any],
):
method = getattr(type(self), method_name)
base_method = getattr(DagsterSlingTranslator, method_name)
if method is not base_method: # user defined this
supersession_warning(
subject=method_name,
additional_warn_text=(
f"Instead of overriding DagsterSlingTranslator.{method_name}(), "
f"override DagsterSlingTranslator.get_asset_spec()."
),
)
return method(self, stream_definition)
else:
return default_fn(stream_definition)
@public
def sanitize_stream_name(self, stream_name: str) -> str:
"""A function that takes a stream name from a Sling replication config and returns a
sanitized name for the stream.
By default, this removes any non-alphanumeric characters from the stream name and replaces
them with underscores, while removing any double quotes.
Args:
stream_name (str): The name of the stream.
Examples:
Using a custom stream name sanitizer:
.. code-block:: python
class CustomSlingTranslator(DagsterSlingTranslator):
def sanitize_stream_name(self, stream_name: str) -> str:
return stream_name.replace(".", "")
"""
return clean_name_lower_with_dots(name=stream_name.replace('"', ""))
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).key` instead.",
)
@public
def get_asset_key(self, stream_definition: Mapping[str, Any]) -> AssetKey:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetKey.
The stream definition is a dictionary key/value pair where the key is the stream name and
the value is a dictionary representing the Sling Replication Stream Config.
For example:
.. code-block:: python
stream_definition = {"public.users":
{'sql': 'select all_user_id, name from public."all_Users"',
'object': 'public.all_users'}
}
By default, this returns the class's target_prefix parameter concatenated with the stream name.
A stream named "public.accounts" will create an AssetKey named "target_public_accounts".
Override this function to customize how to map a Sling stream to a Dagster AssetKey.
Alternatively, you can provide metadata in your Sling replication config to specify the
Dagster AssetKey for a stream as follows:
.. code-block:: yaml
public.users:
meta:
dagster:
asset_key: "mydb_users"
Args:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition
Returns:
AssetKey: The Dagster AssetKey for the replication stream.
Examples:
Using a custom mapping for streams:
.. code-block:: python
class CustomSlingTranslator(DagsterSlingTranslator):
def get_asset_spec(self, stream_definition: Mapping[str, Any]) -> AssetKey:
default_spec = super().get_asset_spec(stream_definition)
map = {"stream1": "asset1", "stream2": "asset2"}
return default_spec.replace_attributes(key=AssetKey(map[stream_definition["name"]]))
"""
return self._default_asset_key_fn(stream_definition)
def _default_asset_key_fn(self, stream_definition: Mapping[str, Any]) -> AssetKey:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetKey.
The stream definition is a dictionary key/value pair where the key is the stream name and
the value is a dictionary representing the Sling Replication Stream Config.
For example:
.. code-block:: python
stream_definition = {"public.users":
{'sql': 'select all_user_id, name from public."all_Users"',
'object': 'public.all_users'}
}
This returns the class's target_prefix parameter concatenated with the stream name.
A stream named "public.accounts" will create an AssetKey named "target_public_accounts".
Alternatively, you can provide metadata in your Sling replication config to specify the
Dagster AssetKey for a stream as follows:
.. code-block:: yaml
public.users:
meta:
dagster:
asset_key: "mydb_users"
Args:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition
Returns:
AssetKey: The Dagster AssetKey for the replication stream.
Examples:
Using a custom mapping for streams:
.. code-block:: python
class CustomSlingTranslator(DagsterSlingTranslator):
def get_asset_spec(self, stream_definition: Mapping[str, Any]) -> AssetKey:
default_spec = super().get_asset_spec(stream_definition)
map = {"stream1": "asset1", "stream2": "asset2"}
return default_spec.replace_attributes(key=AssetKey(map[stream_definition["name"]]))
"""
config = stream_definition.get("config", {}) or {}
object_key = config.get("object")
meta = config.get("meta", {})
asset_key = meta.get("dagster", {}).get("asset_key")
if asset_key:
if self.sanitize_stream_name(asset_key) != asset_key:
raise ValueError(
f"Asset key {asset_key} for stream {stream_definition['name']} is not "
"sanitized. Please use only alphanumeric characters and underscores."
)
return AssetKey(asset_key.split("."))
# You can override the Sling Replication default object with an object key
stream_name = object_key or stream_definition["name"]
sanitized_components = self.sanitize_stream_name(stream_name).split(".")
return AssetKey([self.target_prefix] + sanitized_components)
@superseded(
additional_warn_text=(
"Iterate over `DagsterSlingTranslator.get_asset_spec(...).deps` to access `AssetDep.asset_key` instead."
),
)
@public
def get_deps_asset_key(self, stream_definition: Mapping[str, Any]) -> Iterable[AssetKey]:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetKey for each dependency of the replication stream.
By default, this returns the stream name. For example, a stream named "public.accounts"
will create an AssetKey named "target_public_accounts" and a dependency named "public_accounts".
Override this function to customize how to map a Sling stream to a Dagster dependency.
Alternatively, you can provide metadata in your Sling replication config to specify the
Dagster AssetKey for a stream as follows:
.. code-block:: yaml
public.users:
meta:
dagster:
deps: "sourcedb_users"
Args:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition
Returns:
Iterable[AssetKey]: A list of Dagster AssetKey for each dependency of the replication stream.
"""
return self._default_deps_fn(stream_definition)
def _default_deps_fn(self, stream_definition: Mapping[str, Any]) -> Iterable[AssetKey]:
"""A function that takes a stream definition from a Sling replication config and returns a
Dagster AssetKey for each dependency of the replication stream.
This returns the stream name. For example, a stream named "public.accounts"
will create an AssetKey named "target_public_accounts" and a dependency named "public_accounts".
Alternatively, you can provide metadata in your Sling replication config to specify the
Dagster AssetKey for a stream as follows:
.. code-block:: yaml
public.users:
meta:
dagster:
deps: "sourcedb_users"
Args:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition
Returns:
Iterable[AssetKey]: A list of Dagster AssetKey for each dependency of the replication stream.
"""
config = stream_definition.get("config", {}) or {}
meta = config.get("meta", {})
deps = meta.get("dagster", {}).get("deps")
deps_out = []
if deps and isinstance(deps, str):
deps = [deps]
if deps:
assert isinstance(deps, list)
for asset_key in deps:
if self.sanitize_stream_name(asset_key) != asset_key:
raise ValueError(
f"Deps Asset key {asset_key} for stream {stream_definition['name']} is not "
"sanitized. Please use only alphanumeric characters and underscores."
)
deps_out.append(AssetKey(asset_key.split(".")))
return deps_out
stream_name = stream_definition["name"]
components = self.sanitize_stream_name(stream_name).split(".")
return [AssetKey(components)]
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).description` instead.",
)
@public
def get_description(self, stream_definition: Mapping[str, Any]) -> Optional[str]:
"""Retrieves the description for a given stream definition.
This method checks the provided stream definition for a description. It first looks
for an "sql" key in the configuration and returns its value if found. If not, it looks
for a description in the metadata under the "dagster" key.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[str]: The description of the stream if found, otherwise None.
"""
return self._default_description_fn(stream_definition)
def _default_description_fn(self, stream_definition: Mapping[str, Any]) -> Optional[str]:
"""Retrieves the description for a given stream definition.
This method checks the provided stream definition for a description. It first looks
for an "sql" key in the configuration and returns its value if found. If not, it looks
for a description in the metadata under the "dagster" key.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[str]: The description of the stream if found, otherwise None.
"""
config = stream_definition.get("config", {}) or {}
if "sql" in config:
return config["sql"]
meta = config.get("meta", {})
description = meta.get("dagster", {}).get("description")
return description
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).metadata` instead.",
)
@public
def get_metadata(self, stream_definition: Mapping[str, Any]) -> Mapping[str, Any]:
"""Retrieves the metadata for a given stream definition.
This method extracts the configuration from the provided stream definition and returns
it as a JSON metadata value.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Mapping[str, Any]: A dictionary containing the stream configuration as JSON metadata.
"""
return self._default_metadata_fn(stream_definition)
def _default_metadata_fn(self, stream_definition: Mapping[str, Any]) -> Mapping[str, Any]:
"""Retrieves the metadata for a given stream definition.
This method extracts the configuration from the provided stream definition and returns
it as a JSON metadata value.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Mapping[str, Any]: A dictionary containing the stream configuration as JSON metadata.
"""
return {"stream_config": MetadataValue.json(stream_definition.get("config", {}))}
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).tags` instead.",
)
@public
def get_tags(self, stream_definition: Mapping[str, Any]) -> Mapping[str, Any]:
"""Retrieves the tags for a given stream definition.
This method returns an empty dictionary, indicating that no tags are associated with
the stream definition by default. This method can be overridden to provide custom tags.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Mapping[str, Any]: An empty dictionary.
"""
return self._default_tags_fn(stream_definition)
def _default_tags_fn(self, stream_definition: Mapping[str, Any]) -> Mapping[str, Any]:
"""Retrieves the tags for a given stream definition.
This method returns an empty dictionary, indicating that no tags are associated with
the stream definition by default. This method can be overridden to provide custom tags.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Mapping[str, Any]: An empty dictionary.
"""
return {}
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).kinds` instead.",
)
@public
def get_kinds(self, stream_definition: Mapping[str, Any]) -> set[str]:
"""Retrieves the kinds for a given stream definition.
This method returns "sling" by default. This method can be overridden to provide custom kinds.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Set[str]: A set containing kinds for the stream's assets.
"""
return self._default_kinds_fn(stream_definition)
def _default_kinds_fn(self, stream_definition: Mapping[str, Any]) -> set[str]:
"""Retrieves the kinds for a given stream definition.
This method returns "sling" by default. This method can be overridden to provide custom kinds.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Set[str]: A set containing kinds for the stream's assets.
"""
return {"sling"}
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).group_name` instead.",
)
@public
def get_group_name(self, stream_definition: Mapping[str, Any]) -> Optional[str]:
"""Retrieves the group name for a given stream definition.
This method checks the provided stream definition for a group name in the metadata
under the "dagster" key.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[str]: The group name if found, otherwise None.
"""
return self._default_group_name_fn(stream_definition)
def _default_group_name_fn(self, stream_definition: Mapping[str, Any]) -> Optional[str]:
"""Retrieves the group name for a given stream definition.
This method checks the provided stream definition for a group name in the metadata
under the "dagster" key.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[str]: The group name if found, otherwise None.
"""
config = stream_definition.get("config", {}) or {}
meta = config.get("meta", {})
return meta.get("dagster", {}).get("group")
@superseded(
additional_warn_text="Use `DagsterSlingTranslator.get_asset_spec(...).auto_materialize_policy` instead.",
)
@public
def get_auto_materialize_policy(
self, stream_definition: Mapping[str, Any]
) -> Optional[AutoMaterializePolicy]:
"""Defines the auto-materialize policy for a given stream definition.
This method checks the provided stream definition for a specific configuration
indicating an auto-materialize policy. If the configuration is found, it returns
an eager auto-materialize policy. Otherwise, it returns None.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[AutoMaterializePolicy]: An eager auto-materialize policy if the configuration
is found, otherwise None.
"""
return self._default_auto_materialize_policy_fn(stream_definition)
def _default_auto_materialize_policy_fn(
self, stream_definition: Mapping[str, Any]
) -> Optional[AutoMaterializePolicy]:
"""Defines the auto-materialize policy for a given stream definition.
This method checks the provided stream definition for a specific configuration
indicating an auto-materialize policy. If the configuration is found, it returns
an eager auto-materialize policy. Otherwise, it returns None.
Parameters:
stream_definition (Mapping[str, Any]): A dictionary representing the stream definition,
which includes configuration details.
Returns:
Optional[AutoMaterializePolicy]: An eager auto-materialize policy if the configuration
is found, otherwise None.
"""
config = stream_definition.get("config", {}) or {}
meta = config.get("meta", {})
auto_materialize_policy_config = "auto_materialize_policy" in meta.get("dagster", {})
if auto_materialize_policy_config:
return AutoMaterializePolicy.eager()
| DagsterSlingTranslator |
python | huggingface__transformers | src/transformers/models/gptj/modeling_gptj.py | {
"start": 19029,
"end": 30479
} | class ____(GPTJPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.embed_dim = config.n_embd
self.vocab_size = config.vocab_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
self.drop = nn.Dropout(config.embd_pdrop)
self.h = nn.ModuleList([GPTJBlock(config, layer_idx=i) for i in range(config.n_layer)])
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.wte
def set_input_embeddings(self, new_embeddings):
self.wte = new_embeddings
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.FloatTensor] = None,
token_type_ids: Optional[torch.LongTensor] = None,
position_ids: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
) -> Union[tuple, BaseModelOutputWithPast]:
r"""
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_dim)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
model's internal embedding lookup matrix.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if self.gradient_checkpointing and self.training:
if use_cache:
logger.warning_once(
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
)
use_cache = False
if inputs_embeds is None:
inputs_embeds = self.wte(input_ids)
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
seq_length = inputs_embeds.shape[1]
if cache_position is None:
past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_key_values_length, past_key_values_length + seq_length, device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
causal_mask = self._update_causal_mask(
attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
)
hidden_states = inputs_embeds
if token_type_ids is not None:
token_type_ids = token_type_ids.view(-1, seq_length)
token_type_embeds = self.wte(token_type_ids)
hidden_states = hidden_states + token_type_embeds
hidden_states = self.drop(hidden_states)
output_shape = (-1, seq_length, hidden_states.size(-1))
all_self_attentions = () if output_attentions else None
all_hidden_states = () if output_hidden_states else None
for i, block in enumerate(self.h):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
outputs = block(
hidden_states,
layer_past=past_key_values,
attention_mask=causal_mask,
position_ids=position_ids,
use_cache=use_cache,
output_attentions=output_attentions,
cache_position=cache_position,
)
hidden_states = outputs[0]
if output_attentions:
all_self_attentions = all_self_attentions + (outputs[1],)
hidden_states = self.ln_f(hidden_states)
hidden_states = hidden_states.view(output_shape)
# Add last hidden state
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(
v for v in [hidden_states, past_key_values, all_hidden_states, all_self_attentions] if v is not None
)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
def _update_causal_mask(
self,
attention_mask: Union[torch.Tensor, "BlockMask"],
input_tensor: torch.Tensor,
cache_position: torch.Tensor,
past_key_values: Cache,
output_attentions: bool = False,
):
if self.config._attn_implementation == "flash_attention_2":
if attention_mask is not None and (attention_mask == 0.0).any():
return attention_mask
return None
if self.config._attn_implementation == "flex_attention":
if isinstance(attention_mask, torch.Tensor):
attention_mask = make_flex_block_causal_mask(attention_mask)
return attention_mask
# For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
# order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
# to infer the attention mask.
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
using_compilable_cache = past_key_values.is_compileable if past_key_values is not None else False
# When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
if self.config._attn_implementation == "sdpa" and not using_compilable_cache and not output_attentions:
if AttentionMaskConverter._ignore_causal_mask_sdpa(
attention_mask,
inputs_embeds=input_tensor,
past_key_values_length=past_seen_tokens,
is_training=self.training,
):
return None
dtype = input_tensor.dtype
sequence_length = input_tensor.shape[1]
if using_compilable_cache:
target_length = past_key_values.get_max_cache_shape()
else:
target_length = (
attention_mask.shape[-1]
if isinstance(attention_mask, torch.Tensor)
else past_seen_tokens + sequence_length + 1
)
# In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
attention_mask,
sequence_length=sequence_length,
target_length=target_length,
dtype=dtype,
cache_position=cache_position,
batch_size=input_tensor.shape[0],
)
if (
self.config._attn_implementation == "sdpa"
and attention_mask is not None
and attention_mask.device.type in ["cuda", "xpu", "npu"]
and not output_attentions
):
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
# Details: https://github.com/pytorch/pytorch/issues/110213
min_dtype = torch.finfo(dtype).min
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
return causal_mask
@staticmethod
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
cache_position: torch.Tensor,
batch_size: int,
**kwargs,
):
"""
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
`(batch_size, 1, query_length, key_value_length)`.
sequence_length (`int`):
The sequence length being processed.
target_length (`int`):
The target length: when generating with static cache, the mask should be as long as the static cache,
to account for the 0 padding, the part of the cache that is not filled yet.
dtype (`torch.dtype`):
The dtype to use for the 4D attention mask.
cache_position (`torch.Tensor`):
Indices depicting the position of the input sequence tokens in the sequence.
batch_size (`torch.Tensor`):
Batch size.
"""
if attention_mask is not None and attention_mask.dim() == 4:
# In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
causal_mask = attention_mask
else:
min_dtype = torch.finfo(dtype).min
causal_mask = torch.full(
(sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
)
if sequence_length != 1:
causal_mask = torch.triu(causal_mask, diagonal=1)
causal_mask *= torch.arange(target_length, device=cache_position.device) > cache_position.reshape(-1, 1)
causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
if attention_mask is not None:
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
mask_length = attention_mask.shape[-1]
padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
causal_mask.device
)
padding_mask = padding_mask == 0
causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
padding_mask, min_dtype
)
return causal_mask
@auto_docstring(
custom_intro="""
The GPT-J Model transformer with a language modeling head on top.
"""
)
| GPTJModel |
python | astropy__astropy | astropy/coordinates/solar_system.py | {
"start": 2413,
"end": 18562
} | class ____(ScienceState):
"""Default ephemerides for calculating positions of Solar-System bodies.
This can be one of the following:
- 'builtin': polynomial approximations to the orbital elements.
- 'dexxx[s]', for a JPL dynamical model, where xxx is the three digit
version number (e.g. de430), and the 's' is optional to specify the
'small' version of a kernel. The version number must correspond to an
ephemeris file available at:
https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/
- 'jpl': Alias for the default JPL ephemeris (currently, 'de430').
- URL: (str) The url to a SPK ephemeris in SPICE binary (.bsp) format.
- PATH: (str) File path to a SPK ephemeris in SPICE binary (.bsp) format.
- `None`: Ensure an Exception is raised without an explicit ephemeris.
The default is 'builtin', which uses the ``epv00`` and ``plan94``
routines from the ``erfa`` implementation of the Standards Of Fundamental
Astronomy library.
Notes
-----
Any file required will be downloaded (and cached) when the state is set.
The default Satellite Planet Kernel (SPK) file from NASA JPL (de430) is
~120MB, and covers years ~1550-2650 CE [1]_. The smaller de432s file is
~10MB, and covers years 1950-2050 [2]_ (and similarly for the newer de440
and de440s). Older versions of the JPL ephemerides (such as the widely
used de200) can be used via their URL [3]_.
.. [1] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de430-de431.txt
.. [2] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/aareadme_de432s.txt
.. [3] https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/
"""
_value = "builtin"
_kernel = None
@classmethod
def validate(cls, value):
# make no changes if value is None
if value is None:
return cls._value
# Set up Kernel; if the file is not in cache, this will download it.
cls.get_kernel(value)
return value
@classmethod
def get_kernel(cls, value):
# ScienceState only ensures the `_value` attribute is up to date,
# so we need to be sure any kernel returned is consistent.
if cls._kernel is None or cls._kernel.origin != value:
if cls._kernel is not None:
cls._kernel.daf.file.close()
cls._kernel = None
kernel = _get_kernel(value)
if kernel is not None:
kernel.origin = value
cls._kernel = kernel
return cls._kernel
@classproperty
def kernel(cls):
return cls.get_kernel(cls._value)
@classproperty
def bodies(cls):
if cls._value is None:
return None
if cls._value.lower() == "builtin":
return ("earth", "sun", "moon") + tuple(
PLAN94_BODY_NAME_TO_PLANET_INDEX.keys()
)
else:
return tuple(BODY_NAME_TO_KERNEL_SPEC.keys())
def _get_kernel(value):
"""
Try importing jplephem, download/retrieve from cache the Satellite Planet
Kernel corresponding to the given ephemeris.
"""
if value is None or value.lower() == "builtin":
return None
if not HAS_JPLEPHEM:
raise ModuleNotFoundError(
"Solar system JPL ephemeris calculations require the jplephem package "
"(https://pypi.org/project/jplephem/)"
)
from jplephem.spk import SPK
if value.lower() == "jpl":
# Get the default JPL ephemeris URL
value = DEFAULT_JPL_EPHEMERIS
if re.compile(r"de[0-9][0-9][0-9]s?").match(value.lower()):
value = (
"https://naif.jpl.nasa.gov/pub/naif/generic_kernels"
f"/spk/planets/{value.lower():s}.bsp"
)
elif os.path.isfile(value):
return SPK.open(value)
else:
try:
urlparse(value)
except Exception:
raise ValueError(
f"{value} was not one of the standard strings and "
"could not be parsed as a file path or URL"
)
return SPK.open(download_file(value, cache=True))
def _get_body_barycentric_posvel(body, time, ephemeris=None, get_velocity=True):
"""Calculate the barycentric position (and velocity) of a solar system body.
Parameters
----------
body : str or other
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL
kernel.
time : `~astropy.time.Time`
Time of observation.
ephemeris : str, optional
Ephemeris to use. By default, use the one set with
``astropy.coordinates.solar_system_ephemeris.set``
get_velocity : bool, optional
Whether or not to calculate the velocity as well as the position.
Returns
-------
position : `~astropy.coordinates.CartesianRepresentation` or tuple
Barycentric (ICRS) position or tuple of position and velocity.
Notes
-----
Whether or not velocities are calculated makes little difference for the
built-in ephemerides, but for most JPL ephemeris files, the execution time
roughly doubles.
"""
# If the ephemeris is to be taken from solar_system_ephemeris, or the one
# it already contains, use the kernel there. Otherwise, open the ephemeris,
# possibly downloading it, but make sure the file is closed at the end.
default_kernel = ephemeris is None or ephemeris is solar_system_ephemeris._value
kernel = None
try:
if default_kernel:
if solar_system_ephemeris.get() is None:
raise ValueError(cleandoc(_EPHEMERIS_NOTE))
kernel = solar_system_ephemeris.kernel
else:
kernel = _get_kernel(ephemeris)
jd1, jd2 = get_jd12(time, "tdb")
if kernel is None:
body = body.lower()
earth_pv_helio, earth_pv_bary = erfa.epv00(jd1, jd2)
if body == "earth":
body_pv_bary = earth_pv_bary
elif body == "moon":
# The moon98 documentation notes that it takes TT, but that TDB leads
# to errors smaller than the uncertainties in the algorithm.
# moon98 returns the astrometric position relative to the Earth.
moon_pv_geo = erfa.moon98(jd1, jd2)
body_pv_bary = erfa.pvppv(moon_pv_geo, earth_pv_bary)
else:
sun_pv_bary = erfa.pvmpv(earth_pv_bary, earth_pv_helio)
if body == "sun":
body_pv_bary = sun_pv_bary
else:
try:
body_index = PLAN94_BODY_NAME_TO_PLANET_INDEX[body]
except KeyError:
raise KeyError(
f"{body}'s position and velocity cannot be "
f"calculated with the '{ephemeris}' ephemeris."
)
body_pv_helio = erfa.plan94(jd1, jd2, body_index)
body_pv_bary = erfa.pvppv(body_pv_helio, sun_pv_bary)
body_pos_bary = CartesianRepresentation(
body_pv_bary["p"], unit=u.au, xyz_axis=-1, copy=COPY_IF_NEEDED
)
if get_velocity:
body_vel_bary = CartesianRepresentation(
body_pv_bary["v"],
unit=u.au / u.day,
xyz_axis=-1,
copy=COPY_IF_NEEDED,
)
else:
if isinstance(body, str):
# Look up kernel chain for JPL ephemeris, based on name
try:
kernel_spec = BODY_NAME_TO_KERNEL_SPEC[body.lower()]
except KeyError:
raise KeyError(
f"{body}'s position cannot be calculated with "
f"the {ephemeris} ephemeris."
)
else:
# otherwise, assume the user knows what their doing and intentionally
# passed in a kernel chain
kernel_spec = body
# jplephem cannot handle multi-D arrays, so convert to 1D here.
jd1_shape = getattr(jd1, "shape", ())
if len(jd1_shape) > 1:
jd1, jd2 = jd1.ravel(), jd2.ravel()
# Note that we use the new jd1.shape here to create a 1D result array.
# It is reshaped below.
body_posvel_bary = np.zeros(
(2 if get_velocity else 1, 3) + getattr(jd1, "shape", ())
)
for pair in kernel_spec:
spk = kernel[pair]
if spk.data_type == 3:
# Type 3 kernels contain both position and velocity.
posvel = spk.compute(jd1, jd2)
if get_velocity:
body_posvel_bary += posvel.reshape(body_posvel_bary.shape)
else:
body_posvel_bary[0] += posvel[:3]
else:
# spk.generate first yields the position and then the
# derivative. If no velocities are desired, body_posvel_bary
# has only one element and thus the loop ends after a single
# iteration, avoiding the velocity calculation.
for body_p_or_v, p_or_v in zip(
body_posvel_bary, spk.generate(jd1, jd2)
):
body_p_or_v += p_or_v
body_posvel_bary.shape = body_posvel_bary.shape[:2] + jd1_shape
body_pos_bary = CartesianRepresentation(
body_posvel_bary[0], unit=u.km, copy=False
)
if get_velocity:
body_vel_bary = CartesianRepresentation(
body_posvel_bary[1], unit=u.km / u.day, copy=False
)
return (body_pos_bary, body_vel_bary) if get_velocity else body_pos_bary
finally:
if not default_kernel and kernel is not None:
kernel.daf.file.close()
def get_body_barycentric_posvel(body, time, ephemeris=None):
"""Calculate the barycentric position and velocity of a solar system body.
Parameters
----------
body : str or list of tuple
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL
kernel.
time : `~astropy.time.Time`
Time of observation.
ephemeris : str, optional
Ephemeris to use. By default, use the one set with
``astropy.coordinates.solar_system_ephemeris.set``
Returns
-------
position, velocity : tuple of `~astropy.coordinates.CartesianRepresentation`
Tuple of barycentric (ICRS) position and velocity.
See Also
--------
get_body_barycentric : to calculate position only.
This is faster by about a factor two for JPL kernels, but has no
speed advantage for the built-in ephemeris.
Notes
-----
{_EPHEMERIS_NOTE}
"""
return _get_body_barycentric_posvel(body, time, ephemeris)
def get_body_barycentric(body, time, ephemeris=None):
"""Calculate the barycentric position of a solar system body.
Parameters
----------
body : str or list of tuple
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL
kernel.
time : `~astropy.time.Time`
Time of observation.
ephemeris : str, optional
Ephemeris to use. By default, use the one set with
``astropy.coordinates.solar_system_ephemeris.set``
Returns
-------
position : `~astropy.coordinates.CartesianRepresentation`
Barycentric (ICRS) position of the body in cartesian coordinates
See Also
--------
get_body_barycentric_posvel : to calculate both position and velocity.
Notes
-----
{_EPHEMERIS_NOTE}
"""
return _get_body_barycentric_posvel(body, time, ephemeris, get_velocity=False)
def _get_apparent_body_position(body, time, ephemeris, obsgeoloc=None):
"""Calculate the apparent position of body ``body`` relative to Earth.
This corrects for the light-travel time to the object.
Parameters
----------
body : str or other
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL
kernel.
time : `~astropy.time.Time`
Time of observation.
ephemeris : str, optional
Ephemeris to use. By default, use the one set with
``~astropy.coordinates.solar_system_ephemeris.set``
obsgeoloc : `~astropy.coordinates.CartesianRepresentation`, optional
The GCRS position of the observer
Returns
-------
cartesian_position : `~astropy.coordinates.CartesianRepresentation`
Barycentric (ICRS) apparent position of the body in cartesian coordinates
Notes
-----
{_EPHEMERIS_NOTE}
"""
if ephemeris is None:
ephemeris = solar_system_ephemeris.get()
# Calculate position given approximate light travel time.
delta_light_travel_time = 20.0 * u.s
emitted_time = time
light_travel_time = 0.0 * u.s
earth_loc = get_body_barycentric("earth", time, ephemeris)
if obsgeoloc is not None:
earth_loc += obsgeoloc
while np.any(np.fabs(delta_light_travel_time) > 1.0e-8 * u.s):
body_loc = get_body_barycentric(body, emitted_time, ephemeris)
earth_distance = (body_loc - earth_loc).norm()
delta_light_travel_time = light_travel_time - earth_distance / speed_of_light
light_travel_time = earth_distance / speed_of_light
emitted_time = time - light_travel_time
return get_body_barycentric(body, emitted_time, ephemeris)
def get_body(body, time, location=None, ephemeris=None):
"""
Get a `~astropy.coordinates.SkyCoord` for a solar system body as observed
from a location on Earth in the `~astropy.coordinates.GCRS` reference
system.
Parameters
----------
body : str or list of tuple
The solar system body for which to calculate positions. Can also be a
kernel specifier (list of 2-tuples) if the ``ephemeris`` is a JPL
kernel.
time : `~astropy.time.Time`
Time of observation.
location : `~astropy.coordinates.EarthLocation`, optional
Location of observer on the Earth. If not given, will be taken from
``time`` (if not present, a geocentric observer will be assumed).
ephemeris : str, optional
Ephemeris to use. If not given, use the one set with
``astropy.coordinates.solar_system_ephemeris.set`` (which is
set to 'builtin' by default).
Returns
-------
skycoord : `~astropy.coordinates.SkyCoord`
GCRS Coordinate for the body
Notes
-----
The coordinate returned is the apparent position, which is the position of
the body at time *t* minus the light travel time from the *body* to the
observing *location*.
{_EPHEMERIS_NOTE}
"""
if location is None:
location = time.location
if location is not None:
obsgeoloc, obsgeovel = location.get_gcrs_posvel(time)
else:
obsgeoloc, obsgeovel = None, None
cartrep = _get_apparent_body_position(body, time, ephemeris, obsgeoloc)
icrs = ICRS(cartrep)
gcrs = icrs.transform_to(
GCRS(obstime=time, obsgeoloc=obsgeoloc, obsgeovel=obsgeovel)
)
return SkyCoord(gcrs)
# Add note about the ephemeris choices to the docstrings of relevant functions.
# Note: sadly, one cannot use f-strings for docstrings, so we format explicitly.
for f in [
f
for f in locals().values()
if callable(f) and f.__doc__ is not None and "{_EPHEMERIS_NOTE}" in f.__doc__
]:
f.__doc__ = f.__doc__.format(_EPHEMERIS_NOTE=_EPHEMERIS_NOTE)
| solar_system_ephemeris |
python | tensorflow__tensorflow | tensorflow/python/framework/combinations.py | {
"start": 1844,
"end": 2998
} | class ____(test_combinations.TestCombination):
"""Control the execution of the test in TF1.x and TF2.
If TF2 is enabled then a test with TF1 test is going to be skipped and vice
versa.
Test targets continuously run in TF2 thanks to the tensorflow.v2 TAP target.
A test can be run in TF2 with bazel by passing --test_env=TF2_BEHAVIOR=1.
"""
def should_execute_combination(self, kwargs):
tf_api_version = kwargs.pop("tf_api_version", None)
if tf_api_version == 1 and tf2.enabled():
return (False, "Skipping a TF1.x test when TF2 is enabled.")
elif tf_api_version == 2 and not tf2.enabled():
return (False, "Skipping a TF2 test when TF2 is not enabled.")
return (True, None)
def parameter_modifiers(self):
return [test_combinations.OptionalParameter("tf_api_version")]
generate = functools.partial(
test_combinations.generate,
test_combinations=(EagerGraphCombination(), TFVersionCombination()))
combine = test_combinations.combine
times = test_combinations.times
NamedObject = test_combinations.NamedObject
tf_export("__internal__.test.combinations.generate", v1=[])(generate)
| TFVersionCombination |
python | astropy__astropy | astropy/visualization/tests/test_interval.py | {
"start": 3919,
"end": 6086
} | class ____(TestInterval):
# Make sure intervals work with MaskedArray
data = np.concatenate((np.linspace(-20.0, 60.0, 100), np.full(100, 1e6)))
data = Masked(data, data > 1000)
def test_zscale():
np.random.seed(42)
data = np.random.randn(100, 100) * 5 + 10
interval = ZScaleInterval()
vmin, vmax = interval.get_limits(data)
assert_allclose(vmin, -9.6, atol=0.1)
assert_allclose(vmax, 25.4, atol=0.1)
data = list(range(1000)) + [np.nan]
interval = ZScaleInterval()
vmin, vmax = interval.get_limits(data)
assert_allclose(vmin, 0, atol=0.1)
assert_allclose(vmax, 999, atol=0.1)
data = list(range(100))
interval = ZScaleInterval()
vmin, vmax = interval.get_limits(data)
assert_allclose(vmin, 0, atol=0.1)
assert_allclose(vmax, 99, atol=0.1)
def test_zscale_npoints():
"""
Regression test to ensure ZScaleInterval returns the minimum and
maximum of the data if the number of data points is less than
``min_pixels``.
"""
data = np.arange(4).reshape((2, 2))
interval = ZScaleInterval(min_npixels=5)
vmin, vmax = interval.get_limits(data)
assert vmin == 0
assert vmax == 3
def test_integers():
# Need to make sure integers get cast to float
interval = MinMaxInterval()
values = interval([1, 3, 4, 5, 6])
assert_allclose(values, [0.0, 0.4, 0.6, 0.8, 1.0])
# Don't accept integer array in output
out = np.zeros(5, dtype=int)
with pytest.raises(
TypeError, match=r"Can only do in-place scaling for floating-point arrays"
):
values = interval([1, 3, 4, 5, 6], out=out)
# But integer input and floating point output is fine
out = np.zeros(5, dtype=float)
interval([1, 3, 4, 5, 6], out=out)
assert_allclose(out, [0.0, 0.4, 0.6, 0.8, 1.0])
def test_constant_data():
"""Test intervals with constant data (avoiding divide-by-zero)."""
shape = (10, 10)
data = np.ones(shape)
interval = MinMaxInterval()
limits = interval.get_limits(data)
values = interval(data)
assert_allclose(limits, (1.0, 1.0))
assert_allclose(values, np.zeros(shape))
| TestIntervalMaskedNDArray |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 284560,
"end": 285176
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("DiscussionEdge"), graphql_name="edges"
)
nodes = sgqlc.types.Field(sgqlc.types.list_of("Discussion"), graphql_name="nodes")
page_info = sgqlc.types.Field(
sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo"
)
total_count = sgqlc.types.Field(
sgqlc.types.non_null(Int), graphql_name="totalCount"
)
| DiscussionConnection |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 374292,
"end": 377446
} | class ____(Request):
"""
Request to stop a running task
:param force: If not true, call fails if the task status is not 'in_progress'
:type force: bool
:param task: Task ID
:type task: str
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"
_action = "stop"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"force": {
"default": False,
"description": "If not true, call fails if the task status is not 'in_progress'",
"type": ["boolean", "null"],
},
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task"],
"type": "object",
}
def __init__(
self,
task: str,
force: Optional[bool] = False,
status_reason: Optional[str] = None,
status_message: Optional[str] = None,
**kwargs: Any
) -> None:
super(StopRequest, self).__init__(**kwargs)
self.force = force
self.task = task
self.status_reason = status_reason
self.status_message = status_message
@schema_property("force")
def force(self) -> Optional[bool]:
return self._property_force
@force.setter
def force(self, value: Optional[bool]) -> None:
if value is None:
self._property_force = None
return
self.assert_isinstance(value, "force", (bool,))
self._property_force = value
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
| StopRequest |
python | doocs__leetcode | solution/2800-2899/2897.Apply Operations on Array to Maximize Sum of Squares/Solution.py | {
"start": 0,
"end": 476
} | class ____:
def maxSum(self, nums: List[int], k: int) -> int:
mod = 10**9 + 7
cnt = [0] * 31
for x in nums:
for i in range(31):
if x >> i & 1:
cnt[i] += 1
ans = 0
for _ in range(k):
x = 0
for i in range(31):
if cnt[i]:
x |= 1 << i
cnt[i] -= 1
ans = (ans + x * x) % mod
return ans
| Solution |
python | huggingface__transformers | tests/utils/test_model_output.py | {
"start": 879,
"end": 984
} | class ____(ModelOutput):
a: float
b: float | None = None
c: float | None = None
| ModelOutputTest |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/service/local_workers_test.py | {
"start": 10891,
"end": 17952
} | class ____(data_service_test_base.TestBase,
parameterized.TestCase):
"""Tests garbage collecting unused local worker tasks.
The user typically creates an iterator in each epoch. This should delete the
previous iterator and releases the resources of it.
"""
@combinations.generate(
combinations.times(test_base.default_test_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testMultipleEpochs(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_epochs, num_steps = 5, 5
dataset = self._make_distributed_infinite_range_dataset(cluster)
for _ in range(num_epochs):
# For each iteration, the previous iterator is garbage collected.
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testMultipleEpochsSharedJob(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_epochs, num_steps = 5, 5
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
for _ in range(num_epochs):
# For each iteration, the previous iterator is garbage collected.
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
num_remote_workers=[0, 3], job_name=[None, "shared_job_name"])))
def testRepeatDistributedDataset(self, num_remote_workers, job_name):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
dataset = self.make_distributed_range_dataset(
10, cluster, job_name=job_name, target_workers="LOCAL")
dataset = dataset.repeat(3)
self.assertDatasetProduces(dataset, list(range(10)) * 3)
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testReadFromDeletedTask(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_steps = 10
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
# Re-creating the dataset resets the iterator index, so the second iterator
# reads from the same task as the first, which has been deleted.
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
with self.assertRaisesRegex(errors.FailedPreconditionError,
"which has been deleted."):
get_next = self.getNext(dataset)
while True:
_ = self.evaluate(get_next())
@combinations.generate(
combinations.times(test_base.graph_only_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testReadFromDeletedTask_GraphMode(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_steps = 10
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
with self.session() as sess:
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(sess.run(get_next()), i)
# Re-creating the dataset resets the iterator index, so the second iterator
# reads from the same task as the first, which has been deleted.
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
with self.assertRaisesRegex(errors.FailedPreconditionError,
"which has been deleted."):
with self.session() as sess:
get_next = self.getNext(dataset)
sess.run(get_next())
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testMultipleEpochs_WorkerRestart(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_steps = 10
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
# Verifies the worker re-creates the task after the iterator is deleted and
# the worker restarts.
del get_next
cluster.restart_local_workers()
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
@combinations.generate(
combinations.times(test_base.eager_only_combinations(),
combinations.combine(num_remote_workers=[0, 3])))
def testMultipleEpochs_DispatcherRestart(self, num_remote_workers):
num_local_workers = 1
cluster = multi_process_cluster.MultiProcessCluster(
num_local_workers=num_local_workers,
num_remote_workers=num_remote_workers)
num_steps = 10
dataset = self._make_distributed_infinite_range_dataset(
cluster, job_name="shared_job_name")
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
# Verifies the worker re-creates the task after the iterator is deleted and
# the dispatcher restarts.
del get_next
cluster.restart_dispatcher()
get_next = self.getNext(dataset)
for i in range(num_steps):
self.assertEqual(self.evaluate(get_next()), i)
def _make_distributed_infinite_range_dataset(self, cluster, job_name=None):
dataset = dataset_ops.Dataset.range(1000000).repeat()
return self.make_distributed_dataset(
dataset,
cluster=cluster,
job_name=job_name,
processing_mode=data_service_ops.ShardingPolicy.OFF,
target_workers="LOCAL")
if __name__ == "__main__":
multi_process_cluster.test_main()
| LocalTaskGarbageCollectTest |
python | django__django | tests/gis_tests/test_ptr.py | {
"start": 130,
"end": 2398
} | class ____(SimpleTestCase):
def test(self):
destructor_mock = mock.Mock()
class NullPointerException(Exception):
pass
class FakeGeom1(CPointerBase):
null_ptr_exception_class = NullPointerException
class FakeGeom2(FakeGeom1):
ptr_type = ctypes.POINTER(ctypes.c_float)
destructor = destructor_mock
fg1 = FakeGeom1()
fg2 = FakeGeom2()
# These assignments are OK. None is allowed because it's equivalent
# to the NULL pointer.
fg1.ptr = fg1.ptr_type()
fg1.ptr = None
fg2.ptr = fg2.ptr_type(ctypes.c_float(5.23))
fg2.ptr = None
# Because pointers have been set to NULL, an exception is raised on
# access. Raising an exception is preferable to a segmentation fault
# that commonly occurs when a C method is given a NULL reference.
for fg in (fg1, fg2):
with self.assertRaises(NullPointerException):
fg.ptr
# Anything that's either not None or the acceptable pointer type
# results in a TypeError when trying to assign it to the `ptr`
# property. Thus, memory addresses (integers) and pointers of the
# incorrect type (in `bad_ptrs`) aren't allowed.
bad_ptrs = (5, ctypes.c_char_p(b"foobar"))
for bad_ptr in bad_ptrs:
for fg in (fg1, fg2):
with self.assertRaisesMessage(TypeError, "Incompatible pointer type"):
fg.ptr = bad_ptr
# Object can be deleted without a destructor set.
fg = FakeGeom1()
fg.ptr = fg.ptr_type(1)
del fg
# A NULL pointer isn't passed to the destructor.
fg = FakeGeom2()
fg.ptr = None
del fg
self.assertFalse(destructor_mock.called)
# The destructor is called if set.
fg = FakeGeom2()
ptr = fg.ptr_type(ctypes.c_float(1.0))
fg.ptr = ptr
del fg
destructor_mock.assert_called_with(ptr)
def test_destructor_catches_importerror(self):
class FakeGeom(CPointerBase):
destructor = mock.Mock(side_effect=ImportError)
fg = FakeGeom()
fg.ptr = fg.ptr_type(1)
del fg
| CPointerBaseTests |
python | pytorch__pytorch | torch/sparse/semi_structured.py | {
"start": 910,
"end": 16031
} | class ____(torch.Tensor):
"""
This class implements semi-structured sparsity as a Tensor subclass.
Semi-structured sparsity describes a sparsity pattern where n in every 2n elements are sparse,
depending on the datatype. It is also referred to as 2:4 sparsity or fine-grained
structured sparsity.
There are two backends available for semi_structred sparsity, either cuSPARSELt or CUTLASS.
This class is meant to serve as a base class for both implementations. SparseSemiStructuredCUTLASS
and SparseSemiStructuredCUSPARSELT both inherit from this class and define three backend-specific items.
Note that as such, this class cannot be instantiated directly.
-`_DTYPE_SHAPE_CONSTRAINTS` - A dictionary holding backend specific dense/sparse min shape constraints
- `def from_dense()` - backend specific compression routines
- `def _mm()` - backend specific mm op (either torch._cslt_sparse_mm or torch._sparse_semi_structured_(mm|addmm))
"""
_DEFAULT_ALG_ID: int = 0
_DTYPE_SHAPE_CONSTRAINTS: dict[torch.dtype, _SEMI_STRUCTURED_SPARSE_CONFIG]
_FORCE_CUTLASS: bool = False
_FUSE_TRANSPOSE: bool = False
_PROTOTYPE_WARNING_SHOWN: bool = False
BACKEND: str
SPARSE_DISPATCH: dict[Callable, Callable]
packed: torch.Tensor | None
meta: torch.Tensor | None
packed_t: torch.Tensor | None
meta_t: torch.Tensor | None
compressed_swizzled_bitmask: torch.Tensor | None
fuse_transpose_cusparselt: bool
alg_id_cusparselt: int
__slots__ = ["packed", "meta", "packed_t", "meta_t", "compressed_swizzled_bitmask"]
@staticmethod
def __new__( # noqa: PYI034
cls,
shape: torch.Size,
packed: torch.Tensor | None,
meta: torch.Tensor | None,
packed_t: torch.Tensor | None,
meta_t: torch.Tensor | None,
compressed_swizzled_bitmask: torch.Tensor | None,
fuse_transpose_cusparselt: bool = False,
alg_id_cusparselt: int = 0,
requires_grad: bool = False,
):
"""
Create a new instance of the tensor subclass from the compressed sparse representation.
We have the option to create the subclass with the compressed representations of both X and X', for training.
For inference, we only need a single representation (either X or X'), while the corresponding other set will be None.
Depending on the backend selected, certain fields will be set to None. (CUSPARSELT vs CUTLASS)
Args:
shape: The shape of the original dense tensor
packed: The compressed representation of the original dense tensor
meta: The metadata of the original dense tensor, if it is stored separately
packed_t: The compressed representation of the transposed original dense tensor
meta_t: The metadata of the transposed original dense tensor, if it is stored separately
compressed_swizzled_bitmask: The masks used by the CUTLASS backend to determine which threads should
participate in the computation. Used for pointwise ops.
fuse_transpose_cusparselt: When running with cuSPARSELt, we have the option to fuse a transposition
with a matmul, which is useful in the case of 2:4 sparse training.
alg_id_cusparselt: The algorithm id to use when using cuSPARSELT, will have effect on performance
Returns:
torch.Tensor: A torch.Tensor wrapper subclass.
Raises:
ValueError: If all of the tensor arguments are None.
"""
if not cls._PROTOTYPE_WARNING_SHOWN:
warnings.warn(
(
"The PyTorch API of SparseSemiStructuredTensor is in prototype stage "
"and will change in the near future. Please open a Github issue "
"for features requests and see our documentation on the torch.sparse "
"module for further information about the project."
),
UserWarning,
stacklevel=2,
)
cls._PROTOTYPE_WARNING_SHOWN = True
# Because this only runs once, we also load the dispatch table here as well.
# We can't define the dispatch table explicitly because of torch.ops import errors, so we do this instead
# But this is useful since it allows users to overload the dispatch table for debugging / testing.
cls._load_dispatch_table()
# we can also register the classes with dynamo when the warning is shown.
torch._dynamo.allow_in_graph(cls)
if packed is not None:
previous_tensor = packed
elif packed_t is not None:
previous_tensor = packed_t
else:
raise ValueError("At least one of packed or packed_t must be provided")
tensor = torch.Tensor._make_wrapper_subclass(
cls,
shape,
device=previous_tensor.device,
dtype=previous_tensor.dtype,
layout=previous_tensor.layout,
requires_grad=requires_grad,
)
tensor.packed = packed
tensor.meta = meta
tensor.packed_t = packed_t
tensor.meta_t = meta_t
tensor.compressed_swizzled_bitmask = compressed_swizzled_bitmask
tensor.fuse_transpose_cusparselt = fuse_transpose_cusparselt
tensor.alg_id_cusparselt = alg_id_cusparselt
return tensor
def __repr__(self) -> str: # type: ignore[override]
assert hasattr(self, "shape")
return f"{self.__class__.__name__}(shape={self.shape})"
def __tensor_flatten__(
self,
) -> tuple[list[str], tuple[torch.Size, bool, int, bool]]:
inner_tensors = list(
filter(lambda x: getattr(self, x) is not None, self.__slots__)
)
tensor_meta = (
self.shape,
self.fuse_transpose_cusparselt,
self.alg_id_cusparselt,
self.requires_grad,
)
return inner_tensors, tensor_meta
@classmethod
def __tensor_unflatten__(
cls,
inner_tensors,
tensor_meta: tuple[torch.Size, bool, int, bool],
outer_size,
outer_stride,
) -> torch.Tensor:
shape, fuse_transpose_cusparselt, alg_id_cusparselt, requires_grad = tensor_meta
# pyrefly: ignore [no-matching-overload]
return cls(
shape=shape,
packed=inner_tensors.get("packed", None),
meta=inner_tensors.get("meta", None),
packed_t=inner_tensors.get("packed_t", None),
meta_t=inner_tensors.get("meta_t", None),
compressed_swizzled_bitmask=inner_tensors.get(
"compressed_swizzled_bitmask", None
),
fuse_transpose_cusparselt=fuse_transpose_cusparselt,
alg_id_cusparselt=alg_id_cusparselt,
requires_grad=requires_grad,
)
__torch_function__ = torch._C._disabled_torch_function_impl # type: ignore[assignment]
@classmethod
def __torch_dispatch__(cls, func, types, args, kwargs) -> Any: # type: ignore[override]
if func._overloadpacket not in cls.SPARSE_DISPATCH:
raise NotImplementedError(
f"{cls.__name__} only supports a specific set of operations, "
f"can't perform requested op ({func.__name__})"
)
return cls.SPARSE_DISPATCH[func._overloadpacket](func, types, args, kwargs)
@classmethod
def _load_dispatch_table(cls, custom_dispatch_table=None) -> None:
"""
Loads the op overload sparse dispatch table for the current class.
"""
if getattr(cls, "SPARSE_DISPATCH", None) is None:
cls.SPARSE_DISPATCH = {
torch.ops.aten.values: semi_sparse_values,
torch.ops.aten.indices: semi_sparse_indices,
torch.ops.aten.is_same_size: fallback_dispatcher,
torch.ops.aten.detach_: fallback_dispatcher,
torch.ops.aten.detach: semi_sparse_detach,
torch.ops.aten.t: semi_sparse_t,
torch.ops.aten.view: semi_sparse_view,
torch.ops.aten.mm: semi_sparse_mm,
torch.ops.aten.matmul: semi_sparse_mm,
torch.ops.aten.addmm: semi_sparse_addmm,
torch.ops.aten.linear: semi_sparse_linear,
torch.ops.aten._to_copy: fallback_dispatcher,
torch.ops.aten._scaled_mm: semi_sparse_scaled_mm,
}
if custom_dispatch_table is not None:
cls.SPARSE_DISPATCH.update(custom_dispatch_table)
@classmethod
def _validate_device_dim_dtype_shape(cls, original_tensor: torch.Tensor) -> None:
"""
Assert that the given tensor is valid for semi-structured sparse compression.
"""
# check device
if not original_tensor.is_cuda:
raise RuntimeError(
f"Error original_tensor.device= {original_tensor.device} is not supported! "
"Only CUDA tensors are currently supported."
)
# check dim
if original_tensor.dim() != 2:
raise RuntimeError(
f"Error original_tensor.dim = {original_tensor.dim()} is not supported! "
"Only 2d tensors are currently supported."
)
# check contiguous
if not original_tensor.is_contiguous():
raise RuntimeError(
"Error original_tensor is not contiguous!"
"Only contiguous tensors are currently supported."
)
# check dtype
if original_tensor.dtype not in cls._DTYPE_SHAPE_CONSTRAINTS:
raise RuntimeError(
f"Error original_tensor.dtype {original_tensor.dtype} is not a supported dtype for {cls}!"
)
# check shape
m, n = original_tensor.shape
min_rows = cls._DTYPE_SHAPE_CONSTRAINTS[original_tensor.dtype].sparse_min_rows
min_cols = cls._DTYPE_SHAPE_CONSTRAINTS[original_tensor.dtype].sparse_min_cols
if m < min_rows or m % min_rows or n < min_cols or n % min_cols:
# TODO in the future we can add in padding to support sparse dimensions that aren't perfect multiples
raise RuntimeError(
f"Error original_tensor.shape {original_tensor.shape} is not supported! "
f"Both dimensions must be larger or equal than and a multiple of ({min_rows}, {min_cols})"
)
@classmethod
def _pad_dense_input(cls, dense_input: torch.Tensor) -> torch.Tensor:
"""
Calculates padding for dense tensor and pads tensor if necessary.
If padding is not required, this function returns the original tensor.
"""
# only 2d matmul
assert dense_input.dim() == 2
# check shape
m, n = dense_input.shape
min_rows = cls._DTYPE_SHAPE_CONSTRAINTS[dense_input.dtype].dense_min_rows
min_cols = cls._DTYPE_SHAPE_CONSTRAINTS[dense_input.dtype].dense_min_cols
# calculate padding
to_pad_m = -m % min_rows if m < min_rows or m % min_rows else 0
to_pad_n = -n % min_cols if n < min_cols or n % min_rows else 0
if to_pad_m or to_pad_n:
return torch.nn.functional.pad(dense_input, (0, to_pad_n, 0, to_pad_m))
else:
return dense_input
def to_dense(self): # type:ignore[override]
col = self.shape[-1]
return torch.mm(self, torch.eye(col, dtype=self.dtype, device=self.device))
@classmethod
def from_dense(cls, original_tensor: torch.Tensor) -> "SparseSemiStructuredTensor":
raise NotImplementedError
def _mm(
self,
B: torch.Tensor,
*,
bias: torch.Tensor | None = None,
**kwargs,
) -> torch.Tensor:
raise NotImplementedError
def to_sparse_semi_structured(
original_tensor: torch.Tensor,
transposed: bool = False,
) -> SparseSemiStructuredTensor:
"""
This function converts a dense tensor into a sparse semi-structured tensor.
It will return a SparseSemiStructuredTensor, a subclass of torch.Tensor.
This function will check to ensure the dense tensor has the right dtype, size, dims, and device.
We currently only support semi-structured sparse tensors for 2d CUDA tensors.
Additionally, your tensor must be a positive multiple of the minimum sparse block size, given in
`_DTYPE_TO_SHAPE_CONSTRAINTS` for each dtype (float32, float16, bfloat16, int8).
Args:
original_tensor (Tensor): the dense tensor to convert
transposed (bool, optional): deprecated arg to be removed in another release. Do not use.
Returns:
SparseSemiStructuredTensor: A sparse semi-structured tensor created from the given original_tensor
Raises:
None
Example:
>>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
>>> A = torch.Tensor([0, 0, 1, 1]).tile((128, 32)).half().cuda()
tensor([[0., 0., 1., ..., 0., 1., 1.],
[0., 0., 1., ..., 0., 1., 1.],
[0., 0., 1., ..., 0., 1., 1.],
...,
[0., 0., 1., ..., 0., 1., 1.],
[0., 0., 1., ..., 0., 1., 1.],
[0., 0., 1., ..., 0., 1., 1.]], device='cuda:0', dtype=torch.float16)
>>> A_sparse = to_sparse_semi_structured(A)
SparseSemiStructuredTensor(shape=torch.Size([128, 128]))
>>> A_sparse.values()
tensor([[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
...,
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.]], device='cuda:0', dtype=torch.float16),
>>> A_sparse.indices()
tensor([[-4370, -4370, -4370, ..., -4370, -4370, -4370],
[-4370, -4370, -4370, ..., -4370, -4370, -4370],
[-4370, -4370, -4370, ..., -4370, -4370, -4370],
...,
[-4370, -4370, -4370, ..., -4370, -4370, -4370],
[-4370, -4370, -4370, ..., -4370, -4370, -4370],
[-4370, -4370, -4370, ..., -4370, -4370, -4370]], device='cuda:0', dtype=torch.int16))
"""
if transposed:
warnings.warn(
"Setting transpose from `to_sparse_semi_structured` is deprecated "
"and will be removed in a future release. "
"`SparseSemiStructuredTensor` only support contiguous input tensors.",
FutureWarning,
stacklevel=2,
)
# set from _FORCE_CUTLASS flag
SPARSE_SUBCLASS = (
torch.sparse.SparseSemiStructuredTensorCUTLASS
if SparseSemiStructuredTensor._FORCE_CUTLASS
else torch.sparse.SparseSemiStructuredTensorCUSPARSELT
)
return SPARSE_SUBCLASS.from_dense(original_tensor)
| SparseSemiStructuredTensor |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 66502,
"end": 70491
} | class ____(fixtures.MappedTest):
"""test the construction of mapper.primary_key when an inheriting
relationship joins on a column other than primary key column."""
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
global person_table, employee_table, Person, Employee
person_table = Table(
"persons",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(80)),
)
employee_table = Table(
"employees",
metadata,
Column(
"eid", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("salary", Integer),
Column("person_id", Integer, ForeignKey("persons.id")),
)
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
pass
@classmethod
def insert_data(cls, connection):
person_insert = person_table.insert()
connection.execute(person_insert, dict(id=1, name="alice"))
connection.execute(person_insert, dict(id=2, name="bob"))
employee_insert = employee_table.insert()
connection.execute(
employee_insert, dict(id=2, salary=250, person_id=1)
) # alice
connection.execute(
employee_insert, dict(id=3, salary=200, person_id=2)
) # bob
def test_implicit(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee, employee_table, inherits=person_mapper
)
assert list(class_mapper(Employee).primary_key) == [person_table.c.id]
def test_explicit_props(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
properties={"pid": person_table.c.id, "eid": employee_table.c.eid},
)
self._do_test(False)
def test_explicit_composite_pk(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
properties=dict(id=[employee_table.c.eid, person_table.c.id]),
primary_key=[person_table.c.id, employee_table.c.eid],
)
assert_warns_message(
sa_exc.SAWarning,
r"On mapper Mapper\[Employee\(employees\)\], "
"primary key column 'persons.id' is being "
"combined with distinct primary key column 'employees.eid' "
"in attribute 'id'. Use explicit properties to give "
"each column its own mapped attribute name.",
self._do_test,
True,
)
def test_explicit_pk(self):
person_mapper = self.mapper_registry.map_imperatively(
Person, person_table
)
self.mapper_registry.map_imperatively(
Employee,
employee_table,
inherits=person_mapper,
primary_key=[person_table.c.id],
)
self._do_test(False)
def _do_test(self, composite):
session = fixture_session()
if composite:
alice1 = session.get(Employee, [1, 2])
bob = session.get(Employee, [2, 3])
alice2 = session.get(Employee, [1, 2])
else:
alice1 = session.get(Employee, 1)
bob = session.get(Employee, 2)
alice2 = session.get(Employee, 1)
assert alice1.name == alice2.name == "alice"
assert bob.name == "bob"
| DistinctPKTest |
python | django__django | tests/gis_tests/geoadmin/tests.py | {
"start": 2454,
"end": 3280
} | class ____(GeoAdminTest):
admin_site = site_gis # GISModelAdmin
def test_default_gis_widget_kwargs(self):
geoadmin = self.admin_site.get_model_admin(City)
form = geoadmin.get_changelist_form(None)()
widget = form["point"].field.widget
self.assertEqual(widget.attrs["default_lat"], 47)
self.assertEqual(widget.attrs["default_lon"], 5)
self.assertEqual(widget.attrs["default_zoom"], 12)
def test_custom_gis_widget_kwargs(self):
geoadmin = site_gis_custom.get_model_admin(City)
form = geoadmin.get_changelist_form(None)()
widget = form["point"].field.widget
self.assertEqual(widget.attrs["default_lat"], 55)
self.assertEqual(widget.attrs["default_lon"], 37)
self.assertEqual(widget.attrs["default_zoom"], 12)
| GISAdminTests |
python | doocs__leetcode | solution/2100-2199/2101.Detonate the Maximum Bombs/Solution.py | {
"start": 0,
"end": 817
} | class ____:
def maximumDetonation(self, bombs: List[List[int]]) -> int:
n = len(bombs)
g = [[] for _ in range(n)]
for i in range(n - 1):
x1, y1, r1 = bombs[i]
for j in range(i + 1, n):
x2, y2, r2 = bombs[j]
dist = hypot(x1 - x2, y1 - y2)
if dist <= r1:
g[i].append(j)
if dist <= r2:
g[j].append(i)
ans = 0
for k in range(n):
vis = {k}
q = [k]
for i in q:
for j in g[i]:
if j not in vis:
vis.add(j)
q.append(j)
if len(vis) == n:
return n
ans = max(ans, len(vis))
return ans
| Solution |
python | apache__airflow | providers/standard/tests/unit/standard/operators/test_python.py | {
"start": 87338,
"end": 96025
} | class ____:
@pytest.mark.parametrize(
("ignore_downstream_trigger_rules", "with_teardown", "should_skip", "expected"),
[
(False, True, True, ["op2"]),
(False, True, False, []),
(False, False, True, ["op2"]),
(False, False, False, []),
(True, True, True, ["op2", "op3"]),
(True, True, False, []),
(True, False, True, ["op2", "op3", "op4"]),
(True, False, False, []),
],
)
def test_short_circuit_with_teardowns(
self, dag_maker, ignore_downstream_trigger_rules, should_skip, with_teardown, expected
):
with dag_maker(serialized=True):
op1 = ShortCircuitOperator(
task_id="op1",
python_callable=lambda: not should_skip,
ignore_downstream_trigger_rules=ignore_downstream_trigger_rules,
)
op2 = PythonOperator(task_id="op2", python_callable=print)
op3 = PythonOperator(task_id="op3", python_callable=print)
op4 = PythonOperator(task_id="op4", python_callable=print)
if with_teardown:
op4.as_teardown()
op1 >> op2 >> op3 >> op4
op1.skip = MagicMock()
dagrun = dag_maker.create_dagrun()
tis = dagrun.get_task_instances()
ti: TaskInstance = next(x for x in tis if x.task_id == "op1")
ti._run_raw_task()
if should_skip:
# we can't use assert_called_with because it's a set and therefore not ordered
actual_skipped = set(x.task_id for x in op1.skip.call_args.kwargs["tasks"])
assert actual_skipped == set(expected)
else:
op1.skip.assert_not_called()
@pytest.mark.parametrize("config", ["sequence", "parallel"])
def test_short_circuit_with_teardowns_complicated(self, dag_maker, config):
with dag_maker(serialized=True):
s1 = PythonOperator(task_id="s1", python_callable=print).as_setup()
s2 = PythonOperator(task_id="s2", python_callable=print).as_setup()
op1 = ShortCircuitOperator(
task_id="op1",
python_callable=lambda: False,
)
op2 = PythonOperator(task_id="op2", python_callable=print)
t1 = PythonOperator(task_id="t1", python_callable=print).as_teardown(setups=s1)
t2 = PythonOperator(task_id="t2", python_callable=print).as_teardown(setups=s2)
if config == "sequence":
s1 >> op1 >> s2 >> op2 >> [t1, t2]
elif config == "parallel":
s1 >> op1 >> s2 >> op2 >> t2 >> t1
else:
raise ValueError("unexpected")
op1.skip = MagicMock()
dagrun = dag_maker.create_dagrun()
tis = dagrun.get_task_instances()
ti: TaskInstance = next(x for x in tis if x.task_id == "op1")
ti._run_raw_task()
# we can't use assert_called_with because it's a set and therefore not ordered
actual_skipped = set(op1.skip.call_args.kwargs["tasks"])
assert actual_skipped == {s2, op2}
def test_short_circuit_with_teardowns_complicated_2(self, dag_maker):
with dag_maker(serialized=True):
s1 = PythonOperator(task_id="s1", python_callable=print).as_setup()
s2 = PythonOperator(task_id="s2", python_callable=print).as_setup()
op1 = ShortCircuitOperator(
task_id="op1",
python_callable=lambda: False,
)
op2 = PythonOperator(task_id="op2", python_callable=print)
op3 = PythonOperator(task_id="op3", python_callable=print)
t1 = PythonOperator(task_id="t1", python_callable=print).as_teardown(setups=s1)
t2 = PythonOperator(task_id="t2", python_callable=print).as_teardown(setups=s2)
s1 >> op1 >> op3 >> t1
s2 >> op2 >> t2
# this is the weird, maybe nonsensical part
# in this case we don't want to skip t2 since it should run
op1 >> t2
op1.skip = MagicMock()
dagrun = dag_maker.create_dagrun()
tis = dagrun.get_task_instances()
ti: TaskInstance = next(x for x in tis if x.task_id == "op1")
ti._run_raw_task()
# we can't use assert_called_with because it's a set and therefore not ordered
actual_kwargs = op1.skip.call_args.kwargs
actual_skipped = set(actual_kwargs["tasks"])
assert actual_skipped == {op3}
@pytest.mark.parametrize("level", [logging.DEBUG, logging.INFO])
def test_short_circuit_with_teardowns_debug_level(self, dag_maker, level, clear_db, caplog):
"""
When logging is debug we convert to a list to log the tasks skipped
before passing them to the skip method.
"""
with dag_maker(serialized=True):
s1 = PythonOperator(task_id="s1", python_callable=print).as_setup()
s2 = PythonOperator(task_id="s2", python_callable=print).as_setup()
op1 = ShortCircuitOperator(
task_id="op1",
python_callable=lambda: False,
)
op2 = PythonOperator(task_id="op2", python_callable=print)
op3 = PythonOperator(task_id="op3", python_callable=print)
t1 = PythonOperator(task_id="t1", python_callable=print).as_teardown(setups=s1)
t2 = PythonOperator(task_id="t2", python_callable=print).as_teardown(setups=s2)
s1 >> op1 >> op3 >> t1
s2 >> op2 >> t2
# this is the weird, maybe nonsensical part
# in this case we don't want to skip t2 since it should run
op1 >> t2
op1.skip = MagicMock()
dagrun = dag_maker.create_dagrun()
tis = dagrun.get_task_instances()
ti: TaskInstance = next(x for x in tis if x.task_id == "op1")
with caplog.at_level(level):
if hasattr(ti.task.log, "setLevel"):
# Compat with Pre Airflow 3.1
ti.task.log.setLevel(level)
ti._run_raw_task()
# we can't use assert_called_with because it's a set and therefore not ordered
actual_kwargs = op1.skip.call_args.kwargs
actual_skipped = actual_kwargs["tasks"]
if level <= logging.DEBUG:
assert isinstance(actual_skipped, list)
else:
assert isinstance(actual_skipped, Generator)
assert set(actual_skipped) == {op3}
@pytest.mark.parametrize(
("text_input", "expected_tuple"),
[
pytest.param(" 2.7.18.final.0 ", (2, 7, 18, "final", 0), id="py27"),
pytest.param("3.10.13.final.0\n", (3, 10, 13, "final", 0), id="py310"),
pytest.param("\n3.13.0.alpha.3", (3, 13, 0, "alpha", 3), id="py313-alpha"),
],
)
def test_parse_version_info(text_input, expected_tuple):
assert _parse_version_info(text_input) == expected_tuple
@pytest.mark.parametrize(
"text_input",
[
pytest.param(" 2.7.18.final.0.3 ", id="more-than-5-parts"),
pytest.param("3.10.13\n", id="less-than-5-parts"),
pytest.param("Apache Airflow 3.0.0", id="garbage-input"),
],
)
def test_parse_version_invalid_parts(text_input):
with pytest.raises(ValueError, match=r"expected 5 components separated by '\.'"):
_parse_version_info(text_input)
@pytest.mark.parametrize(
"text_input",
[
pytest.param("2EOL.7.18.final.0", id="major-non-int"),
pytest.param("3.XXX.13.final.3", id="minor-non-int"),
pytest.param("3.13.0a.alpha.3", id="micro-non-int"),
pytest.param("3.8.18.alpha.beta", id="serial-non-int"),
],
)
def test_parse_version_invalid_parts_types(text_input):
with pytest.raises(ValueError, match="Unable to convert parts.*parsed from.*to"):
_parse_version_info(text_input)
def test_python_version_info_fail_subprocess(mocker):
mocked_subprocess = mocker.patch("subprocess.check_output")
mocked_subprocess.side_effect = RuntimeError("some error")
with pytest.raises(ValueError, match="Error while executing command.*some error"):
_PythonVersionInfo.from_executable("/dev/null")
mocked_subprocess.assert_called_once()
def test_python_version_info(mocker):
result = _PythonVersionInfo.from_executable(sys.executable)
assert result.major == sys.version_info.major
assert result.minor == sys.version_info.minor
assert result.micro == sys.version_info.micro
assert result.releaselevel == sys.version_info.releaselevel
assert result.serial == sys.version_info.serial
assert list(result) == list(sys.version_info)
| TestShortCircuitWithTeardown |
python | davidhalter__jedi | jedi/api/helpers.py | {
"start": 6787,
"end": 18982
} | class ____:
def __init__(self, bracket_leaf, children, position):
self.bracket_leaf = bracket_leaf
self._children = children
self._position = position
@property
def index(self):
return _get_index_and_key(self._children, self._position)[0]
@property
def keyword_name_str(self):
return _get_index_and_key(self._children, self._position)[1]
@memoize_method
def _list_arguments(self):
return list(_iter_arguments(self._children, self._position))
def calculate_index(self, param_names):
positional_count = 0
used_names = set()
star_count = -1
args = self._list_arguments()
if not args:
if param_names:
return 0
else:
return None
is_kwarg = False
for i, (star_count, key_start, had_equal) in enumerate(args):
is_kwarg |= had_equal | (star_count == 2)
if star_count:
pass # For now do nothing, we don't know what's in there here.
else:
if i + 1 != len(args): # Not last
if had_equal:
used_names.add(key_start)
else:
positional_count += 1
for i, param_name in enumerate(param_names):
kind = param_name.get_kind()
if not is_kwarg:
if kind == Parameter.VAR_POSITIONAL:
return i
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.POSITIONAL_ONLY):
if i == positional_count:
return i
if key_start is not None and not star_count == 1 or star_count == 2:
if param_name.string_name not in used_names \
and (kind == Parameter.KEYWORD_ONLY
or kind == Parameter.POSITIONAL_OR_KEYWORD
and positional_count <= i):
if star_count:
return i
if had_equal:
if param_name.string_name == key_start:
return i
else:
if param_name.string_name.startswith(key_start):
return i
if kind == Parameter.VAR_KEYWORD:
return i
return None
def iter_used_keyword_arguments(self):
for star_count, key_start, had_equal in list(self._list_arguments()):
if had_equal and key_start:
yield key_start
def count_positional_arguments(self):
count = 0
for star_count, key_start, had_equal in self._list_arguments()[:-1]:
if star_count or key_start:
break
count += 1
return count
def _iter_arguments(nodes, position):
def remove_after_pos(name):
if name.type != 'name':
return None
return name.value[:position[1] - name.start_pos[1]]
# Returns Generator[Tuple[star_count, Optional[key_start: str], had_equal]]
nodes_before = [c for c in nodes if c.start_pos < position]
if nodes_before[-1].type == 'arglist':
yield from _iter_arguments(nodes_before[-1].children, position)
return
previous_node_yielded = False
stars_seen = 0
for i, node in enumerate(nodes_before):
if node.type == 'argument':
previous_node_yielded = True
first = node.children[0]
second = node.children[1]
if second == '=':
if second.start_pos < position and first.type == 'name':
yield 0, first.value, True
else:
yield 0, remove_after_pos(first), False
elif first in ('*', '**'):
yield len(first.value), remove_after_pos(second), False
else:
# Must be a Comprehension
first_leaf = node.get_first_leaf()
if first_leaf.type == 'name' and first_leaf.start_pos >= position:
yield 0, remove_after_pos(first_leaf), False
else:
yield 0, None, False
stars_seen = 0
elif node.type == 'testlist_star_expr':
for n in node.children[::2]:
if n.type == 'star_expr':
stars_seen = 1
n = n.children[1]
yield stars_seen, remove_after_pos(n), False
stars_seen = 0
# The count of children is even if there's a comma at the end.
previous_node_yielded = bool(len(node.children) % 2)
elif isinstance(node, tree.PythonLeaf) and node.value == ',':
if not previous_node_yielded:
yield stars_seen, '', False
stars_seen = 0
previous_node_yielded = False
elif isinstance(node, tree.PythonLeaf) and node.value in ('*', '**'):
stars_seen = len(node.value)
elif node == '=' and nodes_before[-1]:
previous_node_yielded = True
before = nodes_before[i - 1]
if before.type == 'name':
yield 0, before.value, True
else:
yield 0, None, False
# Just ignore the star that is probably a syntax error.
stars_seen = 0
if not previous_node_yielded:
if nodes_before[-1].type == 'name':
yield stars_seen, remove_after_pos(nodes_before[-1]), False
else:
yield stars_seen, '', False
def _get_index_and_key(nodes, position):
"""
Returns the amount of commas and the keyword argument string.
"""
nodes_before = [c for c in nodes if c.start_pos < position]
if nodes_before[-1].type == 'arglist':
return _get_index_and_key(nodes_before[-1].children, position)
key_str = None
last = nodes_before[-1]
if last.type == 'argument' and last.children[1] == '=' \
and last.children[1].end_pos <= position:
# Checked if the argument
key_str = last.children[0].value
elif last == '=':
key_str = nodes_before[-2].value
return nodes_before.count(','), key_str
def _get_signature_details_from_error_node(node, additional_children, position):
for index, element in reversed(list(enumerate(node.children))):
# `index > 0` means that it's a trailer and not an atom.
if element == '(' and element.end_pos <= position and index > 0:
# It's an error node, we don't want to match too much, just
# until the parentheses is enough.
children = node.children[index:]
name = element.get_previous_leaf()
if name is None:
continue
if name.type == 'name' or name.parent.type in ('trailer', 'atom'):
return CallDetails(element, children + additional_children, position)
def get_signature_details(module, position):
leaf = module.get_leaf_for_position(position, include_prefixes=True)
# It's easier to deal with the previous token than the next one in this
# case.
if leaf.start_pos >= position:
# Whitespace / comments after the leaf count towards the previous leaf.
leaf = leaf.get_previous_leaf()
if leaf is None:
return None
# Now that we know where we are in the syntax tree, we start to look at
# parents for possible function definitions.
node = leaf.parent
while node is not None:
if node.type in ('funcdef', 'classdef', 'decorated', 'async_stmt'):
# Don't show signatures if there's stuff before it that just
# makes it feel strange to have a signature.
return None
additional_children = []
for n in reversed(node.children):
if n.start_pos < position:
if n.type == 'error_node':
result = _get_signature_details_from_error_node(
n, additional_children, position
)
if result is not None:
return result
additional_children[0:0] = n.children
continue
additional_children.insert(0, n)
# Find a valid trailer
if node.type == 'trailer' and node.children[0] == '(' \
or node.type == 'decorator' and node.children[2] == '(':
# Additionally we have to check that an ending parenthesis isn't
# interpreted wrong. There are two cases:
# 1. Cursor before paren -> The current signature is good
# 2. Cursor after paren -> We need to skip the current signature
if not (leaf is node.children[-1] and position >= leaf.end_pos):
leaf = node.get_previous_leaf()
if leaf is None:
return None
return CallDetails(
node.children[0] if node.type == 'trailer' else node.children[2],
node.children,
position
)
node = node.parent
return None
@signature_time_cache("call_signatures_validity")
def cache_signatures(inference_state, context, bracket_leaf, code_lines, user_pos):
"""This function calculates the cache key."""
line_index = user_pos[0] - 1
before_cursor = code_lines[line_index][:user_pos[1]]
other_lines = code_lines[bracket_leaf.start_pos[0]:line_index]
whole = ''.join(other_lines + [before_cursor])
before_bracket = re.match(r'.*\(', whole, re.DOTALL)
module_path = context.get_root_context().py__file__()
if module_path is None:
yield None # Don't cache!
else:
yield (module_path, before_bracket, bracket_leaf.start_pos)
yield infer(
inference_state,
context,
bracket_leaf.get_previous_leaf(),
)
def validate_line_column(func):
@wraps(func)
def wrapper(self, line=None, column=None, *args, **kwargs):
line = max(len(self._code_lines), 1) if line is None else line
if not (0 < line <= len(self._code_lines)):
raise ValueError('`line` parameter is not in a valid range.')
line_string = self._code_lines[line - 1]
line_len = len(line_string)
if line_string.endswith('\r\n'):
line_len -= 2
elif line_string.endswith('\n'):
line_len -= 1
column = line_len if column is None else column
if not (0 <= column <= line_len):
raise ValueError('`column` parameter (%d) is not in a valid range '
'(0-%d) for line %d (%r).' % (
column, line_len, line, line_string))
return func(self, line, column, *args, **kwargs)
return wrapper
def get_module_names(module, all_scopes, definitions=True, references=False):
"""
Returns a dictionary with name parts as keys and their call paths as
values.
"""
def def_ref_filter(name):
is_def = name.is_definition()
return definitions and is_def or references and not is_def
names = list(chain.from_iterable(module.get_used_names().values()))
if not all_scopes:
# We have to filter all the names that don't have the module as a
# parent_scope. There's None as a parent, because nodes in the module
# node have the parent module and not suite as all the others.
# Therefore it's important to catch that case.
def is_module_scope_name(name):
parent_scope = get_parent_scope(name)
# async functions have an extra wrapper. Strip it.
if parent_scope and parent_scope.type == 'async_stmt':
parent_scope = parent_scope.parent
return parent_scope in (module, None)
names = [n for n in names if is_module_scope_name(n)]
return filter(def_ref_filter, names)
def split_search_string(name):
type, _, dotted_names = name.rpartition(' ')
if type == 'def':
type = 'function'
return type, dotted_names.split('.')
| CallDetails |
python | tensorflow__tensorflow | tensorflow/python/distribute/distribute_lib.py | {
"start": 37375,
"end": 38913
} | class ____(
collections.namedtuple("RunOptions", [
"experimental_enable_dynamic_batch_size",
"experimental_bucketizing_dynamic_shape",
"experimental_xla_options",
])):
"""Run options for `strategy.run`.
This can be used to hold some strategy specific configs.
Attributes:
experimental_enable_dynamic_batch_size: Boolean. Only applies to
TPUStrategy. Default to True. If True, TPUStrategy will enable dynamic
padder to support dynamic batch size for the inputs. Otherwise only static
shape inputs are allowed.
experimental_bucketizing_dynamic_shape: Boolean. Only applies to
TPUStrategy. Default to False. If True, TPUStrategy will automatic
bucketize inputs passed into `run` if the input shape is
dynamic. This is a performance optimization to reduce XLA recompilation,
which should not have impact on correctness.
experimental_xla_options: A `tf.tpu.XLAOptions` instance. Only applies to
TPUStrategy. Controls the XLA compiling options on TPUs. Default to None.
"""
def __new__(cls,
experimental_enable_dynamic_batch_size=True,
experimental_bucketizing_dynamic_shape=False,
experimental_xla_options=None):
return super(RunOptions,
cls).__new__(cls, experimental_enable_dynamic_batch_size,
experimental_bucketizing_dynamic_shape,
experimental_xla_options)
@tf_export("distribute.InputOptions", v1=[])
| RunOptions |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/ctl/commands/test_connections_command.py | {
"start": 1141,
"end": 4510
} | class ____:
connection_id = "test_connection"
export_file_name = "exported_json.json"
parser = cli_parser.get_parser()
connection_collection_response = ConnectionCollectionResponse(
connections=[
ConnectionResponse(
connection_id=connection_id,
conn_type="test_type",
host="test_host",
login="test_login",
password="test_password",
port=1234,
extra="{}",
description="Test connection description",
)
],
total_entries=1,
)
bulk_response_success = BulkResponse(
create=BulkActionResponse(success=[connection_id], errors=[]), update=None, delete=None
)
bulk_response_error = BulkResponse(
create=BulkActionResponse(
success=[],
errors=[
{
"error": f"The connection with these connection_ids: {{'{connection_id}'}} already exist.",
"status_code": 409,
}
],
),
update=None,
delete=None,
)
def test_import_success(self, api_client_maker, tmp_path, monkeypatch):
api_client = api_client_maker(
path="/api/v2/connections",
response_json=self.bulk_response_success.model_dump(),
expected_http_status_code=200,
kind=ClientKind.CLI,
)
monkeypatch.chdir(tmp_path)
expected_json_path = tmp_path / self.export_file_name
connection_file = {
self.connection_id: {
"conn_type": "test_type",
"host": "test_host",
"login": "test_login",
"password": "test_password",
"port": 1234,
"extra": "{}",
"description": "Test connection description",
"connection_id": self.connection_id,
}
}
expected_json_path.write_text(json.dumps(connection_file))
connection_command.import_(
self.parser.parse_args(["connections", "import", expected_json_path.as_posix()]),
api_client=api_client,
)
def test_import_error(self, api_client_maker, tmp_path, monkeypatch):
api_client = api_client_maker(
path="/api/v2/connections",
response_json=self.bulk_response_error.model_dump(),
expected_http_status_code=200,
kind=ClientKind.CLI,
)
monkeypatch.chdir(tmp_path)
expected_json_path = tmp_path / self.export_file_name
connection_file = {
self.connection_id: {
"conn_type": "test_type",
"host": "test_host",
"login": "test_login",
"password": "test_password",
"port": 1234,
"extra": "{}",
"description": "Test connection description",
"connection_id": self.connection_id,
}
}
expected_json_path.write_text(json.dumps(connection_file))
with pytest.raises(SystemExit):
connection_command.import_(
self.parser.parse_args(["connections", "import", expected_json_path.as_posix()]),
api_client=api_client,
)
| TestCliConnectionCommands |
python | apache__airflow | providers/microsoft/winrm/src/airflow/providers/microsoft/winrm/operators/winrm.py | {
"start": 1519,
"end": 5154
} | class ____(BaseOperator):
"""
WinRMOperator to execute commands on given remote host using the winrm_hook.
:param winrm_hook: predefined ssh_hook to use for remote execution
:param ssh_conn_id: connection id from airflow Connections
:param remote_host: remote host to connect
:param command: command to execute on remote host. (templated)
:param ps_path: path to powershell, `powershell` for v5.1- and `pwsh` for v6+.
If specified, it will execute the command as powershell script.
:param output_encoding: the encoding used to decode stout and stderr
:param timeout: timeout for executing the command.
:param expected_return_code: expected return code value(s) of command.
:param working_directory: specify working directory.
"""
template_fields: Sequence[str] = (
"command",
"working_directory",
)
template_fields_renderers = {"command": "powershell", "working_directory": "powershell"}
def __init__(
self,
*,
winrm_hook: WinRMHook | None = None,
ssh_conn_id: str | None = None,
remote_host: str | None = None,
command: str | None = None,
ps_path: str | None = None,
output_encoding: str = "utf-8",
timeout: int = 10,
expected_return_code: int | list[int] | range = 0,
working_directory: str | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.winrm_hook = winrm_hook
self.ssh_conn_id = ssh_conn_id
self.remote_host = remote_host
self.command = command
self.ps_path = ps_path
self.output_encoding = output_encoding
self.timeout = timeout
self.expected_return_code = expected_return_code
self.working_directory = working_directory
def execute(self, context: Context) -> list | str:
if self.ssh_conn_id and not self.winrm_hook:
self.log.info("Hook not found, creating...")
self.winrm_hook = WinRMHook(ssh_conn_id=self.ssh_conn_id)
if not self.winrm_hook:
raise AirflowException("Cannot operate without winrm_hook or ssh_conn_id.")
if self.remote_host is not None:
self.winrm_hook.remote_host = self.remote_host
if not self.command:
raise AirflowException("No command specified so nothing to execute here.")
return_code, stdout_buffer, stderr_buffer = self.winrm_hook.run(
command=self.command,
ps_path=self.ps_path,
output_encoding=self.output_encoding,
return_output=self.do_xcom_push,
working_directory=self.working_directory,
)
success = False
if isinstance(self.expected_return_code, int):
success = return_code == self.expected_return_code
elif isinstance(self.expected_return_code, list) or isinstance(self.expected_return_code, range):
success = return_code in self.expected_return_code
if success:
# returning output if do_xcom_push is set
# TODO: Remove this after minimum Airflow version is 3.0
enable_pickling = conf.getboolean("core", "enable_xcom_pickling", fallback=False)
if enable_pickling:
return stdout_buffer
return b64encode(b"".join(stdout_buffer)).decode(self.output_encoding)
stderr_output = b"".join(stderr_buffer).decode(self.output_encoding)
error_msg = f"Error running cmd: {self.command}, return code: {return_code}, error: {stderr_output}"
raise AirflowException(error_msg)
| WinRMOperator |
python | joke2k__faker | faker/providers/company/nl_NL/__init__.py | {
"start": 45,
"end": 11847
} | class ____(CompanyProvider):
formats = (
"{{last_name}} {{company_suffix}}",
"{{last_name}} & {{last_name}}",
"{{company_prefix}} {{last_name}}",
"{{large_company}}",
)
company_prefixes = (
"Stichting",
"Koninklijke",
"Royal",
)
company_suffixes = (
"BV",
"NV",
"Groep",
)
# Source: https://www.mt.nl/management/reputatie/mt-500-2018-de-lijst/559930
large_companies = (
"Shell",
"Coolblue",
"ASML",
"Ahold",
"Tata Steel",
"KLM",
"Bol.com",
"BP Nederland",
"De Efteling",
"Eneco",
"De Persgroep",
"ING",
"Royal HaskoningDHV",
"Randstad",
"Google",
"Ikea",
"Rockwool",
"BAM",
"Achmea",
"Damen Shipyard",
"ABN Amro",
"Remeha Group",
"TenneT",
"Coca-Cola",
"Van Leeuwen Buizen",
"Wavin",
"Rabobank",
"AkzoNobel",
"Arcadis",
"AFAS",
"Cisco",
"DAF Trucks",
"DHL",
"Hanos",
"Boon Edam",
"BMW Nederland",
"The Greenery",
"Dutch Flower Group",
"Koninklijke Mosa",
"Yacht",
"Rituals",
"Microsoft",
"Esso",
"3W Vastgoed",
"Deloitte",
"Corio",
"Voortman Steel Group",
"Agrifirm",
"Makro Nederland",
"Nederlandse Publieke Omroep",
"De Alliantie",
"Heijmans",
"McDonalds",
"ANWB",
"Mediamarkt",
"Kruidvat" "Van Merksteijn Steel",
"Dura Vermeer",
"Alliander",
"Unilever",
"Enexis",
"Berenschot",
"Jumbo",
"Technische Unie",
"Havenbedrijf Rotterdam",
"Ballast Nedam",
"RTL Nederland",
"Talpa Media",
"Blauwhoed Vastgoed",
"DSM",
"Ymere",
"Witteveen+Bos",
"NS",
"Action",
"FloraHolland",
"Heineken",
"Nuon",
"EY",
"Dow Benelux",
"Bavaria",
"Schiphol",
"Holland Casino",
"Binck bank",
"BDO",
"HEMA",
"Alphabet Nederland",
"Croon Elektrotechniek",
"ASR Vastgoed ontwikkeling",
"PwC",
"Mammoet",
"KEMA",
"IBM",
"A.S. Watson",
"KPMG",
"VodafoneZiggo",
"YoungCapital",
"Triodos Bank",
"Aviko",
"AgruniekRijnvallei",
"Heerema",
"Accenture",
"Aegon",
"NXP",
"Breman Installatiegroep",
"Movares Groep",
"Q-Park",
"FleuraMetz",
"Sanoma",
"Bakker Logistiek",
"VDL Group",
"Bayer",
"Boskalis",
"Nutreco",
"Dell",
"Brunel",
"Exact",
"Manpower",
"Essent",
"Canon",
"ONVZ Zorgverzekeraar",
"Telegraaf Media Group",
"Nationale Nederlanden",
"Andus Group",
"Den Braven Group",
"ADP",
"ASR",
"ArboNed",
"Plieger",
"De Heus Diervoeders",
"USG People",
"Bidvest Deli XL",
"Apollo Vredestein",
"Tempo-Team",
"Trespa",
"Janssen Biologics",
"Starbucks",
"PostNL",
"Vanderlande",
"FrieslandCampina",
"Constellium",
"Huisman",
"Abbott",
"Koninklijke Boom Uitgevers",
"Bosch Rexroth",
"BASF",
"Audax",
"VolkerWessels",
"Hunkemöller",
"Athlon Car Lease",
"DSW Zorgverzekeraar",
"Mars",
"De Brauw Blackstone Westbroek",
"NDC Mediagroep",
"Bluewater",
"Stedin",
"Feenstra",
"Wuppermann Staal Nederland",
"Kramp",
"SABIC",
"Iv-Groep",
"Bejo Zaden",
"Wolters Kluwer",
"Nyrstar holding",
"Adecco",
"Tauw",
"Robeco",
"Eriks",
"Allianz Nederland Groep",
"Driessen",
"Burger King",
"Lekkerland",
"Van Lanschot",
"Brocacef",
"Bureau Veritas",
"Relx",
"Pathé Bioscopen",
"Bosal",
"Ardagh Group",
"Maandag",
"Inalfa",
"Atradius",
"Capgemini",
"Greenchoice",
"Q8 (Kuwait Petroleum Europe)",
"ASM International",
"Van der Valk",
"Delta Lloyd",
"GlaxoSmithKline",
"ABB",
"Fabory, a Grainger company",
"Veen Bosch & Keuning Uitgeversgroep",
"CZ",
"Plus",
"RET Rotterdam",
"Loyens & Loeff",
"Holland Trading",
"Archer Daniels Midland Nederland",
"Ten Brinke",
"NAM",
"DAS",
"Samsung Electronics Benelux",
"Koopman International",
"TUI",
"Lannoo Meulenhoff",
"AC Restaurants",
"Stage Entertainment",
"Acer",
"HDI Global SE",
"Detailresult",
"Nestle",
"GVB Amsterdam",
"Dekamarkt",
"Dirk",
"MSD",
"Arriva",
"Baker Tilly Berk",
"SBM Offshore",
"TomTom",
"Fujifilm",
"B&S",
"BCC",
"Gasunie",
"Oracle Nederland",
"Astellas Pharma",
"SKF",
"Woningstichting Eigen Haard",
"Rijk Zwaan",
"Chubb",
"Fugro",
"Total",
"Rochdale",
"ASVB",
"Atos",
"Acomo",
"KPN",
"Van Drie Group",
"Olympia uitzendbureau",
"Bacardi Nederland",
"JMW Horeca Uitzendbureau",
"Warner Bros/Eyeworks",
"Aalberts Industries",
"SNS Bank",
"Amtrada Holding",
"VGZ",
"Grolsch",
"Office Depot",
"De Rijke Group",
"Bovemij Verzekeringsgroep",
"Coop Nederland",
"Eaton Industries",
"ASN",
"Yara Sluiskil",
"HSF Logistics",
"Fokker",
"Deutsche Bank",
"Sweco",
"Univé Groep",
"Koninklijke Wagenborg",
"Strukton",
"Conclusion",
"Philips",
"In Person",
"Fluor",
"Vroegop-Windig",
"ArboUnie",
"Centraal Boekhuis",
"Siemens",
"Connexxion",
"Fujitsu",
"Consolid",
"AVR Afvalverwerking",
"Brabant Alucast",
"Centric",
"Havensteder",
"Novartis",
"Booking.com",
"Menzis",
"Frankort & Koning Groep",
"Jan de Rijk",
"Brand Loyalty Group",
"Ohra Verzekeringen",
"Terberg Group",
"Cloetta",
"Holland & Barrett",
"Enza Zaden",
"VION",
"Woonzorg Nederland",
"T-Mobile",
"Crucell",
"NautaDutilh",
"BNP Paribas",
"NIBC Bank",
"VastNed",
"CCV Holland",
"IHC Merwede",
"Neways",
"NSI N.V.",
"Deen",
"Accor",
"HTM",
"ITM Group",
"Ordina",
"Dümmen Orange",
"Optiver",
"Zara",
"L'Oreal Nederland B.V.",
"Vinci Energies",
"Suit Supply Topco",
"Sita",
"Vos Logistics",
"Altran",
"St. Clair",
"BESI",
"Fiat Chrysler Automobiles",
"UPS",
"Jacobs",
"Emté",
"TBI",
"De Bijenkorf",
"Aldi Nederland",
"Van Wijnen",
"Vitens",
"De Goudse Verzekeringen",
"SBS Broadcasting",
"Sandd",
"Omron",
"Sogeti",
"Alfa Accountants & Adviseurs",
"Harvey Nash",
"Stork",
"Glencore Grain",
"Meijburg & Co",
"Honeywell",
"Meyn",
"Ericsson Telecommunicatie",
"Hurks",
"Mitsubishi",
"GGN",
"CGI Nederland",
"Staples Nederland",
"Denkavit International",
"Ecorys",
"Rexel Nederland",
"A. Hakpark",
"DuPont Nederland",
"CBRE Group",
"Bolsius",
"Marel",
"Metro",
"Flynth Adviseurs en Accountants",
"Kropman Installatietechniek",
"Kuijpers",
"Medtronic",
"Cefetra",
"Simon Loos",
"Citadel Enterprises",
"Intergamma",
"Ceva Logistics",
"Beter Bed",
"Subway",
"Gamma",
"Karwei" "Varo Energy",
"APM Terminals",
"Center Parcs",
"Brenntag Nederland",
"NFI",
"Hoogvliet",
"Van Gansewinkel",
"Nedap",
"Blokker",
"Perfetti Van Melle",
"Vestia",
"Kuehne + Nagel Logistics",
"Rensa Group",
"NTS Group",
"Joh. Mourik & Co. Holding",
"Mercedes-Benz",
"DIT Personeel",
"Verkade",
"Hametha",
"Vopak",
"IFF",
"Pearle",
"Mainfreight",
"De Jong & Laan",
"DSV",
"P4People",
"Mazars",
"Cargill",
"Ten Brinke Groep",
"Alewijnse",
"Agio Cigars",
"Peter Appel Transport",
"Syngenta",
"Avery Dennison",
"Accon AVM",
"Vitol",
"Vermaat Groep",
"BMC",
"Alcatel-Lucent",
"Maxeda DIY",
"Equens",
"Van Gelder Groep",
"Emerson Electric Nederland",
"Bakkersland",
"Specsavers",
"E.On",
"Landal Greenparks",
"IMC Trading",
"Barentz Group",
"Epson",
"Raet",
"Van Oord",
"Thomas Cook Nederland",
"SDU uitgevers",
"Nedschroef",
"Linde Gas",
"Ewals Cargo Care",
"Theodoor Gilissen",
"TMF Group",
"Cornelis Vrolijk",
"Jan Linders Supermarkten",
"SIF group",
"BT Nederland",
"Kinepolis",
"Pink Elephant",
"General Motors Nederland",
"Carlson Wagonlit",
"Bruna",
"Docdata",
"Schenk Tanktransport",
"WPG",
"Peak-IT",
"Martinair",
"Reesink",
"Elopak Nederland",
"Fagron N.V.",
"OVG Groep",
"Ford Nederland",
"Multi Corporation",
"Simac",
"Primark",
"Tech Data Nederland",
"Vleesgroothandel Zandbergen",
"Raben Group",
"Farm Frites",
"Libéma",
"Caldic",
"Portaal",
"Syntus",
"Jacobs DE",
"Stena Line",
"The Phone House",
"Interfood Group",
"Thales",
"Teva Pharmaceuticals",
"RFS Holland",
"Aebi Schmidt Nederland",
"Rockwell Automation Nederland",
"Engie Services",
"Hendrix Genetics",
"Qbuzz",
"Unica",
"2SistersFoodGroup",
"Ziut",
"Munckhof Groep",
"Spar Holding",
"Samskip",
"Continental Bakeries",
"Sligro",
"Merck",
"Foot Locker Europe",
"Unit4",
"PepsiCo",
"Sulzer",
"Tebodin",
"Value8",
"Boels",
"DKG Groep",
"Bruynzeel Keukens",
"Janssen de Jong Groep",
"ProRail",
"Solid Professionals",
"Hermes Partners",
)
def large_company(self) -> str:
"""
:example: 'Bol.com'
"""
return self.random_element(self.large_companies)
def company_prefix(self) -> str:
"""
:example: 'Stichting'
"""
return self.random_element(self.company_prefixes)
| Provider |
python | Lightning-AI__lightning | tests/tests_pytorch/helpers/datamodules.py | {
"start": 4277,
"end": 4754
} | class ____(SklearnDataModule):
def __init__(self, num_features=16, length=800, batch_size=10):
if not _SKLEARN_AVAILABLE:
raise ImportError(str(_SKLEARN_AVAILABLE))
from sklearn.datasets import make_regression
x, y = make_regression(n_samples=length, n_features=num_features, random_state=42)
y = [[v] for v in y]
super().__init__((x, y), x_type=torch.float32, y_type=torch.float32, batch_size=batch_size)
| RegressDataModule |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 99364,
"end": 99450
} | class ____(_numpy_info):
section = 'Numeric'
modulename = 'Numeric'
| Numeric_info |
python | qdrant__qdrant-client | qdrant_client/local/multi_distances.py | {
"start": 287,
"end": 1221
} | class ____:
def __init__(
self,
positive: Optional[list[list[list[float]]]] = None, # list of matrices
negative: Optional[list[list[list[float]]]] = None, # list of matrices
strategy: Optional[models.RecommendStrategy] = None,
):
assert strategy is not None, "Recommend strategy must be provided"
self.strategy = strategy
positive = positive if positive is not None else []
negative = negative if negative is not None else []
for vector in positive:
assert not np.isnan(vector).any(), "Positive vectors must not contain NaN"
for vector in negative:
assert not np.isnan(vector).any(), "Negative vectors must not contain NaN"
self.positive: list[types.NumpyArray] = [np.array(vector) for vector in positive]
self.negative: list[types.NumpyArray] = [np.array(vector) for vector in negative]
| MultiRecoQuery |
python | kamyu104__LeetCode-Solutions | Python/find-the-longest-valid-obstacle-course-at-each-position.py | {
"start": 3009,
"end": 3559
} | class ____(object):
def longestObstacleCourseAtEachPosition(self, obstacles):
"""
:type obstacles: List[int]
:rtype: List[int]
"""
sorted_obstacles = sorted(set(obstacles))
lookup = {x:i for i, x in enumerate(sorted_obstacles)}
segment_tree = SegmentTree(len(lookup))
result = []
for x in obstacles:
cnt = segment_tree.query(0, lookup[x])+1
result.append(cnt)
segment_tree.update(lookup[x], lookup[x], cnt)
return result
| Solution2_TLE |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 17073,
"end": 18539
} | class ____(nodes.Inline, nodes.FixedTextElement):
"""Node for references to manpages."""
def setup(app: Sphinx) -> ExtensionMetadata:
app.add_node(toctree)
app.add_node(desc)
app.add_node(desc_signature)
app.add_node(desc_signature_line)
app.add_node(desc_content)
app.add_node(desc_inline)
app.add_node(desc_name)
app.add_node(desc_addname)
app.add_node(desc_type)
app.add_node(desc_returns)
app.add_node(desc_parameterlist)
app.add_node(desc_type_parameter_list)
app.add_node(desc_parameter)
app.add_node(desc_type_parameter)
app.add_node(desc_optional)
app.add_node(desc_annotation)
for n in SIG_ELEMENTS:
app.add_node(n)
app.add_node(versionmodified)
app.add_node(seealso)
app.add_node(productionlist)
app.add_node(production)
app.add_node(index)
app.add_node(centered)
app.add_node(acks)
app.add_node(hlist)
app.add_node(hlistcol)
app.add_node(compact_paragraph)
app.add_node(glossary)
app.add_node(only)
app.add_node(start_of_file)
app.add_node(highlightlang)
app.add_node(tabular_col_spec)
app.add_node(pending_xref)
app.add_node(number_reference)
app.add_node(download_reference)
app.add_node(literal_emphasis)
app.add_node(literal_strong)
app.add_node(manpage)
return {
'version': 'builtin',
'parallel_read_safe': True,
'parallel_write_safe': True,
}
| manpage |
python | google__pytype | pytype/load_pytd.py | {
"start": 8011,
"end": 11236
} | class ____:
"""Resolve symbols in a pytd tree."""
def __init__(self, builtins_ast):
self.builtins_ast = builtins_ast
self.allow_singletons = False
def _lookup(self, visitor, mod_ast, lookup_ast):
if lookup_ast:
visitor.EnterTypeDeclUnit(lookup_ast)
mod_ast = mod_ast.Visit(visitor)
return mod_ast
def resolve_local_types(self, mod_ast, *, lookup_ast=None):
local_lookup = visitors.LookupLocalTypes(self.allow_singletons)
return self._lookup(local_lookup, mod_ast, lookup_ast)
def resolve_builtin_types(self, mod_ast, *, lookup_ast=None):
bltn_lookup = visitors.LookupBuiltins(
self.builtins_ast,
full_names=False,
allow_singletons=self.allow_singletons,
)
mod_ast = self._lookup(bltn_lookup, mod_ast, lookup_ast)
return mod_ast
def resolve_external_types(self, mod_ast, module_map, aliases, *, mod_name):
"""Resolves external types in mod_ast."""
name = mod_name or mod_ast.name
try:
return mod_ast.Visit(
visitors.LookupExternalTypes(
module_map, self_name=name, module_alias_map=aliases[name]
)
)
except KeyError as e:
key_error = e
all_aliases = _merge_aliases(aliases)
new_aliases = dict(aliases[name])
while isinstance(key_error, visitors.MissingModuleError):
if key_error.module not in all_aliases:
break
new_aliases[key_error.module] = all_aliases[key_error.module]
try:
return mod_ast.Visit(
visitors.LookupExternalTypes(
module_map, self_name=name, module_alias_map=new_aliases
)
)
except KeyError as e:
key_error = e
key = "".join(str(arg) for arg in key_error.args)
raise BadDependencyError(key, name) from key_error
def resolve_module_alias(
self, name, *, lookup_ast=None, lookup_ast_name=None
):
"""Check if a given name is an alias and resolve it if so."""
# name is bare, but aliases are stored as "ast_name.alias".
if lookup_ast is None:
return name
ast_name = lookup_ast_name or lookup_ast.name
aliases = dict(lookup_ast.aliases)
cur_name = name
while cur_name:
key = f"{ast_name}.{cur_name}"
value = aliases.get(key)
if isinstance(value, pytd.Module):
return value.module_name + name[len(cur_name) :]
cur_name, _, _ = cur_name.rpartition(".")
return name
def verify(self, mod_ast, *, mod_name=None):
try:
mod_ast.Visit(visitors.VerifyLookup(ignore_late_types=True))
except ValueError as e:
name = mod_name or mod_ast.name
raise BadDependencyError(str(e), name) from e
mod_ast.Visit(visitors.VerifyContainers())
mod_ast.Visit(visitors.VerifyLiterals())
@classmethod
def collect_dependencies(cls, mod_ast):
"""Goes over an ast and returns all references module names."""
deps = visitors.CollectDependencies()
mod_ast.Visit(deps)
if isinstance(mod_ast, (pytd.TypeDeclUnit, pytd.Class)):
return {
k: v
for k, v in deps.dependencies.items()
if not isinstance(mod_ast.Get(k), (pytd.Class, pytd.ParamSpec))
}
else:
return deps.dependencies
| _Resolver |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_dataflow.py | {
"start": 6925,
"end": 14054
} | class ____:
@pytest.mark.parametrize(
("job_current_state", "fail_on_terminal_state"),
[
(DataflowJobStatus.JOB_STATE_RUNNING, True),
(DataflowJobStatus.JOB_STATE_RUNNING, False),
(DataflowJobStatus.JOB_STATE_DONE, False),
],
)
@mock.patch("airflow.providers.google.cloud.sensors.dataflow.DataflowHook")
def test_poke(self, mock_hook, job_current_state, fail_on_terminal_state):
mock_get_job = mock_hook.return_value.get_job
mock_fetch_job_metrics_by_id = mock_hook.return_value.fetch_job_metrics_by_id
callback = mock.MagicMock()
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=callback,
fail_on_terminal_state=fail_on_terminal_state,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_get_job.return_value = {"id": TEST_JOB_ID, "currentState": job_current_state}
results = task.poke(mock.MagicMock())
assert callback.return_value == results
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_fetch_job_metrics_by_id.assert_called_once_with(
job_id=TEST_JOB_ID, project_id=TEST_PROJECT_ID, location=TEST_LOCATION
)
mock_fetch_job_metrics_by_id.return_value.__getitem__.assert_called_once_with("metrics")
callback.assert_called_once_with(mock_fetch_job_metrics_by_id.return_value.__getitem__.return_value)
@mock.patch("airflow.providers.google.cloud.sensors.dataflow.DataflowHook")
def test_poke_raise_exception(self, mock_hook):
mock_get_job = mock_hook.return_value.get_job
mock_fetch_job_messages_by_id = mock_hook.return_value.fetch_job_messages_by_id
callback = mock.MagicMock()
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=callback,
fail_on_terminal_state=True,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_get_job.return_value = {"id": TEST_JOB_ID, "currentState": DataflowJobStatus.JOB_STATE_DONE}
with pytest.raises(
AirflowException,
match=f"Job with id '{TEST_JOB_ID}' is already in terminal state: "
f"{DataflowJobStatus.JOB_STATE_DONE}",
):
task.poke(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_fetch_job_messages_by_id.assert_not_called()
callback.assert_not_called()
@mock.patch("airflow.providers.google.cloud.hooks.dataflow.AsyncDataflowHook")
def test_execute_enters_deferred_state(self, mock_hook):
"""
Tests that DataflowJobMetricsTrigger will be fired when the DataflowJobMetricsSensor
is executed and deferrable is set to True.
"""
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
callback=None,
)
mock_hook.return_value.exists.return_value = False
with pytest.raises(TaskDeferred) as exc:
task.execute(None)
assert isinstance(exc.value.trigger, DataflowJobMetricsTrigger), (
"Trigger is not a DataflowJobMetricsTrigger"
)
def test_execute_complete_success_without_callback_function(self):
"""Tests that the trigger event contains expected values if no callback function is provided."""
expected_result = []
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
callback=None,
)
actual_message = task.execute_complete(
context=None,
event={
"status": "success",
"message": f"Detected 2 metrics for job '{TEST_JOB_ID}'",
"result": [],
},
)
assert actual_message == expected_result
def test_execute_complete_success_with_callback_function(self):
"""Tests that the trigger event contains expected values if the callback function is provided."""
expected_result = [
{
"name": {"origin": "", "name": "", "context": {}},
"scalar": 0.0,
"update_time": "2024-03-20T12:36:05.229Z",
"kind": "",
"cumulative": False,
},
{
"name": {"origin": "", "name": "", "context": {}},
"scalar": 0.0,
"update_time": "2024-03-20T12:36:05.229Z",
"kind": "",
"cumulative": False,
},
]
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=lambda res: res,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
)
actual_result = task.execute_complete(
context=None,
event={
"status": "success",
"message": f"Detected 2 job messages for job '{TEST_JOB_ID}'",
"result": expected_result,
},
)
assert actual_result == expected_result
def test_execute_complete_not_success_status_raises_exception(self):
"""Tests that AirflowException or AirflowSkipException is raised if the trigger event contains an error."""
task = DataflowJobMetricsSensor(
task_id=TEST_TASK_ID,
job_id=TEST_JOB_ID,
callback=None,
fail_on_terminal_state=False,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
deferrable=True,
)
with pytest.raises(AirflowException):
task.execute_complete(
context=None, event={"status": "error", "message": "test error message", "result": None}
)
| TestDataflowJobMetricsSensor |
python | pytorch__pytorch | torch/distributed/_shard/sharding_spec/chunk_sharding_spec.py | {
"start": 902,
"end": 9309
} | class ____(ShardingSpec):
"""
This is a type of PlacementSpec that defines the placement as being sharded
across multiple devices. In particular, it represents sharding a Tensor
along a single dimension into equal chunks (similar to :meth:`torch.chunk`).
The semantics of how a tensor is partitioned is inline with
:meth:`torch.chunk`, where ``dim`` in torch.chunk corresponds to the
specified ``dim`` and ``chunks`` in torch.chunk is the number of elements
in the placement specified.
Args:
dim (int or str):
The dimension to shard on, could be an integer representing the
dimension or a string in case of named tensors where dimensions are
named. Note that named tensor support is not added yet.
placement(List[Union[_remote_device, str]]):
Specifies the placement of each shard of the Tensor. The size of
the list represents the number of shards to be created. This could
be a list of
:class:`torch.distributed._remote_device`'s. This list
could also contain a string which represents remote
device as accepted by
:class:`torch.distributed._remote_device`
"""
ShardingDim = Union[int, str]
dim: ShardingDim
placements: list[Union[torch.distributed._remote_device, str]]
def __post_init__(self):
self._verify_dim(self.dim)
for i, remote_device in enumerate(self.placements):
if not isinstance(remote_device, torch.distributed._remote_device):
self.placements[i] = torch.distributed._remote_device(remote_device)
@staticmethod
def _verify_dim(dim):
# Validate the sharding spec.
# TODO: support named dimension
if isinstance(dim, str):
raise NotImplementedError(
"ChunkShardingSpec does not support named dimension yet!"
)
if not isinstance(dim, int):
raise ValueError(f"Sharding dim needs to be an integer, found: {dim}")
def build_metadata(
self,
tensor_sizes: torch.Size,
tensor_properties: sharded_tensor_meta.TensorProperties,
) -> sharded_tensor_meta.ShardedTensorMetadata:
tensor_num_dim = len(tensor_sizes)
self._verify_dim(self.dim)
if self.dim >= tensor_num_dim or self.dim < -tensor_num_dim: # type: ignore[operator]
raise ValueError(f"Invalid sharding dim: {self.dim}")
shards_metadata = []
sharding_dim_size = tensor_sizes[self.dim] # type: ignore[index]
chunks = len(self.placements)
split_size = get_split_size(sharding_dim_size, chunks)
for idx, placement in enumerate(self.placements):
# generate ShardMetadata for each placement device
chunked_dim_size = get_chunked_dim_size(sharding_dim_size, split_size, idx)
shard_size = list(tensor_sizes)
current_offsets = [0] * tensor_num_dim
current_offsets[self.dim] = split_size * idx # type: ignore[index]
shard_size[self.dim] = chunked_dim_size # type: ignore[index]
shard_metadata = ShardMetadata(
shard_offsets=current_offsets,
shard_sizes=shard_size,
placement=placement,
)
shards_metadata.append(shard_metadata)
return sharded_tensor_meta.ShardedTensorMetadata(
shards_metadata, tensor_sizes, tensor_properties
)
def shard(
self, tensor: torch.Tensor, src_rank: int = 0, process_group=None
) -> "ShardedTensor":
"""
Args:
src_rank: group rank relative to ``process_group``
N.B. If ``process_group`` is None, ``src_rank`` is a global rank.
"""
# relative imports to avoid circular dependency
from torch.distributed._shard.sharded_tensor import ShardedTensor
tensor_properties = sharded_tensor_meta.TensorProperties(
dtype=tensor.dtype,
layout=tensor.layout,
requires_grad=tensor.requires_grad,
memory_format=torch.contiguous_format,
pin_memory=tensor.is_pinned(),
)
current_rank = dist.get_rank(process_group)
current_global_rank = dist.get_rank()
tensor_meta = self.build_metadata(tensor.size(), tensor_properties)
local_shards = []
local_tensor = None
local_metadata = None
tensors_to_scatter = cast(
list[Optional[torch.Tensor]],
[None] * dist.get_world_size(process_group),
)
sharding_dim_size = tensor.size()[self.dim] # type: ignore[index]
chunks = len(self.placements)
split_size = get_split_size(sharding_dim_size, chunks)
scatter_shape = list(tensor.size())
scatter_shape[self.dim] = split_size # type: ignore[index]
for shard_meta in tensor_meta.shards_metadata:
remote_global_rank, device = _parse_and_validate_remote_device(
process_group, shard_meta.placement
)
if current_rank == src_rank:
# Reshape to get shard for this rank and we don't want autograd
# recording here for the narrow op and 'local_shard' should be a
# leaf variable in the autograd graph.
narrowed_tensor = narrow_tensor(tensor, shard_meta)
if shard_meta.shard_sizes[self.dim] < split_size: # type: ignore[index]
# for the last shard that might be smaller to other shards
# resize the narrowed tensor to the same size and use it for
# the scatter collective as dist.scatter requires same size
# inputs on every rank
tensor_to_scatter = (
narrowed_tensor.detach().clone().resize_(scatter_shape)
)
else:
tensor_to_scatter = narrowed_tensor.detach().clone(
memory_format=torch.contiguous_format
)
tensors_to_scatter[
# pyrefly: ignore [bad-argument-type]
dist.get_group_rank(process_group, remote_global_rank)
] = tensor_to_scatter
if current_global_rank == remote_global_rank:
local_tensor = torch.empty(
scatter_shape,
dtype=tensor.dtype,
layout=tensor.layout,
device=device,
)
local_metadata = shard_meta
# each rank should have local_tensor and local_metadata initialized if we build
# the metadata list in a correct way.
assert local_tensor is not None
assert local_metadata is not None
# Scatter the shards to all ranks in the pg
# scatter takes the global rank as ``src``
src_for_scatter = src_rank
if (
process_group is not None
and process_group is not distributed_c10d._get_default_group()
):
src_for_scatter = distributed_c10d.get_global_rank(
process_group, src_for_scatter
)
tensors_to_scatter_: Optional[list[torch.Tensor]] = None
if current_rank == src_rank:
tensors_to_scatter_ = []
for t in tensors_to_scatter:
assert isinstance(t, torch.Tensor)
tensors_to_scatter_.append(t)
dist.scatter(
local_tensor,
scatter_list=tensors_to_scatter_,
src=src_for_scatter,
group=process_group,
)
if list(local_tensor.size()) != local_metadata.shard_sizes:
# detach again after receiving to ensure local shards remain a leaf node
local_tensor = local_tensor.resize_(local_metadata.shard_sizes).detach()
# Sync requires_grad to local_shard.
local_tensor.requires_grad = tensor.requires_grad
local_shards.append(Shard(tensor=local_tensor, metadata=local_metadata))
st = ShardedTensor._init_from_local_shards_and_global_metadata(
local_shards, tensor_meta, process_group=process_group
)
# Manually set sharding_spec
st._sharding_spec = self
return st
| ChunkShardingSpec |
python | streamlit__streamlit | lib/streamlit/elements/lib/column_types.py | {
"start": 3151,
"end": 3283
} | class ____(TypedDict):
type: Literal["checkbox"]
SelectboxOptionValue: TypeAlias = str | int | float | bool
| CheckboxColumnConfig |
python | pytorch__pytorch | torch/fx/experimental/migrate_gradual_types/constraint.py | {
"start": 710,
"end": 1175
} | class ____(Constraint):
def __init__(self, disjuncts):
"""
:param disjuncts: Disjunction of constraints
"""
self.disjuncts = disjuncts
def __eq__(self, other):
if isinstance(other, Disj):
return (
self.disjuncts == other.disjuncts and self.disjuncts == other.disjuncts
)
else:
return False
def __repr__(self):
return f"Or({self.disjuncts})"
| Disj |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_experiment_service.py | {
"start": 3426,
"end": 5132
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_no_default_project_id
):
self.hook = ExperimentHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(EXPERIMENT_SERVICE_STRING.format("aiplatform.init"))
def test_create_experiment(self, mock_init) -> None:
self.hook.create_experiment(
project_id=TEST_PROJECT_ID,
location=TEST_REGION,
experiment_name=TEST_EXPERIMENT_NAME,
experiment_description=TEST_EXPERIMENT_DESCRIPTION,
experiment_tensorboard=TEST_TENSORBOARD,
)
mock_init.assert_called_with(
project=TEST_PROJECT_ID,
location=TEST_REGION,
experiment=TEST_EXPERIMENT_NAME,
experiment_description=TEST_EXPERIMENT_DESCRIPTION,
experiment_tensorboard=TEST_TENSORBOARD,
)
@mock.patch(EXPERIMENT_SERVICE_STRING.format("aiplatform.Experiment"))
def test_delete_experiment(self, mock_experiment) -> None:
self.hook.delete_experiment(
project_id=TEST_PROJECT_ID,
location=TEST_REGION,
experiment_name=TEST_EXPERIMENT_NAME,
delete_backing_tensorboard_runs=TEST_DELETE_BACKING_TENSORBOARD_RUNS,
)
mock_experiment.assert_called_with(
project=TEST_PROJECT_ID,
location=TEST_REGION,
experiment_name=TEST_EXPERIMENT_NAME,
)
mock_experiment.return_value.delete.assert_called_with(
delete_backing_tensorboard_runs=TEST_DELETE_BACKING_TENSORBOARD_RUNS
)
| TestExperimentWithoutDefaultProjectIdHook |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.