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 | numpy__numpy | numpy/lib/tests/test_function_base.py | {
"start": 1505,
"end": 3789
} | class ____:
def test_basic(self):
assert_raises(ValueError, rot90, np.ones(4))
assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(0, 1, 2))
assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(0, 2))
assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(1, 1))
assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(-2, 1))
a = [[0, 1, 2],
[3, 4, 5]]
b1 = [[2, 5],
[1, 4],
[0, 3]]
b2 = [[5, 4, 3],
[2, 1, 0]]
b3 = [[3, 0],
[4, 1],
[5, 2]]
b4 = [[0, 1, 2],
[3, 4, 5]]
for k in range(-3, 13, 4):
assert_equal(rot90(a, k=k), b1)
for k in range(-2, 13, 4):
assert_equal(rot90(a, k=k), b2)
for k in range(-1, 13, 4):
assert_equal(rot90(a, k=k), b3)
for k in range(0, 13, 4):
assert_equal(rot90(a, k=k), b4)
assert_equal(rot90(rot90(a, axes=(0, 1)), axes=(1, 0)), a)
assert_equal(rot90(a, k=1, axes=(1, 0)), rot90(a, k=-1, axes=(0, 1)))
def test_axes(self):
a = np.ones((50, 40, 3))
assert_equal(rot90(a).shape, (40, 50, 3))
assert_equal(rot90(a, axes=(0, 2)), rot90(a, axes=(0, -1)))
assert_equal(rot90(a, axes=(1, 2)), rot90(a, axes=(-2, -1)))
def test_rotation_axes(self):
a = np.arange(8).reshape((2, 2, 2))
a_rot90_01 = [[[2, 3],
[6, 7]],
[[0, 1],
[4, 5]]]
a_rot90_12 = [[[1, 3],
[0, 2]],
[[5, 7],
[4, 6]]]
a_rot90_20 = [[[4, 0],
[6, 2]],
[[5, 1],
[7, 3]]]
a_rot90_10 = [[[4, 5],
[0, 1]],
[[6, 7],
[2, 3]]]
assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)
assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)
assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)
for k in range(1, 5):
assert_equal(rot90(a, k=k, axes=(2, 0)),
rot90(a_rot90_20, k=k - 1, axes=(2, 0)))
| TestRot90 |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_tagkey_details.py | {
"start": 1261,
"end": 3349
} | class ____(APITestCase):
@mock.patch("sentry.eventstream.backend")
def test_simple(self, mock_eventstream: mock.MagicMock) -> None:
key = "foo"
val = "bar"
project = self.create_project()
self.store_event(
data={"tags": {key: val}, "timestamp": before_now(seconds=1).isoformat()},
project_id=project.id,
)
self.login_as(user=self.user)
eventstream_state = object()
mock_eventstream.start_delete_tag = mock.Mock(return_value=eventstream_state)
url = reverse(
"sentry-api-0-project-tagkey-details",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"key": key,
},
)
response = self.client.delete(url)
assert response.status_code == 204
mock_eventstream.start_delete_tag.assert_called_once_with(project.id, "foo")
mock_eventstream.end_delete_tag.assert_called_once_with(eventstream_state)
def test_protected(self) -> None:
project = self.create_project()
self.store_event(
data={"environment": "prod", "timestamp": before_now(seconds=1).isoformat()},
project_id=project.id,
)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-project-tagkey-details",
kwargs={
"organization_id_or_slug": project.organization.slug,
"project_id_or_slug": project.slug,
"key": "environment",
},
)
response = self.client.delete(url)
assert response.status_code == 403
assert (
tagstore.backend.get_tag_key(
project.id,
None,
"environment",
status=TagKeyStatus.ACTIVE, # environment_id
tenant_ids={"referrer": "test_tagstore", "organization_id": 123},
).status
== TagKeyStatus.ACTIVE
)
| ProjectTagKeyDeleteTest |
python | doocs__leetcode | solution/0400-0499/0465.Optimal Account Balancing/Solution.py | {
"start": 0,
"end": 692
} | class ____:
def minTransfers(self, transactions: List[List[int]]) -> int:
g = defaultdict(int)
for f, t, x in transactions:
g[f] -= x
g[t] += x
nums = [x for x in g.values() if x]
m = len(nums)
f = [inf] * (1 << m)
f[0] = 0
for i in range(1, 1 << m):
s = 0
for j, x in enumerate(nums):
if i >> j & 1:
s += x
if s == 0:
f[i] = i.bit_count() - 1
j = (i - 1) & i
while j > 0:
f[i] = min(f[i], f[j] + f[i ^ j])
j = (j - 1) & i
return f[-1]
| Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/remote_origin.py | {
"start": 5572,
"end": 7479
} | class ____(IHaveNew, LegacyNamedTupleMixin, CodeLocationOrigin):
loadable_target_origin: LoadableTargetOrigin # pyright: ignore[reportIncompatibleMethodOverride]
location_name: str # pyright: ignore[reportIncompatibleMethodOverride]
container_image: Optional[str]
entry_point: Sequence[str]
container_context: Optional[Mapping[str, Any]]
"""Identifies a repository location constructed in the same process. Primarily
used in tests, since Dagster system processes like the webserver and daemon do not
load user code in the same process.
"""
def __new__(
cls,
loadable_target_origin: LoadableTargetOrigin,
container_image: Optional[str] = None,
entry_point: Optional[Sequence[str]] = None,
container_context=None,
location_name: Optional[str] = None,
):
return super().__new__(
cls,
loadable_target_origin=loadable_target_origin,
container_image=container_image,
entry_point=entry_point if entry_point else DEFAULT_DAGSTER_ENTRY_POINT,
container_context=container_context,
location_name=location_name if location_name else IN_PROCESS_NAME,
)
@property
def is_reload_supported(self) -> bool:
return False
def get_display_metadata(self) -> Mapping[str, Any]:
return {}
def create_location(self, instance: "DagsterInstance") -> "InProcessCodeLocation":
from dagster._core.remote_representation.code_location import InProcessCodeLocation
return InProcessCodeLocation(self, instance=instance)
def reload_location(self, instance: "DagsterInstance") -> "InProcessCodeLocation":
raise NotImplementedError
# Different storage name for backcompat
@whitelist_for_serdes(storage_name="ManagedGrpcPythonEnvRepositoryLocationOrigin")
@record_custom
| InProcessCodeLocationOrigin |
python | pytorch__pytorch | torch/_inductor/codegen/mps.py | {
"start": 1886,
"end": 5881
} | class ____(ExprPrinter_):
"""Converts sympy expression to Metal code snippet"""
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
x, div = expr.args
x = self.doprint(x)
div = self.doprint(div)
if expr.is_integer:
return f"c10::metal::floor_divide({x}, {div})"
return f"metal::floor({x}) / ({div})"
def _print_ModularIndexing(self, expr: sympy.Expr) -> str:
x, div, mod = expr.args
x = self.doprint(x)
if div != 1:
div = self.doprint(div)
if expr.is_integer:
x = f"({x}) / ({div})"
else:
x = f"metal::floor({x}) / ({div})"
mod = self.doprint(mod)
return f"({x}) % ({mod})"
def _print_Min(self, expr: sympy.Expr) -> str:
if len(expr.args) != 2:
raise RuntimeError("metal::min only supported for 2 args")
a, b = map(self._print, expr.args)
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
return f"metal::min({typecast_a}, {typecast_b})"
def _print_Max(self, expr: sympy.Expr) -> str:
if len(expr.args) != 2:
raise RuntimeError("metal::max only supported for 2 args")
a, b = map(self._print, expr.args)
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
return f"metal::max({typecast_a}, {typecast_b})"
def _print_Abs(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return f"metal::abs({self._print(expr.args[0])})"
def _print_RoundToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
return f"static_cast<long>(metal::rint({self._print(expr.args[0])}))"
def _print_RoundDecimal(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 2
number, ndigits = expr.args
if number.is_integer:
# ndigits < 0 should have been filtered by the sympy function
assert ndigits < 0
raise ValueError(
f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}."
)
number_str = self.parenthesize(number, PRECEDENCE["Mul"])
return f"static_cast<float>(metal::rint(1e{ndigits} * {number_str}) * 1e{-ndigits})"
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
lhs, rhs = expr.args
# TODO: This is only accurate up to 2**23
return f"static_cast<float>({self._print(lhs)}) / static_cast<float>({self._print(rhs)})"
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 2
x, y = map(self.doprint, expr.args)
return f"metal::pow(static_cast<float>({x}), static_cast<float>({y}))"
def _print_ToFloat(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
x = self.doprint(expr.args[0])
return f"static_cast<float>({x})"
def _print_Float(self, expr: sympy.Expr) -> str:
if expr.is_integer:
# sympy considers 0.0 to be integer, but Metal doesn't.
# this workaround prints the float as an integer
# xref: https://github.com/sympy/sympy/issues/26620
return str(int(expr))
else:
return str(expr)
def _print_FloorToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
x = self.doprint(expr.args[0])
return f"static_cast<int>(metal::floor(static_cast<float>({x})))"
_print_floor = _print_FloorToInt
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
x = self.doprint(expr.args[0])
return f"static_cast<int>(metal::trunc({x}))"
def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str:
assert len(expr.args) == 1
x = self.doprint(expr.args[0])
return f"metal::log2({x})"
| MetalExprPrinter |
python | numba__llvmlite | llvmlite/binding/module.py | {
"start": 7521,
"end": 11174
} | class ____(_Iterator):
kind = 'type'
def _dispose(self):
self._capi.LLVMPY_DisposeTypesIter(self)
def __next__(self):
vp = self._next()
if vp:
return TypeRef(vp)
else:
raise StopIteration
def _next(self):
return ffi.lib.LLVMPY_TypesIterNext(self)
next = __next__
# =============================================================================
# Set function FFI
ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef,
c_char_p,
POINTER(c_char_p)]
ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef
ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef,
c_char_p, c_size_t,
POINTER(c_char_p)]
ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef
ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef,
POINTER(c_char_p)]
ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef,
POINTER(c_char_p),
POINTER(c_size_t)]
ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef,
c_char_p]
ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef
ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef,
POINTER(c_char_p)]
ffi.lib.LLVMPY_VerifyModule.restype = c_bool
ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)]
ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p]
ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)]
ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p]
ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p]
ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef
ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p]
ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef
ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator
ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator]
ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator]
ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef
ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator
ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator
ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator]
ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator]
ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator]
ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef
ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator]
ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef
ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef
ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_GetModuleName.restype = c_char_p
ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p]
ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef]
ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p
| _TypesIterator |
python | Lightning-AI__lightning | tests/parity_pytorch/test_sync_batchnorm_parity.py | {
"start": 785,
"end": 4395
} | class ____(LightningModule):
def __init__(self, batch_size):
super().__init__()
self.batch_size = batch_size
self.bn_layer = nn.BatchNorm1d(1)
self.linear = nn.Linear(1, 10)
self.bn_outputs = []
def on_train_start(self) -> None:
assert isinstance(self.bn_layer, torch.nn.modules.batchnorm.SyncBatchNorm)
def training_step(self, batch, batch_idx):
with torch.no_grad():
out_bn = self.bn_layer(batch)
self.bn_outputs.append(out_bn.detach())
out = self.linear(out_bn)
return out.sum()
def configure_optimizers(self):
return torch.optim.SGD(self.parameters(), lr=0.02)
def train_dataloader(self):
dataset = torch.arange(64, dtype=torch.float).view(-1, 1)
# we need to set a distributed sampler ourselves to force shuffle=False
sampler = DistributedSampler(
dataset, num_replicas=self.trainer.world_size, rank=self.trainer.global_rank, shuffle=False
)
return DataLoader(dataset, sampler=sampler, batch_size=self.batch_size)
@RunIf(min_cuda_gpus=2, standalone=True)
def test_sync_batchnorm_parity(tmpdir):
"""Test parity between 1) Training a synced batch-norm layer on 2 GPUs with batch size B per device 2) Training a
batch-norm layer on CPU with twice the batch size."""
seed_everything(3)
# 2 GPUS, batch size = 4 per GPU => total batch size = 8
model = SyncBNModule(batch_size=4)
trainer = Trainer(
default_root_dir=tmpdir,
accelerator="gpu",
strategy="ddp_find_unused_parameters_true",
devices=2,
max_steps=3,
sync_batchnorm=True,
num_sanity_val_steps=0,
use_distributed_sampler=False,
deterministic=True,
benchmark=False,
enable_progress_bar=False,
enable_model_summary=False,
)
trainer.fit(model)
# the strategy is responsible for tearing down the batch norm wrappers
assert not isinstance(model.bn_layer, torch.nn.modules.batchnorm.SyncBatchNorm)
assert isinstance(model.bn_layer, torch.nn.modules.batchnorm._BatchNorm)
bn_outputs = torch.stack(model.bn_outputs) # 2 x 4 x 1 on each GPU
bn_outputs_multi_device = trainer.strategy.all_gather(bn_outputs).cpu() # 2 x 2 x 4 x 1
if trainer.global_rank == 0:
# pretend we are now training on a single GPU/process
# (we are reusing the rank 0 from the previous training)
# 1 GPU, batch size = 8 => total batch size = 8
bn_outputs_single_device = _train_single_process_sync_batchnorm(batch_size=8, num_steps=3)
gpu0_outputs = bn_outputs_multi_device[0] # 2 x 4 x 1
gpu1_outputs = bn_outputs_multi_device[1] # 2 x 4 x 1
slice0 = bn_outputs_single_device[:, 0::2]
slice1 = bn_outputs_single_device[:, 1::2]
assert torch.allclose(gpu0_outputs, slice0)
assert torch.allclose(gpu1_outputs, slice1)
def _train_single_process_sync_batchnorm(batch_size, num_steps):
seed_everything(3)
dataset = torch.arange(64, dtype=torch.float).view(-1, 1)
train_dataloader = DataLoader(dataset, batch_size=batch_size)
model = SyncBNModule(batch_size=batch_size)
optimizer = model.configure_optimizers()
model.train()
for batch_idx, batch in enumerate(train_dataloader):
optimizer.zero_grad()
loss = model.training_step(batch, batch)
loss.backward()
optimizer.step()
if batch_idx == num_steps - 1:
break
return torch.stack(model.bn_outputs) # num_steps x batch_size x 1
| SyncBNModule |
python | kamyu104__LeetCode-Solutions | Python/convert-binary-number-in-a-linked-list-to-integer.py | {
"start": 165,
"end": 433
} | class ____(object):
def getDecimalValue(self, head):
"""
:type head: ListNode
:rtype: int
"""
result = 0
while head:
result = result*2 + head.val
head = head.next
return result
| Solution |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 271917,
"end": 273944
} | class ____:
def test_basic(self):
dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger']
dt_complex = np.typecodes['Complex']
# test real
a = np.eye(3)
for dt in dt_numeric + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test complex
a = np.eye(3) * 1j
for dt in dt_complex + 'O':
b = a.astype(dt)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), 3)
# test boolean
b = np.eye(3, dtype=bool)
res = np.vdot(b, b)
assert_(np.isscalar(res))
assert_equal(np.vdot(b, b), True)
def test_vdot_array_order(self):
a = np.array([[1, 2], [3, 4]], order='C')
b = np.array([[1, 2], [3, 4]], order='F')
res = np.vdot(a, a)
# integer arrays are exact
assert_equal(np.vdot(a, b), res)
assert_equal(np.vdot(b, a), res)
assert_equal(np.vdot(b, b), res)
def test_vdot_uncontiguous(self):
for size in [2, 1000]:
# Different sizes match different branches in vdot.
a = np.zeros((size, 2, 2))
b = np.zeros((size, 2, 2))
a[:, 0, 0] = np.arange(size)
b[:, 0, 0] = np.arange(size) + 1
# Make a and b uncontiguous:
a = a[..., 0]
b = b[..., 0]
assert_equal(np.vdot(a, b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy()),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy(), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a.copy('F'), b),
np.vdot(a.flatten(), b.flatten()))
assert_equal(np.vdot(a, b.copy('F')),
np.vdot(a.flatten(), b.flatten()))
| TestVdot |
python | pytorch__pytorch | test/inductor/test_mix_order_reduction.py | {
"start": 16516,
"end": 16644
} | class ____(MixOrderReductionTest):
pass
if __name__ == "__main__":
if HAS_GPU:
run_tests()
| NoMixOrderReductionTest |
python | getsentry__sentry | src/sentry/models/groupmeta.py | {
"start": 2801,
"end": 3383
} | class ____(Model):
"""
Arbitrary key/value store for Groups.
Generally useful for things like storing metadata
provided by plugins.
"""
__relocation_scope__ = RelocationScope.Excluded
group = FlexibleForeignKey("sentry.Group")
key = models.CharField(max_length=64)
value = models.TextField()
objects: ClassVar[GroupMetaManager] = GroupMetaManager()
class Meta:
app_label = "sentry"
db_table = "sentry_groupmeta"
unique_together = (("group", "key"),)
__repr__ = sane_repr("group_id", "key", "value")
| GroupMeta |
python | huggingface__transformers | src/transformers/models/qwen3/modeling_qwen3.py | {
"start": 23493,
"end": 23592
} | class ____(GenericForTokenClassification, Qwen3PreTrainedModel):
pass
| Qwen3ForTokenClassification |
python | pytorch__pytorch | torch/distributed/distributed_c10d.py | {
"start": 19863,
"end": 23843
} | class ____:
"""
Container class for c10d process group state.
This is used during registration and lookup of PG state.
.. warning:: This is an experimental API intended to expose the inner workings
of c10d and is subject to change..
"""
def __init__(self) -> None:
self._default_pg = None
self._pg_coalesce_state: dict[ProcessGroup, list[_CollOp]] = {}
@property
def default_pg(self) -> ProcessGroup | None:
"""
Process group that includes all ranks of the cluster.
This default ProcessGroup is used by c10d APIs when a ProcessGroup is needed
but None is provided.
"""
return self._default_pg
@default_pg.setter
def default_pg(self, value) -> None:
self._default_pg = value
@property
def pg_map(self) -> dict[ProcessGroup, tuple[str, Store]]:
"""
Provide Mapping from ProcessGroup to backend name and store.
For NCCL and GLOO pg, it is a map from ProcessGroup to (Backend, Store)
For MPI pg, it is a map from ProcessGroup to (Backend, None)
TODO don't expose the map, expose fine grained ops
"""
global _pg_map
return _pg_map
@property
def pg_names(self) -> dict[ProcessGroup, str]:
"""
Process group's names, map from ProcessGroup to str.
TODO don't expose the map, expose fine grained ops
"""
global _pg_names
return _pg_names
@property
def pg_group_ranks(self) -> dict[ProcessGroup, dict[int, int]]:
"""
Process group's global rank to local rank mapping.
TODO don't expose the map, expose fine grained ops
"""
global _pg_group_ranks
return _pg_group_ranks
@property
def pg_backend_config(self) -> dict[ProcessGroup, str]:
"""
Process group's backend config.
TODO don't expose the map, expose fine grained ops
"""
global _pg_backend_config
return _pg_backend_config
@property
def group_count(self) -> int:
"""
Process group count for default naming.
TODO don't expose group_count, use something else instead
"""
global _group_count
return _group_count
@group_count.setter
def group_count(self, value: int) -> None:
"""Use to compute the name of ProcessGroups when using global synchronization."""
global _group_count
_group_count = value
@property
def tags_to_pg(self) -> dict[str, list[ProcessGroup]]:
global _tags_to_pg
return _tags_to_pg
@property
def pg_to_tag(self) -> dict[ProcessGroup, str]:
global _pg_to_tag
return _pg_to_tag
@property
def pg_coalesce_state(self) -> dict[ProcessGroup, list[_CollOp]]:
return self._pg_coalesce_state
@property
def pg_config_info(self) -> list[dict[str, Any]]:
"""
Return a list of dict with process groups and backends.
Along with their unique IDs and configurations (types and ranks).
"""
config_info: list[dict[str, Any]] = []
default_pg_size = _get_group_size(None)
for pg in self.pg_map:
ranks = self.pg_group_ranks[pg]
config_info.append(
{
"pg_name": self.pg_names[pg],
"pg_desc": pg.group_desc,
"backend_config": self.pg_backend_config[pg],
"ranks": (
list(ranks.keys()) if len(ranks) != default_pg_size else []
), # 'ranks' is an empty list when all ranks are involved in a pg
"group_size": len(ranks),
"group_count": self.group_count,
}
)
return config_info
_world = _World()
"""Holds the singleton instance of ``_World`` used by c10. Experimental extension point to override it"""
| _World |
python | great-expectations__great_expectations | great_expectations/metrics/metric_results.py | {
"start": 1216,
"end": 2074
} | class ____(MetricResult[Union[pd.Series, "pyspark.sql.Column", "BinaryExpression"]]):
@classmethod
def validate_value_type(cls, value):
if isinstance(value, pd.Series):
return value
try:
from great_expectations.compatibility.pyspark import pyspark
if isinstance(value, pyspark.sql.Column):
return value
except (ImportError, AttributeError):
pass
try:
from great_expectations.compatibility.sqlalchemy import BinaryExpression
if isinstance(value, BinaryExpression):
return value
except (ImportError, AttributeError):
pass
raise ConditionValuesValueError(type(value))
@classmethod
@override
def __get_validators__(cls):
yield cls.validate_value_type
| ConditionValues |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchvision_models.py | {
"start": 30767,
"end": 35025
} | class ____(nn.Module):
"""This class computes an assignment between the targets and the predictions of the network
For efficiency reasons, the targets don't include the no_object. Because of this, in general,
there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predictions,
while the others are un-matched (and thus treated as non-objects).
"""
def __init__(
self, cost_class: float = 1, cost_bbox: float = 1, cost_giou: float = 1
):
"""Creates the matcher
Params:
cost_class: This is the relative weight of the classification error in the matching cost
cost_bbox: This is the relative weight of the L1 error of the bounding box coordinates in the matching cost
cost_giou: This is the relative weight of the giou loss of the bounding box in the matching cost
"""
super().__init__()
self.cost_class = cost_class
self.cost_bbox = cost_bbox
self.cost_giou = cost_giou
assert cost_class != 0 or cost_bbox != 0 or cost_giou != 0, (
"all costs can't be 0"
)
@torch.no_grad()
def forward(self, outputs, targets):
"""Performs the matching
Params:
outputs: This is a dict that contains at least these entries:
"pred_logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
"pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates
targets: This is a list of targets (len(targets) = batch_size), where each target is a dict containing:
"labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of ground-truth
objects in the target) containing the class labels
"boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates
Returns:
A list of size batch_size, containing tuples of (index_i, index_j) where:
- index_i is the indices of the selected predictions (in order)
- index_j is the indices of the corresponding selected targets (in order)
For each batch element, it holds:
len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
"""
bs, num_queries = outputs["pred_logits"].shape[:2]
# We flatten to compute the cost matrices in a batch
out_prob = (
outputs["pred_logits"].flatten(0, 1).softmax(-1)
) # [batch_size * num_queries, num_classes]
out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
# Also concat the target labels and boxes
tgt_ids = torch.cat([v["labels"] for v in targets])
tgt_bbox = torch.cat([v["boxes"] for v in targets])
# Compute the classification cost. Contrary to the loss, we don't use the NLL,
# but approximate it in 1 - proba[target class].
# The 1 is a constant that doesn't change the matching, it can be omitted.
cost_class = -out_prob[:, tgt_ids]
# Compute the L1 cost between boxes
cost_bbox = torch.cdist(out_bbox, tgt_bbox, p=1)
# Compute the giou cost between boxes
cost_giou = -generalized_box_iou(
box_cxcywh_to_xyxy(out_bbox), box_cxcywh_to_xyxy(tgt_bbox)
)
# Final cost matrix
C = (
self.cost_bbox * cost_bbox
+ self.cost_class * cost_class
+ self.cost_giou * cost_giou
)
C = C.view(bs, num_queries, -1).cpu()
sizes = [len(v["boxes"]) for v in targets]
if not scipy_available:
raise RuntimeError(
"The 'detr' model requires scipy to run. Please make sure you have it installed"
" if you enable the 'detr' model."
)
indices = [
linear_sum_assignment(c[i]) for i, c in enumerate(C.split(sizes, -1))
]
return [
(
torch.as_tensor(i, dtype=torch.int64),
torch.as_tensor(j, dtype=torch.int64),
)
for i, j in indices
]
| HungarianMatcher |
python | bokeh__bokeh | src/bokeh/command/subcommand.py | {
"start": 2391,
"end": 5727
} | class ____(metaclass=ABCMeta):
''' Abstract base class for subcommands
Subclasses should implement an ``invoke(self, args)`` method that accepts
a set of argparse processed arguments as input.
Subclasses should also define the following class attributes:
* ``name`` a name for this subcommand
* ``help`` a help string for argparse to use for this subcommand
* ``args`` the parameters to pass to ``parser.add_argument``
The format of the ``args`` should be a sequence of tuples of the form:
.. code-block:: python
('argname', Argument(
metavar='ARGNAME',
nargs='+',
))
Example:
A simple subcommand "foo" might look like this:
.. code-block:: python
class Foo(Subcommand):
name = "foo"
help = "performs the Foo action"
args = (
('--yell', Argument(
action='store_true',
help="Make it loud",
)),
)
def invoke(self, args):
if args.yell:
print("FOO!")
else:
print("foo")
Then executing ``bokeh foo --yell`` would print ``FOO!`` at the console.
'''
name: ClassVar[str]
help: ClassVar[str]
args: ClassVar[Args] = ()
def __init__(self, parser: ArgumentParser) -> None:
''' Initialize the subcommand with its parser
Args:
parser (Parser) : an Argparse ``Parser`` instance to configure
with the args for this subcommand.
This method will automatically add all the arguments described in
``self.args``. Subclasses can perform any additional customizations
on ``self.parser``.
'''
self.parser = parser
for arg in self.args:
flags, spec = arg
if not isinstance(flags, tuple):
flags = (flags,)
if not isinstance(spec, dict):
kwargs = dict(entries(spec))
else:
# NOTE: allow dict for run time backwards compatibility, but don't include in types
kwargs = spec
self.parser.add_argument(*flags, **kwargs)
@abstractmethod
def invoke(self, args: Namespace) -> bool | None:
''' Takes over main program flow to perform the subcommand.
*This method must be implemented by subclasses.*
subclassed overwritten methods return different types:
bool: Build
None: FileOutput (subclassed by HTML, SVG and JSON. PNG overwrites FileOutput.invoke method), Info, Init, \
Sampledata, Secret, Serve, Static
Args:
args (argparse.Namespace) : command line arguments for the subcommand to parse
Raises:
NotImplementedError
'''
raise NotImplementedError("implement invoke()")
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Subcommand |
python | coleifer__peewee | playhouse/shortcuts.py | {
"start": 7246,
"end": 11059
} | class ____(object):
"""
Mixin class that attempts to automatically reconnect to the database under
certain error conditions.
For example, MySQL servers will typically close connections that are idle
for 28800 seconds ("wait_timeout" setting). If your application makes use
of long-lived connections, you may find your connections are closed after
a period of no activity. This mixin will attempt to reconnect automatically
when these errors occur.
This mixin class probably should not be used with Postgres (unless you
REALLY know what you are doing) and definitely has no business being used
with Sqlite. If you wish to use with Postgres, you will need to adapt the
`reconnect_errors` attribute to something appropriate for Postgres.
"""
reconnect_errors = (
# Error class, error message fragment (or empty string for all).
(OperationalError, '2006'), # MySQL server has gone away.
(OperationalError, '2013'), # Lost connection to MySQL server.
(OperationalError, '2014'), # Commands out of sync.
(OperationalError, '4031'), # Client interaction timeout.
# mysql-connector raises a slightly different error when an idle
# connection is terminated by the server. This is equivalent to 2013.
(OperationalError, 'MySQL Connection not available.'),
# Postgres error examples:
#(OperationalError, 'terminat'),
#(InterfaceError, 'connection already closed'),
)
def __init__(self, *args, **kwargs):
super(ReconnectMixin, self).__init__(*args, **kwargs)
# Normalize the reconnect errors to a more efficient data-structure.
self._reconnect_errors = {}
for exc_class, err_fragment in self.reconnect_errors:
self._reconnect_errors.setdefault(exc_class, [])
self._reconnect_errors[exc_class].append(err_fragment.lower())
def execute_sql(self, sql, params=None, commit=None):
if commit is not None:
__deprecated__('"commit" has been deprecated and is a no-op.')
return self._reconnect(super(ReconnectMixin, self).execute_sql,
sql, params)
def begin(self, *args, **kwargs):
return self._reconnect(super(ReconnectMixin, self).begin,
*args, **kwargs)
def _reconnect(self, func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
# If we are in a transaction, do not reconnect silently as
# any changes could be lost.
if self.in_transaction():
raise exc
exc_class = type(exc)
if exc_class not in self._reconnect_errors:
raise exc
exc_repr = str(exc).lower()
for err_fragment in self._reconnect_errors[exc_class]:
if err_fragment in exc_repr:
break
else:
raise exc
if not self.is_closed():
self.close()
self.connect()
return func(*args, **kwargs)
def resolve_multimodel_query(query, key='_model_identifier'):
mapping = {}
accum = [query]
while accum:
curr = accum.pop()
if isinstance(curr, CompoundSelectQuery):
accum.extend((curr.lhs, curr.rhs))
continue
model_class = curr.model
name = model_class._meta.table_name
mapping[name] = model_class
curr._returning.append(Value(name).alias(key))
def wrapped_iterator():
for row in query.dicts().iterator():
identifier = row.pop(key)
model = mapping[identifier]
yield model(**row)
return wrapped_iterator()
| ReconnectMixin |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 19086,
"end": 19951
} | class ____:
params = [True, False]
param_names = ["monotonic"]
def setup(self, monotonic):
N = 10000
K = 10
df = DataFrame(
{
"key1": Index([f"i-{i}" for i in range(N)], dtype=object).values.repeat(
K
),
"key2": Index([f"i-{i}" for i in range(N)], dtype=object).values.repeat(
K
),
"value": np.random.randn(N * K),
}
)
if monotonic:
df = df.sort_values(["key1", "key2"])
self.df_by_columns = df
self.df_by_index = df.set_index(["key1", "key2"])
def time_sort_values(self, monotonic):
self.df_by_columns.sort_values(by=["key1", "key2"])
def time_sort_index(self, monotonic):
self.df_by_index.sort_index()
| SortMultiKey |
python | pydantic__pydantic | tests/benchmarks/test_discriminated_unions.py | {
"start": 324,
"end": 1300
} | class ____(BaseModel):
state_type: Literal['leaf']
AnyState = Annotated[Union[NestedState, LoopState, LeafState], Field(discriminator='state_type')]
@pytest.mark.benchmark
def test_schema_build(benchmark) -> None:
@benchmark
def run():
adapter = TypeAdapter(AnyState)
assert adapter.core_schema['schema']['type'] == 'tagged-union'
any_state_adapter = TypeAdapter(AnyState)
def build_nested_state(n):
if n <= 0:
return {'state_type': 'leaf'}
else:
return {'state_type': 'loop', 'substate': {'state_type': 'nested', 'substate': build_nested_state(n - 1)}}
@pytest.mark.benchmark
def test_efficiency_with_highly_nested_examples(benchmark) -> None:
# can go much higher, but we keep it reasonably low here for a proof of concept
@benchmark
def run():
for i in range(1, 12):
very_nested_input = build_nested_state(i)
any_state_adapter.validate_python(very_nested_input)
| LeafState |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 12566,
"end": 12964
} | class ____(GroupType):
type_id = 1007
slug = "performance_consecutive_db_queries"
description = "Consecutive DB Queries"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.DB_QUERY.value
noise_config = NoiseConfig(ignore_limit=15)
default_priority = PriorityLevel.LOW
released = True
@dataclass(frozen=True)
| PerformanceConsecutiveDBQueriesGroupType |
python | walkccc__LeetCode | solutions/801. Minimum Swaps To Make Sequences Increasing/801.py | {
"start": 0,
"end": 566
} | class ____:
def minSwap(self, nums1: list[int], nums2: list[int]) -> int:
keepAt = [math.inf] * len(nums1)
swapAt = [math.inf] * len(nums1)
keepAt[0] = 0
swapAt[0] = 1
for i in range(1, len(nums1)):
if nums1[i] > nums1[i - 1] and nums2[i] > nums2[i - 1]:
keepAt[i] = keepAt[i - 1]
swapAt[i] = swapAt[i - 1] + 1
if nums1[i] > nums2[i - 1] and nums2[i] > nums1[i - 1]:
keepAt[i] = min(keepAt[i], swapAt[i - 1])
swapAt[i] = min(swapAt[i], keepAt[i - 1] + 1)
return min(keepAt[-1], swapAt[-1])
| Solution |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/asset_factory/asset_factory_component.py | {
"start": 105,
"end": 304
} | class ____(dg.Model):
bucket: str = dg.Field
source_object: str = dg.Field
target_object: str = dg.Field
sql: str = dg.Field
# end_etl_job_model
# start_asset_factory_component
| EtlJob |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 4615,
"end": 5430
} | class ____(BaseModel):
"""Common parameters used for chat completions and completion endpoints."""
temperature: float = Field(0.0, ge=0, le=2)
n: int = Field(1, ge=1)
stop: list[str] | None = Field(None, min_length=1)
max_tokens: int | None = Field(None, ge=1)
stream: bool | None = None
stream_options: dict[str, Any] | None = None
model: str | None = None
# NB: For interface constructs that rely on other BaseModel implementations, in
# pydantic 1 the **order** in which classes are defined in this module is absolutely
# critical to prevent ForwardRef errors. Pydantic 2 does not have this limitation.
# To maintain compatibility with Pydantic 1, ensure that all classes that are defined in
# this file have dependencies defined higher than the line of usage.
| BaseRequestPayload |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 1725,
"end": 1839
} | class ____[*Ts = Unpack[tuple[int, ...]]]: ...
# This should generate an error because T1 isn't legal here.
| ClassTs8 |
python | tensorflow__tensorflow | tensorflow/python/distribute/checkpoint_utils_test.py | {
"start": 2062,
"end": 5249
} | class ____(
test.TestCase, parameterized.TestCase):
def _get_test_object(self):
checkpoint_dir = self.get_temp_dir()
with self.cached_session() as session:
v1, v2 = _create_checkpoints(session, checkpoint_dir)
return checkpoint_dir, v1, v2
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.default_strategy,
strategy_combinations.one_device_strategy,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.mirrored_strategy_with_two_gpus,
strategy_combinations
.mirrored_strategy_with_two_gpus_no_merge_call,
],
in_replica_mode=[True, False],
mode=["graph"]))
def testInitFromCheckpoint(self, distribution, in_replica_mode):
checkpoint_dir, v1_value, v2_value = self._get_test_object()
def init_and_verify(g):
v1 = variable_scope.get_variable("new_var1", [1, 10])
v2 = variable_scope.get_variable(
"new_var2", [10, 10],
synchronization=variable_scope.VariableSynchronization.ON_READ,
aggregation=variable_scope.VariableAggregation.MEAN)
checkpoint_utils.init_from_checkpoint(checkpoint_dir, {
"var1": "new_var1",
"var2": "new_var2"
})
with self.session(graph=g) as session:
session.run(variables.global_variables_initializer())
self.assertAllEqual(v1_value, self.evaluate(v1))
self.assertAllEqual(v2_value, self.evaluate(v2))
with ops.Graph().as_default() as g, distribution.scope():
if in_replica_mode:
distribution.extended.call_for_each_replica(init_and_verify, args=[g])
else:
init_and_verify(g)
@combinations.generate(
combinations.combine(
distribution=[
strategy_combinations.default_strategy,
strategy_combinations.one_device_strategy,
strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
strategy_combinations.mirrored_strategy_with_two_gpus,
strategy_combinations
.mirrored_strategy_with_two_gpus_no_merge_call,
],
in_replica_mode=[True, False],
mode=["graph"]))
def testInitFromDifferentNameObject(self, distribution, in_replica_mode):
checkpoint_dir, v1_value, _ = self._get_test_object()
def init_and_verify(g):
v1 = variable_scope.get_variable("new_var1", [1, 10])
# Use string add to create new object in each replica
prefix = "new_"
suffix = "var1"
new_var1 = prefix + suffix
checkpoint_utils.init_from_checkpoint(checkpoint_dir, {
"var1": new_var1,
})
with self.test_session(graph=g) as session:
session.run(variables.global_variables_initializer())
self.assertAllEqual(v1_value, self.evaluate(v1))
with ops.Graph().as_default() as g, distribution.scope():
if in_replica_mode:
distribution.extended.call_for_each_replica(init_and_verify, [g])
else:
init_and_verify(g)
if __name__ == "__main__":
test.main()
| CheckpointUtilsWithDistributionStrategyTest |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran_tests/deprecated/test_asset_defs.py | {
"start": 7094,
"end": 9472
} | class ____(DagsterFivetranTranslator):
def get_asset_spec(self, props: FivetranConnectorTableProps) -> AssetSpec:
default_spec = super().get_asset_spec(props)
return default_spec.replace_attributes(
key=["wacky", *["".join(reversed(item)) for item in default_spec.key.path], "wow"],
)
@pytest.mark.parametrize(
"translator, expected_key",
[
(
MyCustomTranslator,
AssetKey(["prefix", "schema_name_in_destination_1", "table_name_in_destination_1"]),
),
(
MyCustomTranslatorWackyKeys,
AssetKey(
["wacky", "1_noitanitsed_ni_eman_amehcs", "1_noitanitsed_ni_eman_elbat", "wow"]
),
),
],
ids=["custom_translator", "custom_translator_wacky_keys"],
)
def test_translator_custom_metadata_materialize(
fetch_workspace_data_api_mocks: responses.RequestsMock,
sync_and_poll: MagicMock,
translator: type[DagsterFivetranTranslator],
expected_key: AssetKey,
) -> None:
with environ({"FIVETRAN_API_KEY": TEST_API_KEY, "FIVETRAN_API_SECRET": TEST_API_SECRET}):
resource = FivetranResource(api_key=TEST_API_KEY, api_secret=TEST_API_SECRET)
my_cacheable_fivetran_assets = load_assets_from_fivetran_instance(
fivetran=resource, fetch_column_metadata=False, translator=translator
)
my_fivetran_assets = my_cacheable_fivetran_assets.build_definitions(
my_cacheable_fivetran_assets.compute_cacheable_data()
)
my_fivetran_assets_def = next(
assets_def
for assets_def in my_fivetran_assets
if TEST_CONNECTOR_ID in assets_def.op.name
)
result = materialize(
[my_fivetran_assets_def],
)
assert result.success
asset_materializations = [
event
for event in result.all_events
if event.event_type_value == "ASSET_MATERIALIZATION"
]
assert len(asset_materializations) == 4
materialized_asset_keys = {
asset_materialization.asset_key for asset_materialization in asset_materializations
}
assert len(materialized_asset_keys) == 4
assert my_fivetran_assets_def.keys == materialized_asset_keys
assert expected_key in materialized_asset_keys
| MyCustomTranslatorWackyKeys |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 6572,
"end": 20005
} | class ____(Exception):
"""Error raised when there is an issue converting data to Arrow."""
MAX_DATA_STR_LEN = 200
def __init__(self, data_str: str):
if len(data_str) > self.MAX_DATA_STR_LEN:
data_str = data_str[: self.MAX_DATA_STR_LEN] + "..."
message = f"Error converting data to Arrow: {data_str}"
super().__init__(message)
@DeveloperAPI
def pyarrow_table_from_pydict(
pydict: Dict[str, Union[List[Any], pa.Array]],
) -> pa.Table:
"""
Convert a Python dictionary to a pyarrow Table.
Raises:
ArrowConversionError: if the conversion fails.
"""
try:
return pa.Table.from_pydict(pydict)
except Exception as e:
raise ArrowConversionError(str(pydict)) from e
@DeveloperAPI(stability="alpha")
def convert_to_pyarrow_array(
column_values: Union[List[Any], np.ndarray, ArrayLike], column_name: str
) -> pa.Array:
"""Converts provided NumPy `ndarray` into PyArrow's `array` while utilizing
both Arrow's natively supported types as well as custom extension types:
- ArrowTensorArray (for tensors)
- ArrowPythonObjectArray (for user-defined python class objects, as well as
any python object that aren't represented by a corresponding Arrow's native
scalar type)
"""
try:
# Since Arrow does NOT support tensors (aka multidimensional arrays) natively,
# we have to make sure that we handle this case utilizing `ArrowTensorArray`
# extension type
if len(column_values) > 0 and _should_convert_to_tensor(
column_values, column_name
):
from ray.data.extensions.tensor_extension import ArrowTensorArray
# Convert to Numpy before creating instance of `ArrowTensorArray` to
# align tensor shapes falling back to ragged ndarray only if necessary
return ArrowTensorArray.from_numpy(
convert_to_numpy(column_values), column_name
)
else:
return _convert_to_pyarrow_native_array(column_values, column_name)
except ArrowConversionError as ace:
from ray.data.context import DataContext
enable_fallback_config: Optional[
bool
] = DataContext.get_current().enable_fallback_to_arrow_object_ext_type
if not _object_extension_type_allowed():
object_ext_type_fallback_allowed = False
object_ext_type_detail = (
"skipping fallback to serialize as pickled python"
f" objects (due to unsupported Arrow version {PYARROW_VERSION}, "
f"min required version is {MIN_PYARROW_VERSION_SCALAR_SUBCLASS})"
)
else:
# NOTE: By default setting is unset which (for compatibility reasons)
# is allowing the fallback
object_ext_type_fallback_allowed = (
enable_fallback_config is None or enable_fallback_config
)
if object_ext_type_fallback_allowed:
object_ext_type_detail = (
"falling back to serialize as pickled python objects"
)
else:
object_ext_type_detail = (
"skipping fallback to serialize as pickled python objects "
"(due to DataContext.enable_fallback_to_arrow_object_ext_type "
"= False)"
)
# To avoid logging following warning for every block it's
# only going to be logged in following cases
# - It's being logged for the first time, and
# - When config enabling fallback is not set explicitly (in this case
# fallback will still occur by default for compatibility reasons), or
# - Fallback is disallowed (either explicitly or due to use of incompatible
# Pyarrow version)
if (
enable_fallback_config is None or not object_ext_type_fallback_allowed
) and log_once("_fallback_to_arrow_object_extension_type_warning"):
logger.warning(
f"Failed to convert column '{column_name}' into pyarrow "
f"array due to: {ace}; {object_ext_type_detail}",
exc_info=ace,
)
if not object_ext_type_fallback_allowed:
# If `ArrowPythonObjectType` is not supported raise original exception
raise
# Otherwise, attempt to fall back to serialize as python objects
return ArrowPythonObjectArray.from_objects(column_values)
def _convert_to_pyarrow_native_array(
column_values: Union[List[Any], np.ndarray], column_name: str
) -> pa.Array:
"""Converts provided NumPy `ndarray` into PyArrow's `array` while only utilizing
Arrow's natively supported types (ie no custom extension types)"""
try:
# NOTE: Python's `datetime` only supports precision up to us and could
# inadvertently lose precision when handling Pandas `Timestamp` type.
# To avoid that we convert provided list of `datetime` objects into
# ndarray of `np.datetime64`
if len(column_values) > 0 and isinstance(column_values[0], datetime):
column_values = _convert_datetime_to_np_datetime(column_values)
# To avoid deserialization penalty of converting Arrow arrays (`Array` and `ChunkedArray`)
# to Python objects and then back to Arrow, we instead combine them into ListArray manually
if len(column_values) > 0 and isinstance(
column_values[0], (pa.Array, pa.ChunkedArray)
):
return _combine_as_list_array(column_values)
# NOTE: We explicitly infer PyArrow `DataType` so that
# we can perform upcasting to be able to accommodate
# blocks that are larger than 2Gb in size (limited
# by int32 offsets used by Arrow internally)
pa_type = _infer_pyarrow_type(column_values)
if pa_type and pa.types.is_timestamp(pa_type):
# NOTE: Quirky Arrow behavior will coerce unsupported Numpy `datetime64`
# precisions that are nested inside a list type, but won't do it,
# if these are top-level ndarray. To work this around we have to cast
# ndarray values manually
if isinstance(column_values, np.ndarray):
column_values = _coerce_np_datetime_to_pa_timestamp_precision(
column_values, pa_type, column_name
)
logger.log(
logging.getLevelName("TRACE"),
f"Inferred dtype of '{pa_type}' for column '{column_name}'",
)
# NOTE: Pyarrow 19.0 is not able to properly handle `ListScalar(None)` when
# creating native array and hence we have to manually replace any such
# cases w/ an explicit null value
#
# See for more details https://github.com/apache/arrow/issues/45682
if len(column_values) > 0 and isinstance(column_values[0], pa.ListScalar):
column_values = [v if v.is_valid else None for v in column_values]
return pa.array(column_values, type=pa_type)
except Exception as e:
raise ArrowConversionError(str(column_values)) from e
def _combine_as_list_array(column_values: List[Union[pa.Array, pa.ChunkedArray]]):
"""Combines list of Arrow arrays into a single `ListArray`"""
# First, compute respective offsets in the resulting array
lens = [len(v) for v in column_values]
offsets = pa.array(np.concatenate([[0], np.cumsum(lens)]), type=pa.int32())
# Concat all the chunks into a single contiguous array
combined = pa.concat_arrays(
itertools.chain(
*[
v.chunks if isinstance(v, pa.ChunkedArray) else [v]
for v in column_values
]
)
)
# TODO support null masking
return pa.ListArray.from_arrays(offsets, combined, pa.list_(combined.type))
def _coerce_np_datetime_to_pa_timestamp_precision(
column_values: np.ndarray, dtype: pa.TimestampType, column_name: str
):
assert np.issubdtype(column_values.dtype, np.datetime64)
numpy_precision, _ = np.datetime_data(column_values.dtype)
arrow_precision = dtype.unit
if arrow_precision != numpy_precision:
# Arrow supports fewer timestamp resolutions than NumPy. So, if Arrow
# doesn't support the resolution, we need to cast the NumPy array to a
# different type. This can be a lossy conversion.
column_values = column_values.astype(f"datetime64[{arrow_precision}]")
if log_once(f"column_{column_name}_timestamp_warning"):
logger.warning(
f"Converting a {numpy_precision!r} precision datetime NumPy "
f"array to '{arrow_precision}' precision Arrow timestamp. This "
"conversion occurs because Arrow supports fewer precisions "
"than Arrow and might result in a loss of precision or "
"unrepresentable values."
)
return column_values
def _infer_pyarrow_type(
column_values: Union[List[Any], np.ndarray]
) -> Optional[pa.DataType]:
"""Infers target Pyarrow `DataType` based on the provided
columnar values.
NOTE: This is a wrapper on top of `pa.infer_type(...)` utility
performing up-casting of `binary` and `string` types to
corresponding `large_binary` and `large_string` types in case
any of the array elements exceeds 2Gb in size therefore
making it impossible for original types to accommodate such
values.
Unfortunately, for unknown reasons PA doesn't perform
that upcasting itself henceforth we have to do perform
it manually
Args:
column_values: List of columnar values
Returns:
Instance of PyArrow's `DataType` based on the provided
column values
"""
if len(column_values) == 0:
return None
# `pyarrow.infer_type` leaks memory if you pass an array with a datetime64 dtype.
# To avoid this, we handle datetime64 dtypes separately.
# See https://github.com/apache/arrow/issues/45493.
dtype_with_timestamp_type = _try_infer_pa_timestamp_type(column_values)
if dtype_with_timestamp_type is not None:
return dtype_with_timestamp_type
inferred_pa_dtype = pa.infer_type(column_values)
def _len_gt_overflow_threshold(obj: Any) -> bool:
# NOTE: This utility could be seeing objects other than strings or bytes in
# cases when column contains non-scalar non-homogeneous object types as
# column values, therefore making Arrow unable to infer corresponding
# column type appropriately, therefore falling back to assume the type
# of the first element in the list.
#
# Check out test cases for this method for an additional context.
if isinstance(obj, (str, bytes)):
return len(obj) > INT32_MAX
return False
if pa.types.is_binary(inferred_pa_dtype) and any(
[_len_gt_overflow_threshold(v) for v in column_values]
):
return pa.large_binary()
elif pa.types.is_string(inferred_pa_dtype) and any(
[_len_gt_overflow_threshold(v) for v in column_values]
):
return pa.large_string()
return inferred_pa_dtype
_NUMPY_TO_ARROW_PRECISION_MAP = {
# Coarsest timestamp precision in Arrow is seconds
"Y": "s",
"D": "s",
"M": "s",
"W": "s",
"h": "s",
"m": "s",
"s": "s",
"ms": "ms",
"us": "us",
"ns": "ns",
# Finest timestamp precision in Arrow is nanoseconds
"ps": "ns",
"fs": "ns",
"as": "ns",
}
def _try_infer_pa_timestamp_type(
column_values: Union[List[Any], np.ndarray]
) -> Optional[pa.DataType]:
if isinstance(column_values, list) and len(column_values) > 0:
# In case provided column values is a list of elements, this
# utility assumes homogeneity (in line with the behavior of Arrow
# type inference utils)
element_type = _try_infer_pa_timestamp_type(column_values[0])
return pa.list_(element_type) if element_type else None
if isinstance(column_values, np.ndarray) and np.issubdtype(
column_values.dtype, np.datetime64
):
np_precision, _ = np.datetime_data(column_values.dtype)
return pa.timestamp(_NUMPY_TO_ARROW_PRECISION_MAP[np_precision])
else:
return None
@DeveloperAPI
def get_arrow_extension_tensor_types():
"""Returns list of extension types of Arrow Array holding
multidimensional tensors
"""
return (
*get_arrow_extension_fixed_shape_tensor_types(),
*get_arrow_extension_variable_shape_tensor_types(),
)
@DeveloperAPI
def get_arrow_extension_fixed_shape_tensor_types():
"""Returns list of Arrow extension types holding multidimensional
tensors of *fixed* shape
"""
return ArrowTensorType, ArrowTensorTypeV2
@DeveloperAPI
def get_arrow_extension_variable_shape_tensor_types():
"""Returns list of Arrow extension types holding multidimensional
tensors of *fixed* shape
"""
return (ArrowVariableShapedTensorType,)
# ArrowExtensionSerializeDeserializeCache needs to be first in the MRO to ensure the cache is used
| ArrowConversionError |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 41798,
"end": 42422
} | class ____:
cases = [
(Dummy.a_static_method, FunctionKind.STATIC),
(Dummy.a_class_method.__func__, FunctionKind.CLASS),
(Dummy.an_instance_method, FunctionKind.INSTANCE),
(Dummy.a_property.fget, FunctionKind.PROPERTY),
(a_module_func, FunctionKind.MODULE),
]
if cached_property:
cases.append((Dummy.a_cached_property.func, FunctionKind.DJANGO_CACHED_PROPERTY))
@pytest.mark.parametrize(
'func, expected',
cases,
)
def test_from_callable(self, func, expected):
assert FunctionKind.from_callable(func) == expected
| TestFunctionKind |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/firehose.py | {
"start": 978,
"end": 2023
} | class ____(AwsBaseHook):
"""
Interact with Amazon Kinesis Firehose.
Provide thick wrapper around :external+boto3:py:class:`boto3.client("firehose") <Firehose.Client>`.
:param delivery_stream: Name of the delivery stream
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
- :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""
def __init__(self, delivery_stream: str, *args, **kwargs) -> None:
self.delivery_stream = delivery_stream
kwargs["client_type"] = "firehose"
super().__init__(*args, **kwargs)
def put_records(self, records: Iterable) -> dict:
"""
Write batch records to Kinesis Firehose.
.. seealso::
- :external+boto3:py:meth:`Firehose.Client.put_record_batch`
:param records: list of records
"""
return self.get_conn().put_record_batch(DeliveryStreamName=self.delivery_stream, Records=records)
| FirehoseHook |
python | getsentry__sentry | src/sentry/apidocs/examples/team_examples.py | {
"start": 1603,
"end": 16326
} | class ____:
ADD_TO_TEAM = [
OpenApiExample(
"Join, request access to or add a member to a team",
value=BASE_TEAM_1,
status_codes=["201"],
response_only=True,
)
]
CREATE_TEAM = [
OpenApiExample(
"Create a new team",
value={
"id": "5151492858",
"slug": "ancient-gabelers",
"name": "Ancient Gabelers",
"dateCreated": "2021-06-12T23:38:54.168307Z",
"isMember": True,
"teamRole": "admin",
"flags": {"idp:provisioned": False},
"access": [
"project:write",
"member:read",
"event:write",
"team:admin",
"alerts:read",
"project:releases",
"alerts:write",
"org:read",
"team:read",
"project:admin",
"project:read",
"org:integrations",
"event:read",
"event:admin",
"team:write",
],
"hasAccess": True,
"isPending": False,
"memberCount": 1,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
},
status_codes=["201"],
response_only=True,
)
]
DELETE_FROM_TEAM = [
OpenApiExample(
"Remove a member from a team",
value={
"id": "4502349234123",
"slug": "ancient-gabelers",
"name": "Ancient Gabelers",
"dateCreated": "2023-05-31T19:47:53.621181Z",
"isMember": False,
"teamRole": None,
"flags": {"idp:provisioned": False},
"access": [
"alerts:read",
"event:write",
"project:read",
"team:read",
"member:read",
"project:releases",
"event:read",
"org:read",
],
"hasAccess": True,
"isPending": False,
"memberCount": 3,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
},
status_codes=["200"],
response_only=True,
)
]
LIST_TEAM_MEMBERS = [
OpenApiExample(
"List Team Members",
value=[ORGANIZATION_MEMBER_ON_TEAM],
status_codes=["200"],
response_only=True,
)
]
LIST_ORG_TEAMS = [
OpenApiExample(
"Get list of organization's teams",
value=[
{
"id": "48531",
"slug": "ancient-gabelers",
"name": "Ancient Gabelers",
"dateCreated": "2018-11-06T21:20:08.115Z",
"isMember": False,
"teamRole": None,
"flags": {"idp:provisioned": False},
"access": [
"member:read",
"alerts:read",
"org:read",
"event:read",
"project:read",
"project:releases",
"event:write",
"team:read",
],
"hasAccess": True,
"isPending": False,
"memberCount": 2,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
},
{
"id": "100253",
"slug": "powerful-abolitionist",
"name": "Powerful Abolitionist",
"dateCreated": "2018-10-03T17:47:50.745447Z",
"isMember": False,
"teamRole": None,
"flags": {"idp:provisioned": False},
"access": [
"member:read",
"alerts:read",
"org:read",
"event:read",
"project:read",
"project:releases",
"event:write",
"team:read",
],
"hasAccess": True,
"isPending": False,
"memberCount": 5,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
"projects": [
{
"id": "6403534",
"slug": "prime-mover",
"name": "Prime Mover",
"platform": None,
"dateCreated": "2019-04-06T00:02:40.468175Z",
"isBookmarked": False,
"isMember": False,
"features": [
"alert-filters",
"custom-inbound-filters",
"data-forwarding",
"discard-groups",
"minidump",
"rate-limits",
"servicehooks",
"similarity-indexing",
"similarity-indexing-v2",
"similarity-view",
"similarity-view-v2",
"releases",
],
"firstEvent": "2019-04-06T02:00:21Z",
"firstTransactionEvent": True,
"access": [
"alerts:read",
"event:write",
"org:read",
"project:read",
"member:read",
"team:read",
"event:read",
"project:releases",
],
"hasAccess": True,
"hasMinifiedStackTrace": False,
"hasMonitors": True,
"hasProfiles": False,
"hasReplays": False,
"hasFlags": False,
"hasFeedbacks": False,
"hasNewFeedbacks": False,
"hasSessions": True,
"hasInsightsHttp": True,
"hasInsightsDb": False,
"hasInsightsAssets": True,
"hasInsightsAppStart": False,
"hasInsightsScreenLoad": False,
"hasInsightsVitals": False,
"hasInsightsCaches": False,
"hasInsightsQueues": False,
"hasInsightsAgentMonitoring": False,
"hasInsightsMCP": False,
"hasLogs": False,
"hasTraceMetrics": False,
"isInternal": False,
"isPublic": False,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
"color": "#6d3fbf",
"status": "active",
},
{
"id": "6403599",
"slug": "the-spoiled-yoghurt",
"name": "The Spoiled Yoghurt",
"platform": "",
"dateCreated": "2022-06-24T17:55:27.304367Z",
"isBookmarked": False,
"isMember": False,
"features": [
"alert-filters",
"custom-inbound-filters",
"data-forwarding",
"discard-groups",
"minidump",
"rate-limits",
"servicehooks",
"similarity-indexing",
"similarity-indexing-v2",
"similarity-view",
"similarity-view-v2",
],
"firstEvent": "2022-07-13T18:17:56.197351Z",
"firstTransactionEvent": False,
"access": [
"alerts:read",
"event:write",
"org:read",
"project:read",
"member:read",
"team:read",
"event:read",
"project:releases",
],
"hasAccess": True,
"hasMinifiedStackTrace": False,
"hasMonitors": True,
"hasProfiles": False,
"hasReplays": False,
"hasFlags": False,
"hasFeedbacks": False,
"hasNewFeedbacks": False,
"hasSessions": False,
"hasInsightsHttp": False,
"hasInsightsDb": True,
"hasInsightsAssets": True,
"hasInsightsAppStart": True,
"hasInsightsScreenLoad": True,
"hasInsightsVitals": False,
"hasInsightsCaches": False,
"hasInsightsQueues": False,
"hasInsightsAgentMonitoring": False,
"hasInsightsMCP": False,
"hasLogs": False,
"hasTraceMetrics": False,
"isInternal": False,
"isPublic": False,
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
"color": "#6e3fbf",
"status": "active",
},
],
},
],
status_codes=["200"],
response_only=True,
)
]
LIST_PROJECT_TEAMS = [
OpenApiExample(
"List a project's teams",
value=[BASE_TEAM_1, BASE_TEAM_2],
status_codes=["200"],
response_only=True,
)
]
LIST_TEAM_PROJECTS = [
OpenApiExample(
"Get list of team's projects",
value=[PROJECT_SUMMARY],
status_codes=["200"],
response_only=True,
)
]
RETRIEVE_TEAM_DETAILS = [
OpenApiExample(
"Retrieve a Team",
value={
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
"dateCreated": "2018-11-06T21:19:55.114Z",
"hasAccess": True,
"id": "2",
"isMember": True,
"isPending": False,
"memberCount": 1,
"name": "Powerful Abolitionist",
"organization": {
"avatar": {"avatarType": "letter_avatar", "avatarUuid": None},
"dateCreated": "2018-11-06T21:19:55.101Z",
"id": "2",
"isEarlyAdopter": False,
"allowMemberInvite": True,
"allowMemberProjectCreation": True,
"allowSuperuserAccess": False,
"name": "The Interstellar Jurisdiction",
"require2FA": False,
"slug": "the-interstellar-jurisdiction",
"status": {"id": "active", "name": "active"},
"features": ["session-replay-videos"],
"hasAuthProvider": True,
"links": {
"organizationUrl": "https://philosophers.sentry.io",
"regionUrl": "https://us.sentry.io",
},
},
"slug": "powerful-abolitionist",
"access": [
"event:read",
"event:write",
"team:read",
"org:read",
"project:read",
"member:read",
"project:releases",
"alerts:read",
],
"flags": {"idp:provisioned": False},
"teamRole": "contributor",
},
status_codes=["200"],
response_only=True,
)
]
UPDATE_TEAM = [
OpenApiExample(
"Update a Team",
value={
"avatar": {"avatarType": "letter_avatar"},
"dateCreated": "2018-11-06T21:20:08.115Z",
"hasAccess": True,
"id": "3",
"isMember": False,
"isPending": False,
"memberCount": 1,
"name": "The Inflated Philosophers",
"slug": "the-inflated-philosophers",
"access": [
"event:read",
"event:write",
"team:read",
"org:read",
"project:read",
"member:read",
"project:releases",
"alerts:read",
],
"flags": {"idp:provisioned": False},
"teamRole": "contributor",
},
status_codes=["200"],
response_only=True,
)
]
UPDATE_TEAM_ROLE = [
OpenApiExample(
"Update a Team Role",
value={
"isActive": True,
"teamRole": "admin",
},
status_codes=["200"],
response_only=True,
)
]
| TeamExamples |
python | sqlalchemy__sqlalchemy | test/sql/test_compare.py | {
"start": 5383,
"end": 5508
} | class ____(TypeDecorator):
impl = Integer
cache_ok = True
def __init__(self, arg):
self.arg = arg
| MyType3 |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 191750,
"end": 193874
} | class ____(fixtures.MappedTest):
"""test usage of the old 'relation' function."""
run_inserts = "once"
run_deletes = None
@classmethod
def define_tables(cls, metadata):
Table(
"users_table",
metadata,
Column("id", Integer, primary_key=True),
Column("name", String(64)),
)
Table(
"addresses_table",
metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("users_table.id")),
Column("email_address", String(128)),
Column("purpose", String(16)),
Column("bounces", Integer, default=0),
)
@classmethod
def setup_classes(cls):
class User(cls.Basic):
pass
class Address(cls.Basic):
pass
@classmethod
def fixtures(cls):
return dict(
users_table=(
("id", "name"),
(1, "jack"),
(2, "ed"),
(3, "fred"),
(4, "chuck"),
),
addresses_table=(
("id", "user_id", "email_address", "purpose", "bounces"),
(1, 1, "jack@jack.home", "Personal", 0),
(2, 1, "jack@jack.bizz", "Work", 1),
(3, 2, "ed@foo.bar", "Personal", 0),
(4, 3, "fred@the.fred", "Personal", 10),
),
)
def test_relationship(self):
addresses_table, User, users_table, Address = (
self.tables.addresses_table,
self.classes.User,
self.tables.users_table,
self.classes.Address,
)
self.mapper_registry.map_imperatively(
User,
users_table,
properties=dict(addresses=relationship(Address, backref="user")),
)
self.mapper_registry.map_imperatively(Address, addresses_table)
session = fixture_session()
session.query(User).filter(
User.addresses.any(Address.email_address == "ed@foo.bar")
).one()
| RelationDeprecationTest |
python | getsentry__sentry | src/sentry/utils/pubsub.py | {
"start": 163,
"end": 1054
} | class ____:
# XXX(markus): Deprecated. Please use `sentry.utils.arroyo_producer.get_arroyo_producer`.
def __init__(self, connection: dict[str, Any], asynchronous: bool = True) -> None:
connection = connection or {}
if "client.id" not in connection:
connection["client.id"] = "sentry.utils.pubsub"
self.producer = get_confluent_producer(
build_kafka_producer_configuration(default_config=connection)
)
self.asynchronous = asynchronous
def publish(self, channel: str, value: str, key: str | None = None) -> None:
self.producer.produce(topic=channel, value=value, key=key)
if self.asynchronous:
self.producer.poll(0)
else:
self.producer.flush()
def flush(self) -> None:
"""Manually flush the Kafka client buffer."""
self.producer.flush()
| KafkaPublisher |
python | getsentry__sentry | src/sentry/models/statistical_detectors.py | {
"start": 822,
"end": 3135
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
# Meta data about the regression group
date_added = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
# When the regression started, this is the breakpoint.
date_regressed = models.DateTimeField()
# When the regression resolved.
date_resolved = models.DateTimeField(null=True)
# The version associated with the group. Each time a regression
# is detected for the group, we increment the version.
version = models.IntegerField()
# Indiciates if the regression group is active or not. This should
# be checked in conjunction with the issue group status to determine
# the status of the group as manual status changes do not
# propagate from the issue group to here.
active = models.BooleanField(default=True)
project_id = BoundedBigIntegerField(db_index=True)
type = BoundedIntegerField(choices=RegressionType.as_choices())
# The fingerprint sent to the issue platform which
# accepts a list of strings. This corresponds to the
# first string which is a 8 char hex for functions
# and a 40 char hex for transactions
fingerprint = models.CharField(max_length=64)
# The value measured from before the regression.
baseline = models.FloatField()
# The value measured from after the regression.
regressed = models.FloatField()
class Meta:
indexes = (models.Index(fields=("type", "project_id", "fingerprint", "active")),)
unique_together = (("type", "project_id", "fingerprint", "version"),)
__repr__ = sane_repr("active", "version", "type", "project_id", "fingerprint")
def get_regression_groups(
regression_type: RegressionType, pairs: Sequence[tuple[int, str]], active: bool | None = None
) -> QuerySet[RegressionGroup]:
conditions = Q()
for project_id, fingerprint in pairs:
conditions |= Q(project_id=project_id, fingerprint=fingerprint)
is_active = Q() if active is None else Q(active=active)
return (
RegressionGroup.objects.filter(conditions, is_active, type=regression_type.value)
.order_by("type", "project_id", "fingerprint", "-version")
.distinct("type", "project_id", "fingerprint")
)
| RegressionGroup |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/recompose_on_mount.py | {
"start": 214,
"end": 539
} | class ____(Static):
choices: reactive[list[str]] = reactive(list, recompose=True)
def compose(self) -> ComposeResult:
yield RadioSet(*self.choices)
async def on_mount(self) -> None:
self.choices.append("Foo")
self.choices.append("Bar")
self.mutate_reactive(Profile.choices)
| Profile |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 10910,
"end": 11121
} | class ____(Where):
"""Not in comparison - value is not in a list"""
key: str
values: List[Any]
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$nin": self.values}}
@dataclass
| Nin |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 131060,
"end": 134171
} | class ____(Response):
"""
Response of tasks.archive_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "archive_many"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"archived": {
"description": "Indicates whether the task was archived",
"type": "boolean",
},
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(self, succeeded=None, failed=None, **kwargs):
super(ArchiveManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self):
return self._property_succeeded
@succeeded.setter
def succeeded(self, value):
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self):
return self._property_failed
@failed.setter
def failed(self, value):
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
| ArchiveManyResponse |
python | great-expectations__great_expectations | great_expectations/render/renderer/site_index_page_renderer.py | {
"start": 764,
"end": 18020
} | class ____(Renderer):
@classmethod
def _generate_expectation_suites_link_table(cls, index_links_dict):
table_options = {
"search": "true",
"trimOnSearch": "false",
"visibleSearch": "true",
"rowStyle": "rowStyleLinks",
"rowAttributes": "rowAttributesLinks",
"sortName": "expectation_suite_name",
"sortOrder": "asc",
"pagination": "true",
"iconSize": "sm",
"toolbarAlign": "right",
}
table_columns = [
{
"field": "expectation_suite_name",
"title": "Expectation Suites",
"sortable": "true",
},
]
expectation_suite_link_dicts = index_links_dict.get("expectations_links", [])
table_data = []
for dict_ in expectation_suite_link_dicts:
table_data.append(
{
"expectation_suite_name": dict_.get("expectation_suite_name"),
"_table_row_link_path": dict_.get("filepath"),
}
)
return RenderedBootstrapTableContent(
**{
"table_columns": table_columns,
"table_data": table_data,
"table_options": table_options,
"styling": {
"classes": ["col-12", "ge-index-page-table-container"],
"body": {
"classes": [
"table-sm",
"ge-index-page-expectation_suites-table",
]
},
},
}
)
# TODO: deprecate dual batch api support in 0.14
@classmethod
def _generate_profiling_results_link_table(cls, index_links_dict):
table_options = {
"search": "true",
"trimOnSearch": "false",
"visibleSearch": "true",
"rowStyle": "rowStyleLinks",
"rowAttributes": "rowAttributesLinks",
"sortName": "run_time",
"sortOrder": "desc",
"pagination": "true",
"filterControl": "true",
"iconSize": "sm",
"toolbarAlign": "right",
}
table_columns = [
{
"field": "run_time",
"title": "Run Time",
"sortName": "_run_time_sort",
"sortable": "true",
"filterControl": "datepicker",
"filterCustomSearch": "formatRuntimeDateForFilter",
"filterDatepickerOptions": {
"clearBtn": "true",
"autoclose": "true",
"format": "yyyy-mm-dd",
"todayHighlight": "true",
},
},
{
"field": "asset_name",
"title": "Asset Name",
"sortable": "true",
"filterControl": "select",
},
{
"field": "batch_identifier",
"title": "Batch ID",
"sortName": "_batch_identifier_sort",
"sortable": "true",
"filterControl": "input",
},
{
"field": "profiler_name",
"title": "Profiler",
"sortable": "true",
"filterControl": "select",
},
]
profiling_link_dicts = index_links_dict.get("profiling_links", [])
table_data = []
for dict_ in profiling_link_dicts:
table_data.append(
{
"run_time": cls._get_formatted_datetime(dict_.get("run_time")),
"_run_time_sort": cls._get_timestamp(dict_.get("run_time")),
"asset_name": dict_.get("asset_name"),
"batch_identifier": cls._render_batch_id_cell(
dict_.get("batch_identifier"),
dict_.get("batch_kwargs"),
dict_.get("batch_spec"),
),
"_batch_identifier_sort": dict_.get("batch_identifier"),
"profiler_name": dict_.get("expectation_suite_name").split(".")[-1],
"_table_row_link_path": dict_.get("filepath"),
}
)
return RenderedBootstrapTableContent(
**{
"table_columns": table_columns,
"table_data": table_data,
"table_options": table_options,
"styling": {
"classes": ["col-12", "ge-index-page-table-container"],
"body": {"classes": ["table-sm", "ge-index-page-profiling-results-table"]},
},
}
)
# TODO: deprecate dual batch api support in 0.14
@classmethod
def _generate_validation_results_link_table(cls, index_links_dict):
table_options = {
"search": "true",
"trimOnSearch": "false",
"visibleSearch": "true",
"rowStyle": "rowStyleLinks",
"rowAttributes": "rowAttributesLinks",
"sortName": "run_time",
"sortOrder": "desc",
"pagination": "true",
"filterControl": "true",
"iconSize": "sm",
"toolbarAlign": "right",
"showSearchClearButton": "true",
}
table_columns = [
{
"field": "validation_success",
"title": "Status",
"sortable": "true",
"align": "center",
"filterControl": "select",
"filterDataCollector": "validationSuccessFilterDataCollector",
},
{
"field": "run_time",
"title": "Run Time",
"sortName": "_run_time_sort",
"sortable": "true",
"filterControl": "datepicker",
"filterCustomSearch": "formatRuntimeDateForFilter",
"filterDatepickerOptions": {
"clearBtn": "true",
"autoclose": "true",
"format": "yyyy-mm-dd",
"todayHighlight": "true",
},
},
{
"field": "run_name",
"title": "Run Name",
"sortable": "true",
"filterControl": "input",
},
{
"field": "asset_name",
"title": "Asset Name",
"sortable": "true",
"filterControl": "select",
},
{
"field": "batch_identifier",
"title": "Batch ID",
"sortName": "_batch_identifier_sort",
"sortable": "true",
"filterControl": "input",
},
{
"field": "expectation_suite_name",
"title": "Expectation Suite",
"sortName": "_expectation_suite_name_sort",
"sortable": "true",
"filterControl": "select",
"filterDataCollector": "expectationSuiteNameFilterDataCollector",
},
]
validation_link_dicts = index_links_dict.get("validations_links", [])
table_data = []
for dict_ in validation_link_dicts:
table_data.append(
{
"validation_success": cls._render_validation_success_cell(
dict_.get("validation_success")
),
"run_time": cls._get_formatted_datetime(dict_.get("run_time")),
"_run_time_sort": cls._get_timestamp(dict_.get("run_time")),
"run_name": dict_.get("run_name"),
"batch_identifier": cls._render_batch_id_cell(
dict_.get("batch_identifier"),
dict_.get("batch_kwargs"),
dict_.get("batch_spec"),
),
"_batch_identifier_sort": dict_.get("batch_identifier"),
"expectation_suite_name": cls._render_expectation_suite_cell(
dict_.get("expectation_suite_name"),
dict_.get("expectation_suite_filepath"),
),
"_expectation_suite_name_sort": dict_.get("expectation_suite_name"),
"_table_row_link_path": dict_.get("filepath"),
"_validation_success_text": "Success"
if dict_.get("validation_success")
else "Failed",
"asset_name": dict_.get("asset_name"),
}
)
return RenderedBootstrapTableContent(
**{
"table_columns": table_columns,
"table_data": table_data,
"table_options": table_options,
"styling": {
"classes": ["col-12", "ge-index-page-table-container"],
"body": {
"classes": [
"table-sm",
"ge-index-page-validation-results-table",
]
},
},
}
)
@classmethod
def _render_expectation_suite_cell(cls, expectation_suite_name, expectation_suite_path):
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$link_text",
"params": {"link_text": expectation_suite_name},
"tag": "a",
"styling": {
"styles": {"word-break": "break-all"},
"attributes": {"href": expectation_suite_path},
"classes": ["ge-index-page-table-expectation-suite-link"],
},
},
}
)
# TODO: deprecate dual batch api support in 0.14
@classmethod
def _render_batch_id_cell(cls, batch_id, batch_kwargs=None, batch_spec=None):
if batch_kwargs:
content_title = "Batch Kwargs"
content = json.dumps(batch_kwargs, indent=2)
else:
content_title = "Batch Spec"
content = json.dumps(batch_spec, indent=2)
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": str(batch_id),
"tooltip": {
"content": f"{content_title}:\n\n{content}",
"placement": "top",
},
"styling": {"classes": ["m-0", "p-0"]},
},
}
)
@classmethod
def _get_formatted_datetime(cls, _datetime):
if isinstance(_datetime, datetime.datetime):
local_zone = tzlocal.get_localzone()
local_datetime = _datetime.astimezone(tz=local_zone)
return local_datetime.strftime("%Y-%m-%d %H:%M:%S %Z")
elif isinstance(_datetime, str):
dt = parse(_datetime)
local_datetime = dt.astimezone(tz=tzlocal.get_localzone())
return local_datetime.strftime("%Y-%m-%d %H:%M:%S %Z")
else:
return None
@classmethod
def _get_timestamp(cls, _datetime):
if isinstance(_datetime, datetime.datetime):
return _datetime.timestamp()
elif isinstance(_datetime, str):
return parse(_datetime).timestamp()
else:
return ""
@classmethod
def _render_validation_success_cell(cls, validation_success):
return RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$validation_success",
"params": {"validation_success": ""},
"styling": {
"params": {
"validation_success": {
"tag": "i",
"classes": [
"fas",
"fa-check-circle",
"text-success",
"ge-success-icon",
]
if validation_success
else [
"fas",
"fa-times",
"text-danger",
"ge-failed-icon",
],
}
},
"classes": ["ge-index-page-table-validation-links-item"],
},
},
}
)
@classmethod
@override
def render(cls, index_links_dict):
sections = []
cta_object = index_links_dict.pop("cta_object", None)
try:
content_blocks = []
# site name header
site_name_header_block = RenderedHeaderContent(
**{
"content_block_type": "header",
"header": RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": "$title_prefix | $site_name",
"params": {
"site_name": index_links_dict.get("site_name"),
"title_prefix": "Data Docs",
},
"styling": {"params": {"title_prefix": {"tag": "strong"}}},
},
}
),
"styling": {
"classes": ["col-12", "ge-index-page-site-name-title"],
"header": {"classes": ["alert", "alert-secondary"]},
},
}
)
content_blocks.append(site_name_header_block)
tabs = []
if index_links_dict.get("validations_links"):
tabs.append(
{
"tab_name": "Validation Results",
"tab_content": cls._generate_validation_results_link_table(
index_links_dict
),
}
)
if index_links_dict.get("profiling_links"):
tabs.append(
{
"tab_name": "Profiling Results",
"tab_content": cls._generate_profiling_results_link_table(index_links_dict),
}
)
if index_links_dict.get("expectations_links"):
tabs.append(
{
"tab_name": "Expectation Suites",
"tab_content": cls._generate_expectation_suites_link_table(
index_links_dict
),
}
)
tabs_content_block = RenderedTabsContent(
**{
"tabs": tabs,
"styling": {
"classes": ["col-12", "ge-index-page-tabs-container"],
},
}
)
content_blocks.append(tabs_content_block)
section = RenderedSectionContent(
**{
"section_name": index_links_dict.get("site_name"),
"content_blocks": content_blocks,
}
)
sections.append(section)
index_page_document = RenderedDocumentContent(
**{
"renderer_type": "SiteIndexPageRenderer",
"utm_medium": "index-page",
"sections": sections,
}
)
if cta_object:
index_page_document.cta_footer = CallToActionRenderer.render(cta_object)
return index_page_document
except Exception as e:
exception_message = """\
An unexpected Exception occurred during data docs rendering. Because of this error, certain parts of data docs will \
not be rendered properly and/or may not appear altogether. Please use the trace, included in this message, to \
diagnose and repair the underlying issue. Detailed information follows:
""" # noqa: E501 # FIXME CoP
exception_traceback = traceback.format_exc()
exception_message += (
f'{type(e).__name__}: "{e!s}". Traceback: "{exception_traceback}".'
)
logger.error(exception_message) # noqa: TRY400 # FIXME CoP
| SiteIndexPageRenderer |
python | modin-project__modin | modin/core/execution/dispatching/factories/factories.py | {
"start": 3466,
"end": 22168
} | class ____(object):
io_cls: typing.Type[BaseIO] = None # The module where the I/O functionality exists.
@classmethod
def get_info(cls) -> FactoryInfo:
"""
Get information about current factory.
Notes
-----
It parses factory name, so it must be conformant with how ``FactoryDispatcher``
class constructs factory names.
"""
try:
experimental, partition, engine = re.match(
r"^(Experimental)?(.*)On(.*)Factory$", cls.__name__
).groups()
except AttributeError:
raise NotRealFactory()
return FactoryInfo(
engine=engine, partition=partition, experimental=bool(experimental)
)
@classmethod
@doc(
_doc_factory_prepare_method,
io_module_name="an underlying execution's IO-module",
)
def prepare(cls):
raise NotImplementedError("Subclasses of BaseFactory must implement prepare")
@classmethod
@doc(
_doc_io_method_template,
source="pandas DataFrame",
params="df : pandas.DataFrame",
method="io.from_pandas",
)
def _from_pandas(cls, df):
return cls.io_cls.from_pandas(df)
@classmethod
@doc(
_doc_io_method_template,
source="Arrow Table",
params="at : pyarrow.Table",
method="io.from_arrow",
)
def _from_arrow(cls, at):
return cls.io_cls.from_arrow(at)
@classmethod
@doc(
_doc_io_method_template,
source="a non-pandas object (dict, list, np.array etc...)",
params=_doc_io_method_all_params,
method="io.from_non_pandas",
)
def _from_non_pandas(cls, *args, **kwargs):
return cls.io_cls.from_non_pandas(*args, **kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a DataFrame object supporting exchange protocol `__dataframe__()`",
params=_doc_io_method_all_params,
method="io.from_interchange_dataframe",
)
def _from_interchange_dataframe(cls, *args, **kwargs):
return cls.io_cls.from_interchange_dataframe(*args, **kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a Ray Dataset",
params="ray_obj : ray.data.Dataset",
method="modin.core.execution.ray.implementations.pandas_on_ray.io.PandasOnRayIO.from_ray",
)
def _from_ray(cls, ray_obj):
return cls.io_cls.from_ray(ray_obj)
@classmethod
@doc(
_doc_io_method_template,
source="a Dask DataFrame",
params="dask_obj : dask.dataframe.DataFrame",
method="modin.core.execution.dask.implementations.pandas_on_dask.io.PandasOnDaskIO.from_dask",
)
def _from_dask(cls, dask_obj):
return cls.io_cls.from_dask(dask_obj)
@classmethod
def _from_map(cls, func, iterable, *args, **kwargs):
"""
Create a Modin `query_compiler` from a map function.
This method will construct a Modin `query_compiler` split by row partitions.
The number of row partitions matches the number of elements in the iterable object.
Parameters
----------
func : callable
Function to map across the iterable object.
iterable : Iterable
An iterable object.
*args : tuple
Positional arguments to pass in `func`.
**kwargs : dict
Keyword arguments to pass in `func`.
Returns
-------
BaseQueryCompiler
QueryCompiler containing data returned by map function.
"""
return cls.io_cls.from_map(func, iterable, *args, **kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a Parquet file",
params=_doc_io_method_kwargs_params,
method="read_parquet",
)
def _read_parquet(cls, **kwargs):
return cls.io_cls.read_parquet(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a CSV file",
params=_doc_io_method_kwargs_params,
method="read_csv",
)
def _read_csv(cls, **kwargs):
return cls.io_cls.read_csv(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a JSON file",
params=_doc_io_method_kwargs_params,
method="read_json",
)
def _read_json(cls, **kwargs):
return cls.io_cls.read_json(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a Google BigQuery",
params=_doc_io_method_kwargs_params,
method="read_gbq",
)
def _read_gbq(cls, **kwargs):
return cls.io_cls.read_gbq(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="an HTML document",
params=_doc_io_method_kwargs_params,
method="read_html",
)
def _read_html(cls, **kwargs):
return cls.io_cls.read_html(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="clipboard",
params=_doc_io_method_kwargs_params,
method="read_clipboard",
)
def _read_clipboard(cls, **kwargs): # pragma: no cover
return cls.io_cls.read_clipboard(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="an Excel file",
params=_doc_io_method_kwargs_params,
method="read_excel",
)
def _read_excel(cls, **kwargs):
return cls.io_cls.read_excel(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="an HDFStore",
params=_doc_io_method_kwargs_params,
method="read_hdf",
)
def _read_hdf(cls, **kwargs):
return cls.io_cls.read_hdf(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a feather-format object",
params=_doc_io_method_kwargs_params,
method="read_feather",
)
def _read_feather(cls, **kwargs):
return cls.io_cls.read_feather(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a Stata file",
params=_doc_io_method_kwargs_params,
method="read_stata",
)
def _read_stata(cls, **kwargs):
return cls.io_cls.read_stata(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a SAS file",
params=_doc_io_method_kwargs_params,
method="read_sas",
)
def _read_sas(cls, **kwargs): # pragma: no cover
return cls.io_cls.read_sas(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a pickled Modin or pandas DataFrame",
params=_doc_io_method_kwargs_params,
method="read_pickle",
)
def _read_pickle(cls, **kwargs):
return cls.io_cls.read_pickle(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a SQL query or database table",
params=_doc_io_method_kwargs_params,
method="read_sql",
)
def _read_sql(cls, **kwargs):
return cls.io_cls.read_sql(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a table of fixed-width formatted lines",
params=_doc_io_method_kwargs_params,
method="read_fwf",
)
def _read_fwf(cls, **kwargs):
return cls.io_cls.read_fwf(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a SQL database table",
params=_doc_io_method_kwargs_params,
method="read_sql_table",
)
def _read_sql_table(cls, **kwargs):
return cls.io_cls.read_sql_table(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="a SQL query",
params=_doc_io_method_kwargs_params,
method="read_sql_query",
)
def _read_sql_query(cls, **kwargs):
return cls.io_cls.read_sql_query(**kwargs)
@classmethod
@doc(
_doc_io_method_template,
source="an SPSS file",
params=_doc_io_method_kwargs_params,
method="read_spss",
)
def _read_spss(cls, **kwargs):
return cls.io_cls.read_spss(**kwargs)
@classmethod
def _to_sql(cls, *args, **kwargs):
"""
Write query compiler content to a SQL database.
Parameters
----------
*args : args
Arguments to the writer method.
**kwargs : kwargs
Arguments to the writer method.
"""
return cls.io_cls.to_sql(*args, **kwargs)
@classmethod
def _to_pickle(cls, *args, **kwargs):
"""
Pickle query compiler object.
Parameters
----------
*args : args
Arguments to the writer method.
**kwargs : kwargs
Arguments to the writer method.
"""
return cls.io_cls.to_pickle(*args, **kwargs)
@classmethod
def _to_csv(cls, *args, **kwargs):
"""
Write query compiler content to a CSV file.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
return cls.io_cls.to_csv(*args, **kwargs)
@classmethod
def _to_json(cls, *args, **kwargs):
"""
Write query compiler content to a JSON file.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
return cls.io_cls.to_json(*args, **kwargs)
@classmethod
def _to_json_series(cls, *args, **kwargs):
"""
Write query compiler content of a Series to a JSON file.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
return cls.io_cls.to_json_series(*args, **kwargs)
@classmethod
def _to_xml(cls, *args, **kwargs):
"""
Write query compiler content to a XML file.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
return cls.io_cls.to_xml(*args, **kwargs)
@classmethod
def _to_parquet(cls, *args, **kwargs):
"""
Write query compiler content to a parquet file.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
return cls.io_cls.to_parquet(*args, **kwargs)
@classmethod
def _to_ray(cls, modin_obj):
"""
Write query compiler content to a Ray Dataset.
Parameters
----------
modin_obj : modin.pandas.DataFrame, modin.pandas.Series
The Modin DataFrame/Series to write.
Returns
-------
ray.data.Dataset
A Ray Dataset object.
Notes
-----
Modin DataFrame/Series can only be converted to a Ray Dataset if Modin uses a Ray engine.
"""
return cls.io_cls.to_ray(modin_obj)
@classmethod
def _to_dask(cls, modin_obj):
"""
Write query compiler content to a Dask DataFrame/Series.
Parameters
----------
modin_obj : modin.pandas.DataFrame, modin.pandas.Series
The Modin DataFrame/Series to write.
Returns
-------
dask.dataframe.DataFrame or dask.dataframe.Series
A Dask DataFrame/Series object.
Notes
-----
Modin DataFrame/Series can only be converted to a Dask DataFrame/Series if Modin uses a Dask engine.
"""
return cls.io_cls.to_dask(modin_obj)
# experimental methods that don't exist in pandas
@classmethod
@doc(
_doc_io_method_raw_template,
source="CSV files",
params=_doc_io_method_kwargs_params,
)
def _read_csv_glob(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_csv_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_csv_glob(**kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="Pickle files",
params=_doc_io_method_kwargs_params,
)
def _read_pickle_glob(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_pickle_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_pickle_glob(**kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="SQL files",
params=_doc_io_method_kwargs_params,
)
def _read_sql_distributed(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
extra_parameters = (
"partition_column",
"lower_bound",
"upper_bound",
"max_sessions",
)
if any(
param in kwargs and kwargs[param] is not None
for param in extra_parameters
):
warnings.warn(
f"Distributed read_sql() was only implemented for {', '.join(supported_executions)} executions."
)
for param in extra_parameters:
del kwargs[param]
return cls.io_cls.read_sql(**kwargs)
return cls.io_cls.read_sql_distributed(**kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="Custom text files",
params=_doc_io_method_kwargs_params,
)
def _read_custom_text(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_custom_text()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_custom_text(**kwargs)
@classmethod
def _to_pickle_glob(cls, *args, **kwargs):
"""
Distributed pickle query compiler object.
Parameters
----------
*args : args
Arguments to the writer method.
**kwargs : kwargs
Arguments to the writer method.
"""
# TODO(https://github.com/modin-project/modin/issues/7429): Use
# frame-level execution instead of the global, default execution.
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_to_pickle_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.to_pickle_glob(*args, **kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="Parquet files",
params=_doc_io_method_kwargs_params,
)
def _read_parquet_glob(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_parquet_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_parquet_glob(**kwargs)
@classmethod
def _to_parquet_glob(cls, *args, **kwargs):
"""
Write query compiler content to several parquet files.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_to_parquet_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.to_parquet_glob(*args, **kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="Json files",
params=_doc_io_method_kwargs_params,
)
def _read_json_glob(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_json_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_json_glob(**kwargs)
@classmethod
def _to_json_glob(cls, *args, **kwargs):
"""
Write query compiler content to several json files.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_to_json_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.to_json_glob(*args, **kwargs)
@classmethod
@doc(
_doc_io_method_raw_template,
source="XML files",
params=_doc_io_method_kwargs_params,
)
def _read_xml_glob(cls, **kwargs):
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_read_xml_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.read_xml_glob(**kwargs)
@classmethod
def _to_xml_glob(cls, *args, **kwargs):
"""
Write query compiler content to several XML files.
Parameters
----------
*args : args
Arguments to pass to the writer method.
**kwargs : kwargs
Arguments to pass to the writer method.
"""
current_execution = get_current_execution()
if current_execution not in supported_executions:
raise NotImplementedError(
f"`_to_xml_glob()` is not implemented for {current_execution} execution."
)
return cls.io_cls.to_xml_glob(*args, **kwargs)
@doc(_doc_factory_class, execution_name="PandasOnRay")
| BaseFactory |
python | huggingface__transformers | tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py | {
"start": 5167,
"end": 8259
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as AST does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
if is_torch_available()
else {}
)
test_resize_embeddings = False
# TODO: Fix the failed tests when this model gets more usage
def is_pipeline_test_to_skip(
self,
pipeline_test_case_name,
config_class,
model_architecture,
tokenizer_name,
image_processor_name,
feature_extractor_name,
processor_name,
):
if pipeline_test_case_name == "AudioClassificationPipelineTests":
return True
return False
def setUp(self):
self.model_tester = ASTModelTester(self)
self.config_tester = ConfigTester(self, config_class=ASTConfig, has_text_modality=False, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
@unittest.skip(reason="AST does not use inputs_embeds")
def test_inputs_embeds(self):
pass
def test_model_get_set_embeddings(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
x = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(x, nn.Linear))
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = ["input_values"]
self.assertListEqual(arg_names[:1], expected_arg_names)
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
model_name = "MIT/ast-finetuned-audioset-10-10-0.4593"
model = ASTModel.from_pretrained(model_name)
self.assertIsNotNone(model)
# We will verify our results on some audio from AudioSet
def prepare_audio():
filepath = hf_hub_download(
repo_id="nielsr/audio-spectogram-transformer-checkpoint", filename="sample_audio.flac", repo_type="dataset"
)
audio, sampling_rate = torchaudio.load(filepath)
return audio, sampling_rate
@require_torch
@require_torchaudio
| ASTModelTest |
python | lepture__authlib | authlib/integrations/requests_client/assertion_session.py | {
"start": 446,
"end": 2073
} | class ____(AssertionClient, Session):
"""Constructs a new Assertion Framework for OAuth 2.0 Authorization Grants
per RFC7521_.
.. _RFC7521: https://tools.ietf.org/html/rfc7521
"""
token_auth_class = AssertionAuth
JWT_BEARER_GRANT_TYPE = JWTBearerGrant.GRANT_TYPE
ASSERTION_METHODS = {
JWT_BEARER_GRANT_TYPE: JWTBearerGrant.sign,
}
DEFAULT_GRANT_TYPE = JWT_BEARER_GRANT_TYPE
def __init__(
self,
token_endpoint,
issuer,
subject,
audience=None,
grant_type=None,
claims=None,
token_placement="header",
scope=None,
default_timeout=None,
leeway=60,
**kwargs,
):
Session.__init__(self)
self.default_timeout = default_timeout
update_session_configure(self, kwargs)
AssertionClient.__init__(
self,
session=self,
token_endpoint=token_endpoint,
issuer=issuer,
subject=subject,
audience=audience,
grant_type=grant_type,
claims=claims,
token_placement=token_placement,
scope=scope,
leeway=leeway,
**kwargs,
)
def request(self, method, url, withhold_token=False, auth=None, **kwargs):
"""Send request with auto refresh token feature."""
if self.default_timeout:
kwargs.setdefault("timeout", self.default_timeout)
if not withhold_token and auth is None:
auth = self.token_auth
return super().request(method, url, auth=auth, **kwargs)
| AssertionSession |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 2745,
"end": 4193
} | class ____(BaseLinksSerializer):
_self = serializers.SerializerMethodField()
version = serializers.SerializerMethodField()
project = serializers.SerializerMethodField()
notifications = serializers.SerializerMethodField()
def get__self(self, obj):
path = reverse(
"projects-builds-detail",
kwargs={
"parent_lookup_project__slug": obj.project.slug,
"build_pk": obj.pk,
},
)
return self._absolute_url(path)
def get_version(self, obj):
if obj.version:
path = reverse(
"projects-versions-detail",
kwargs={
"parent_lookup_project__slug": obj.project.slug,
"version_slug": obj.version.slug,
},
)
return self._absolute_url(path)
return None
def get_project(self, obj):
path = reverse(
"projects-detail",
kwargs={
"project_slug": obj.project.slug,
},
)
return self._absolute_url(path)
def get_notifications(self, obj):
path = reverse(
"projects-builds-notifications-list",
kwargs={
"parent_lookup_project__slug": obj.project.slug,
"parent_lookup_build__id": obj.pk,
},
)
return self._absolute_url(path)
| BuildLinksSerializer |
python | ray-project__ray | python/ray/tests/spark/test_basic.py | {
"start": 10054,
"end": 16963
} | class ____:
@classmethod
def setup_class(cls):
cls.spark = (
SparkSession.builder.master("local[2]")
.config("spark.task.cpus", "1")
.config("spark.task.maxFailures", "1")
.getOrCreate()
)
@classmethod
def teardown_class(cls):
time.sleep(10) # Wait all background spark job canceled.
cls.spark.stop()
def test_basic(self):
local_addr, remote_addr = setup_ray_cluster(
max_worker_nodes=2,
head_node_options={"include_dashboard": False},
collect_log_to_path="/tmp/ray_log_collect",
)
for cluster_addr in [local_addr, remote_addr]:
ray.init(address=cluster_addr)
@ray.remote
def f(x):
return x * x
futures = [f.remote(i) for i in range(32)]
results = ray.get(futures)
assert results == [i * i for i in range(32)]
ray.shutdown()
shutdown_ray_cluster()
def test_use_driver_resources(self):
setup_ray_cluster(
max_worker_nodes=1,
num_cpus_head_node=3,
num_gpus_head_node=2,
object_store_memory_head_node=256 * 1024 * 1024,
head_node_options={"include_dashboard": False},
min_worker_nodes=0,
)
ray.init()
head_resources_list = []
for node in ray.nodes():
if node["Alive"] and node["Resources"].get("CPU", 0) == 3:
head_resources_list.append(node["Resources"])
assert len(head_resources_list) == 1
head_resources = head_resources_list[0]
assert head_resources.get("GPU", 0) == 2
shutdown_ray_cluster()
def test_setup_global_ray_cluster(self):
shutil.rmtree("/tmp/ray", ignore_errors=True)
assert ray.util.spark.cluster_init._global_ray_cluster_cancel_event is None
def start_serve_thread():
def serve():
try:
with mock.patch(
"ray.util.spark.cluster_init.get_spark_session",
return_value=self.spark,
):
setup_global_ray_cluster(
max_worker_nodes=1,
min_worker_nodes=0,
)
except BaseException:
# For debugging testing failure.
import traceback
traceback.print_exc()
raise
threading.Thread(target=serve, daemon=True).start()
start_serve_thread()
wait_for_condition(
(
lambda: ray.util.spark.cluster_init._global_ray_cluster_cancel_event
is not None
),
timeout=120,
retry_interval_ms=10000,
)
# assert it uses default temp directory
assert os.path.exists("/tmp/ray")
# assert we can connect to it on client server port 10001
assert (
ray.util.spark.cluster_init._active_ray_cluster.ray_client_server_port
== 10001
)
with mock.patch("ray.util.spark.cluster_init._active_ray_cluster", None):
# assert we cannot create another global mode cluster at a time
with pytest.raises(
ValueError,
match=re.compile(
"Acquiring global lock failed for setting up new global mode "
"Ray on spark cluster"
),
):
setup_global_ray_cluster(
max_worker_nodes=1,
min_worker_nodes=0,
)
# shut down the cluster
ray.util.spark.cluster_init._global_ray_cluster_cancel_event.set()
# assert temp directory is deleted
wait_for_condition(
lambda: not os.path.exists("/tmp/ray"),
timeout=60,
retry_interval_ms=10000,
)
def test_autoscaling_config_generation(self):
from ray.util.spark.cluster_init import AutoscalingCluster
autoscaling_cluster = AutoscalingCluster(
head_resources={
"CPU": 3,
"GPU": 4,
"memory": 10000000,
"object_store_memory": 20000000,
},
worker_node_types={
"ray.worker": {
"resources": {
"CPU": 5,
"GPU": 6,
"memory": 30000000,
"object_store_memory": 40000000,
},
"node_config": {},
"min_workers": 0,
"max_workers": 100,
},
},
extra_provider_config={
"extra_aa": "abc",
"extra_bb": 789,
},
upscaling_speed=2.0,
idle_timeout_minutes=3.0,
)
config = autoscaling_cluster._config
assert config["max_workers"] == 100
assert config["available_node_types"]["ray.head.default"] == {
"resources": {
"CPU": 3,
"GPU": 4,
"memory": 10000000,
"object_store_memory": 20000000,
},
"node_config": {},
"max_workers": 0,
}
assert config["available_node_types"]["ray.worker"] == {
"resources": {
"CPU": 5,
"GPU": 6,
"memory": 30000000,
"object_store_memory": 40000000,
},
"node_config": {},
"min_workers": 0,
"max_workers": 100,
}
assert config["upscaling_speed"] == 2.0
assert config["idle_timeout_minutes"] == 3.0
assert config["provider"]["extra_aa"] == "abc"
assert config["provider"]["extra_bb"] == 789
def test_start_ray_node_in_new_process_group(self):
from ray.util.spark.cluster_init import _start_ray_head_node
proc, _ = _start_ray_head_node(
[
sys.executable,
"-m",
"ray.util.spark.start_ray_node",
"--head",
"--block",
"--port=44335",
],
synchronous=False,
extra_env={
"RAY_ON_SPARK_COLLECT_LOG_TO_PATH": "",
"RAY_ON_SPARK_START_RAY_PARENT_PID": str(os.getpid()),
},
)
time.sleep(10)
# Assert the created Ray head node process has a different
# group id from parent process group id.
assert os.getpgid(proc.pid) != os.getpgrp()
proc.terminate()
if __name__ == "__main__":
sys.exit(pytest.main(["-sv", __file__]))
| TestSparkLocalCluster |
python | realpython__materials | arcade-a-primer/arcade_game.py | {
"start": 614,
"end": 7859
} | class ____(arcade.Window):
"""Space Shooter side scroller game
Player starts on the left, enemies appear on the right
Player can move anywhere, but not off screen
Enemies fly to the left at variable speed
Collisions end the game
"""
def __init__(self, width: int, height: int, title: str):
"""Initialize the game"""
super().__init__(width, height, title)
# Setup the empty sprite lists
self.enemies_list = arcade.SpriteList()
self.clouds_list = arcade.SpriteList()
self.all_sprites = arcade.SpriteList()
def setup(self):
"""Get the game ready to play"""
# Set the background color
arcade.set_background_color(arcade.color.SKY_BLUE)
# Setup the player
self.player = arcade.Sprite("images/jet.png", SCALING)
self.player.center_y = self.height / 2
self.player.left = 10
self.all_sprites.append(self.player)
# Spawn a new enemy every second
arcade.schedule(self.add_enemy, 1.0)
# Spawn a new cloud every 3 seconds
arcade.schedule(self.add_cloud, 3.0)
# Load our background music
# Sound source: http://ccmixter.org/files/Apoxode/59262
# License: https://creativecommons.org/licenses/by/3.0/
self.background_music = arcade.load_sound(
"sounds/Apoxode_-_Electric_1.wav"
)
# Load our other sounds
# Sound sources: Jon Fincher
self.collision_sound = arcade.load_sound("sounds/Collision.wav")
self.move_up_sound = arcade.load_sound("sounds/Rising_putter.wav")
self.move_down_sound = arcade.load_sound("sounds/Falling_putter.wav")
# Start the background music
arcade.play_sound(self.background_music)
# Unpause everything and reset the collision timer
self.paused = False
self.collided = False
self.collision_timer = 0.0
def add_enemy(self, delta_time: float):
"""Adds a new enemy to the screen
Arguments:
delta_time {float} -- How much time has passed since the last call
"""
# First, create the new enemy sprite
enemy = FlyingSprite("images/missile.png", SCALING)
# Set its position to a random height and off screen right
enemy.left = random.randint(self.width, self.width + 10)
enemy.top = random.randint(10, self.height - 10)
# Set its speed to a random speed heading left
enemy.velocity = (random.randint(-200, -50), 0)
# Add it to the enemies list
self.enemies_list.append(enemy)
self.all_sprites.append(enemy)
def add_cloud(self, delta_time: float):
"""Adds a new cloud to the screen
Arguments:
delta_time {float} -- How much time has passed since the last call
"""
# First, create the new cloud sprite
cloud = FlyingSprite("images/cloud.png", SCALING)
# Set its position to a random height and off screen right
cloud.left = random.randint(self.width, self.width + 10)
cloud.top = random.randint(10, self.height - 10)
# Set its speed to a random speed heading left
cloud.velocity = (random.randint(-50, -20), 0)
# Add it to the enemies list
self.clouds_list.append(cloud)
self.all_sprites.append(cloud)
def on_key_press(self, symbol: int, modifiers: int):
"""Handle user keyboard input
Q: Quit the game
P: Pause the game
I/J/K/L: Move Up, Left, Down, Right
Arrows: Move Up, Left, Down, Right
Arguments:
symbol {int} -- Which key was pressed
modifiers {int} -- Which modifiers were pressed
"""
if symbol == arcade.key.Q:
# Quit immediately
arcade.close_window()
if symbol == arcade.key.P:
self.paused = not self.paused
if symbol == arcade.key.I or symbol == arcade.key.UP:
self.player.change_y = 250
arcade.play_sound(self.move_up_sound)
if symbol == arcade.key.K or symbol == arcade.key.DOWN:
self.player.change_y = -250
arcade.play_sound(self.move_down_sound)
if symbol == arcade.key.J or symbol == arcade.key.LEFT:
self.player.change_x = -250
if symbol == arcade.key.L or symbol == arcade.key.RIGHT:
self.player.change_x = 250
def on_key_release(self, symbol: int, modifiers: int):
"""Undo movement vectors when movement keys are released
Arguments:
symbol {int} -- Which key was pressed
modifiers {int} -- Which modifiers were pressed
"""
if (
symbol == arcade.key.I
or symbol == arcade.key.K
or symbol == arcade.key.UP
or symbol == arcade.key.DOWN
):
self.player.change_y = 0
if (
symbol == arcade.key.J
or symbol == arcade.key.L
or symbol == arcade.key.LEFT
or symbol == arcade.key.RIGHT
):
self.player.change_x = 0
def on_update(self, delta_time: float):
"""Update the positions and statuses of all game objects
If we're paused, do nothing
Once everything has moved, check for collisions between
the player and the list of enemies
Arguments:
delta_time {float} -- Time since the last update
"""
# Did we collide with something earlier? If so, update our timer
if self.collided:
self.collision_timer += delta_time
# If we've paused for two seconds, we can quit
if self.collision_timer > 2.0:
arcade.close_window()
# Stop updating things as well
return
# If we're paused, don't update anything
if self.paused:
return
# Did we hit anything? If so, end the game
if self.player.collides_with_list(self.enemies_list):
self.collided = True
self.collision_timer = 0.0
arcade.play_sound(self.collision_sound)
# Update everything
for sprite in self.all_sprites:
sprite.center_x = int(
sprite.center_x + sprite.change_x * delta_time
)
sprite.center_y = int(
sprite.center_y + sprite.change_y * delta_time
)
# self.all_sprites.update()
# Keep the player on screen
if self.player.top > self.height:
self.player.top = self.height
if self.player.right > self.width:
self.player.right = self.width
if self.player.bottom < 0:
self.player.bottom = 0
if self.player.left < 0:
self.player.left = 0
def on_draw(self):
"""Draw all game objects"""
arcade.start_render()
self.all_sprites.draw()
if __name__ == "__main__":
# Create a new Space Shooter window
space_game = SpaceShooter(
int(SCREEN_WIDTH * SCALING), int(SCREEN_HEIGHT * SCALING), SCREEN_TITLE
)
# Setup to play
space_game.setup()
# Run the game
arcade.run()
| SpaceShooter |
python | getsentry__sentry | src/sentry/roles/manager.py | {
"start": 3882,
"end": 7107
} | class ____:
def __init__(
self,
org_config: Iterable[Mapping[str, Any]],
team_config: Iterable[Mapping[str, Any]],
default_org_role: str | None = None,
) -> None:
self.organization_roles: RoleLevel[OrganizationRole] = RoleLevel(
(
OrganizationRole.from_config(self, idx, **role_cfg)
for idx, role_cfg in enumerate(org_config)
),
default_org_role,
)
self.team_roles: RoleLevel[TeamRole] = RoleLevel(
TeamRole.from_config(self, idx, **role_cfg) for idx, role_cfg in enumerate(team_config)
)
self._minimum_team_role_map = self._make_minimum_team_role_map(
self.organization_roles, self.team_roles
)
@staticmethod
def _make_minimum_team_role_map(
organization_roles: RoleLevel[OrganizationRole], team_roles: RoleLevel[TeamRole]
) -> dict[str, str]:
def get_mapped_org_role(team_role: TeamRole) -> OrganizationRole | None:
if team_role.is_minimum_role_for is None:
return None
try:
return organization_roles.get(team_role.is_minimum_role_for)
except KeyError:
warnings.warn(
f"Broken role mapping: {team_role.id}.is_minimum_role_for = {team_role.is_minimum_role_for}"
)
return None
def get_highest_available_team_role(org_role: OrganizationRole) -> TeamRole:
if org_role is organization_roles.get_top_dog():
return team_roles.get_top_dog()
for team_role in reversed(team_roles.get_all()):
mapped_org_role = get_mapped_org_role(team_role)
if mapped_org_role and mapped_org_role.priority <= org_role.priority:
return team_role
return team_roles.get_default()
return {
org_role.id: get_highest_available_team_role(org_role).id
for org_role in organization_roles.get_all()
}
def __iter__(self) -> Iterable[OrganizationRole]:
yield from self.organization_roles.get_all()
def can_manage(self, role: str, other: str) -> bool:
return self.organization_roles.can_manage(role, other)
def get(self, id: str) -> OrganizationRole:
return self.organization_roles.get(id)
def get_all(self) -> Sequence[OrganizationRole]:
return self.organization_roles.get_all()
def get_choices(self) -> Sequence[tuple[str, str]]:
return self.organization_roles.get_choices()
def get_default(self) -> OrganizationRole:
return self.organization_roles.get_default()
def get_top_dog(self) -> OrganizationRole:
return self.organization_roles.get_top_dog()
def with_scope(self, scope: str) -> Iterable[OrganizationRole]:
return self.organization_roles.with_scope(scope)
def with_any_scope(self, scopes: Iterable[str]) -> Iterable[OrganizationRole]:
return self.organization_roles.with_any_scope(scopes)
def get_minimum_team_role(self, org_role: str) -> TeamRole:
return self.team_roles.get(self._minimum_team_role_map[org_role])
| RoleManager |
python | huggingface__transformers | src/transformers/models/moonshine/modeling_moonshine.py | {
"start": 16381,
"end": 18371
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MoonshineConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MoonshineAttention(
config=config,
layer_idx=layer_idx,
is_causal=False,
num_attention_heads=config.encoder_num_attention_heads,
num_key_value_heads=config.encoder_num_key_value_heads,
)
self.mlp = MoonshineEncoderMLP(config, config.encoder_hidden_act)
self.input_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
self.post_attention_layernorm = nn.LayerNorm(config.hidden_size, bias=False)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
| MoonshineEncoderLayer |
python | ray-project__ray | python/ray/_private/external_storage.py | {
"start": 15238,
"end": 20582
} | class ____(ExternalStorage):
"""The external storage class implemented by smart_open.
(https://github.com/RaRe-Technologies/smart_open)
Smart open supports multiple backend with the same APIs.
To use this implementation, you should pre-create the given uri.
For example, if your uri is a local file path, you should pre-create
the directory.
Args:
uri: Storage URI used for smart open.
prefix: Prefix of objects that are stored.
override_transport_params: Overriding the default value of
transport_params for smart-open library.
Raises:
ModuleNotFoundError: If it fails to setup.
For example, if smart open library
is not downloaded, this will fail.
"""
def __init__(
self,
node_id: str,
uri: str or list,
override_transport_params: dict = None,
buffer_size=1024 * 1024, # For remote spilling, at least 1MB is recommended.
):
super().__init__()
try:
from smart_open import open # noqa
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
"Smart open is chosen to be a object spilling "
"external storage, but smart_open and boto3 "
f"is not downloaded. Original error: {e}"
)
# Validation
assert uri is not None, "uri should be provided to use object spilling."
if isinstance(uri, str):
uri = [uri]
assert isinstance(uri, list), "uri must be a single string or list of strings."
assert isinstance(buffer_size, int), "buffer_size must be an integer."
uri_is_s3 = [u.startswith("s3://") for u in uri]
self.is_for_s3 = all(uri_is_s3)
if not self.is_for_s3:
assert not any(uri_is_s3), "all uri's must be s3 or none can be s3."
self._uris = uri
else:
self._uris = [u.strip("/") for u in uri]
assert len(self._uris) == len(uri)
self._current_uri_index = random.randrange(0, len(self._uris))
self.prefix = f"{DEFAULT_OBJECT_PREFIX}_{node_id}"
self.override_transport_params = override_transport_params or {}
if self.is_for_s3:
import boto3 # noqa
# Setup boto3. It is essential because if we don't create boto
# session, smart_open will create a new session for every
# open call.
self.s3 = boto3.resource(service_name="s3")
# smart_open always seek to 0 if we don't set this argument.
# This will lead us to call a Object.get when it is not necessary,
# so defer seek and call seek before reading objects instead.
self.transport_params = {
"defer_seek": True,
"resource": self.s3,
"buffer_size": buffer_size,
}
else:
self.transport_params = {}
self.transport_params.update(self.override_transport_params)
def spill_objects(self, object_refs, owner_addresses) -> List[str]:
if len(object_refs) == 0:
return []
from smart_open import open
# Choose the current uri by round robin order.
self._current_uri_index = (self._current_uri_index + 1) % len(self._uris)
uri = self._uris[self._current_uri_index]
key = f"{self.prefix}-{_get_unique_spill_filename(object_refs)}"
url = f"{uri}/{key}"
with open(
url,
mode="wb",
transport_params=self.transport_params,
) as file_like:
return self._write_multiple_objects(
file_like, object_refs, owner_addresses, url
)
def restore_spilled_objects(
self, object_refs: List[ObjectRef], url_with_offset_list: List[str]
):
from smart_open import open
total = 0
for i in range(len(object_refs)):
object_ref = object_refs[i]
url_with_offset = url_with_offset_list[i].decode()
# Retrieve the information needed.
parsed_result = parse_url_with_offset(url_with_offset)
base_url = parsed_result.base_url
offset = parsed_result.offset
with open(base_url, "rb", transport_params=self.transport_params) as f:
# smart open seek reads the file from offset-end_of_the_file
# when the seek is called.
f.seek(offset)
address_len = int.from_bytes(f.read(8), byteorder="little")
metadata_len = int.from_bytes(f.read(8), byteorder="little")
buf_len = int.from_bytes(f.read(8), byteorder="little")
self._size_check(address_len, metadata_len, buf_len, parsed_result.size)
owner_address = f.read(address_len)
total += buf_len
metadata = f.read(metadata_len)
# read remaining data to our buffer
self._put_object_to_store(
metadata, buf_len, f, object_ref, owner_address
)
return total
def delete_spilled_objects(self, urls: List[str]):
pass
def destroy_external_storage(self):
pass
_external_storage = NullStorage()
| ExternalStorageSmartOpenImpl |
python | run-llama__llama_index | llama-index-core/llama_index/core/selectors/pydantic_selectors.py | {
"start": 1366,
"end": 3325
} | class ____(BaseSelector):
def __init__(self, selector_program: BasePydanticProgram) -> None:
self._selector_program = selector_program
@classmethod
def from_defaults(
cls,
program: Optional[BasePydanticProgram] = None,
llm: Optional["OpenAI"] = None,
prompt_template_str: str = DEFAULT_SINGLE_PYD_SELECT_PROMPT_TMPL,
verbose: bool = False,
) -> "PydanticSingleSelector":
if program is None:
program = FunctionCallingProgram.from_defaults(
output_cls=SingleSelection,
prompt_template_str=prompt_template_str,
llm=llm,
verbose=verbose,
)
return cls(selector_program=program)
def _get_prompts(self) -> Dict[str, Any]:
"""Get prompts."""
# TODO: no accessible prompts for a base pydantic program
return {}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
def _select(
self, choices: Sequence[ToolMetadata], query: QueryBundle
) -> SelectorResult:
# prepare input
choices_text = _build_choices_text(choices)
# predict
prediction = self._selector_program(
num_choices=len(choices),
context_list=choices_text,
query_str=query.query_str,
)
# parse output
return _pydantic_output_to_selector_result(prediction)
async def _aselect(
self, choices: Sequence[ToolMetadata], query: QueryBundle
) -> SelectorResult:
# prepare input
choices_text = _build_choices_text(choices)
# predict
prediction = await self._selector_program.acall(
num_choices=len(choices),
context_list=choices_text,
query_str=query.query_str,
)
# parse output
return _pydantic_output_to_selector_result(prediction)
| PydanticSingleSelector |
python | spack__spack | lib/spack/spack/hooks/__init__.py | {
"start": 794,
"end": 2329
} | class ____:
#: Order in which hooks are executed
HOOK_ORDER = [
"spack.hooks.module_file_generation",
"spack.hooks.licensing",
"spack.hooks.sbang",
"spack.hooks.windows_runtime_linkage",
"spack.hooks.drop_redundant_rpaths",
"spack.hooks.absolutify_elf_sonames",
"spack.hooks.permissions_setters",
"spack.hooks.resolve_shared_libraries",
# after all mutations to the install prefix, write metadata
"spack.hooks.write_install_manifest",
# after all metadata is written
"spack.hooks.autopush",
]
#: Contains all hook modules after first call, shared among all HookRunner objects
_hooks: Optional[List[types.ModuleType]] = None
def __init__(self, hook_name):
self.hook_name = hook_name
@property
def hooks(self) -> List[types.ModuleType]:
if not self._hooks:
self._hooks = [importlib.import_module(module_name) for module_name in self.HOOK_ORDER]
return self._hooks
def __call__(self, *args, **kwargs):
for module in self.hooks:
if hasattr(module, self.hook_name):
hook = getattr(module, self.hook_name)
if hasattr(hook, "__call__"):
hook(*args, **kwargs)
# pre/post install and run by the install subprocess
pre_install = _HookRunner("pre_install")
post_install = _HookRunner("post_install")
pre_uninstall = _HookRunner("pre_uninstall")
post_uninstall = _HookRunner("post_uninstall")
| _HookRunner |
python | apache__thrift | lib/py/src/transport/TTwisted.py | {
"start": 9668,
"end": 10904
} | class ____(resource.Resource):
allowedMethods = ('POST',)
def __init__(self, processor, inputProtocolFactory,
outputProtocolFactory=None):
resource.Resource.__init__(self)
self.inputProtocolFactory = inputProtocolFactory
if outputProtocolFactory is None:
self.outputProtocolFactory = inputProtocolFactory
else:
self.outputProtocolFactory = outputProtocolFactory
self.processor = processor
def getChild(self, path, request):
return self
def _cbProcess(self, _, request, tmo):
msg = tmo.getvalue()
request.setResponseCode(http.OK)
request.setHeader("content-type", "application/x-thrift")
request.write(msg)
request.finish()
def render_POST(self, request):
request.content.seek(0, 0)
data = request.content.read()
tmi = TTransport.TMemoryBuffer(data)
tmo = TTransport.TMemoryBuffer()
iprot = self.inputProtocolFactory.getProtocol(tmi)
oprot = self.outputProtocolFactory.getProtocol(tmo)
d = self.processor.process(iprot, oprot)
d.addCallback(self._cbProcess, request, tmo)
return server.NOT_DONE_YET
| ThriftResource |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 73793,
"end": 74237
} | class ____:
def __init__(
self,
schedule_ref: _PipelineSchedule,
arg_mbs: list[tuple] | None = None,
kwarg_mbs: list[dict] | None = None,
target_mbs: list | None = None,
losses: list | None = None,
):
self.schedule_ref = schedule_ref
self.arg_mbs = arg_mbs
self.kwarg_mbs = kwarg_mbs
self.target_mbs = target_mbs
self.losses = losses
| _PipelineContext |
python | django__django | tests/migrations/test_migrations_squashed_complex_multi_apps/app2/1_squashed_2.py | {
"start": 35,
"end": 262
} | class ____(migrations.Migration):
replaces = [
("app2", "1_auto"),
("app2", "2_auto"),
]
dependencies = [("app1", "1_auto")]
operations = [migrations.RunPython(migrations.RunPython.noop)]
| Migration |
python | pytorch__pytorch | torch/_inductor/mkldnn_ir.py | {
"start": 42088,
"end": 43615
} | class ____(ExternKernelAlloc):
def __init__(
self,
layout,
inputs,
constant_args=(),
) -> None:
"""
inputs = [x, w, qGroupSize, qScalesAndZeros]
constant_args = ()
"""
assert len(inputs) == 4
assert len(constant_args) == 0
super().__init__(
layout,
inputs,
constant_args,
None,
op_overload=(torch.ops.quantized.int4mm_packed_weight_cpu.default),
cpp_kernel_name=("aoti_torch_cpu__weight_int4pack_mm_cpu_tensor"),
)
def codegen(self, wrapper):
wrapper.include_extra_header("torch/csrc/inductor/aoti_torch/c/shim_cpu.h")
super().codegen(wrapper)
if isinstance(self.layout, Layout):
self.codegen_size_asserts(wrapper)
@classmethod
def create(
cls,
x: "TensorBox",
w: "TensorBox",
qGroupSize: "TensorBox",
qScalesAndZeros: "TensorBox",
):
inputs = [x, w, qGroupSize, qScalesAndZeros]
*m, _ = x.get_size()
n, _ = w.get_size()
output_size = list(m) + [n]
output_stride = FlexibleLayout.contiguous_strides(output_size)
kernel_layout = FixedLayout(
x.get_device(), # type: ignore[arg-type]
x.get_dtype(),
output_size,
output_stride,
)
return WeightInt4PackMatmul(
layout=kernel_layout,
inputs=inputs,
)
| WeightInt4PackMatmul |
python | tqdm__tqdm | tqdm/std.py | {
"start": 1985,
"end": 3938
} | class ____(object):
"""
Provide a default write lock for thread and multiprocessing safety.
Works only on platforms supporting `fork` (so Windows is excluded).
You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
before forking in order for the write lock to work.
On Windows, you need to supply the lock from the parent to the children as
an argument to joblib or the parallelism lib you use.
"""
# global thread lock so no setup required for multithreading.
# NB: Do not create multiprocessing lock as it sets the multiprocessing
# context, disallowing `spawn()`/`forkserver()`
th_lock = TRLock()
def __init__(self):
# Create global parallelism locks to avoid racing issues with parallel
# bars works only if fork available (Linux/MacOSX, but not Windows)
cls = type(self)
root_lock = cls.th_lock
if root_lock is not None:
root_lock.acquire()
cls.create_mp_lock()
self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
if root_lock is not None:
root_lock.release()
def acquire(self, *a, **k):
for lock in self.locks:
lock.acquire(*a, **k)
def release(self):
for lock in self.locks[::-1]: # Release in inverse order of acquisition
lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, *exc):
self.release()
@classmethod
def create_mp_lock(cls):
if not hasattr(cls, 'mp_lock'):
try:
from multiprocessing import RLock
cls.mp_lock = RLock()
except (ImportError, OSError): # pragma: no cover
cls.mp_lock = None
@classmethod
def create_th_lock(cls):
assert hasattr(cls, 'th_lock')
warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
| TqdmDefaultWriteLock |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 37769,
"end": 38156
} | class ____(ExprNode):
__slots__ = ("value",)
def validate(self):
if not isinstance(self.value, Call):
# TODO: investigate wrong col_offset for `self.value`
raise StructureException(
"`extcall` must be followed by a function call",
self.value,
hint="did you forget parentheses?",
)
| ExtCall |
python | pytorch__pytorch | test/dynamo/cpython/3_13/seq_tests.py | {
"start": 1813,
"end": 1976
} | class ____:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
| Sequence |
python | getsentry__responses | responses/tests/test_responses.py | {
"start": 70111,
"end": 73005
} | class ____:
def test_strict_wrapper(self):
"""Test that assert_all_requests_are_fired could be applied to the decorator."""
@responses.activate(assert_all_requests_are_fired=True)
def run_strict():
responses.add(responses.GET, "https://someapi1.com/", "success")
responses.add(responses.GET, "https://notcalled1.com/", "success")
requests.get("https://someapi1.com/")
assert responses.mock.assert_all_requests_are_fired
@responses.activate(assert_all_requests_are_fired=False)
def run_not_strict():
responses.add(responses.GET, "https://someapi2.com/", "success")
responses.add(responses.GET, "https://notcalled2.com/", "success")
requests.get("https://someapi2.com/")
assert not responses.mock.assert_all_requests_are_fired
@responses.activate
def run_classic():
responses.add(responses.GET, "https://someapi3.com/", "success")
responses.add(responses.GET, "https://notcalled3.com/", "success")
requests.get("https://someapi3.com/")
assert not responses.mock.assert_all_requests_are_fired
# keep the order of function calls to ensure that decorator doesn't leak to another function
with pytest.raises(AssertionError) as exc_info:
run_strict()
# check that one URL is in uncalled assertion
assert "https://notcalled1.com/" in str(exc_info.value)
run_classic()
run_not_strict()
@pytest.mark.parametrize("assert_fired", (True, False, None))
def test_nested_decorators(self, assert_fired): # type: ignore[misc]
"""Validate if assert_all_requests_are_fired is applied from the correct function.
assert_all_requests_are_fired must be applied from the function
where call to 'requests' is done.
Test matrix of True/False/None values applied to validate different scenarios.
"""
@responses.activate(assert_all_requests_are_fired=assert_fired)
def wrapped():
responses.add(responses.GET, "https://notcalled1.com/", "success")
responses.add(responses.GET, "http://example.com/1", body="Hello 1")
assert b"Hello 1" == requests.get("http://example.com/1").content
@responses.activate(assert_all_requests_are_fired=not assert_fired)
def call_another_wrapped_function():
responses.add(responses.GET, "https://notcalled2.com/", "success")
wrapped()
if assert_fired:
with pytest.raises(AssertionError) as exc_info:
call_another_wrapped_function()
assert "https://notcalled1.com/" in str(exc_info.value)
assert "https://notcalled2.com/" in str(exc_info.value)
else:
call_another_wrapped_function()
| TestStrictWrapper |
python | django__django | tests/mail/tests.py | {
"start": 103849,
"end": 105296
} | class ____(BaseEmailBackendTests, SimpleTestCase):
email_backend = "django.core.mail.backends.locmem.EmailBackend"
def get_mailbox_content(self):
return [m.message() for m in mail.outbox]
def flush_mailbox(self):
mail.outbox = []
def tearDown(self):
super().tearDown()
mail.outbox = []
def test_locmem_shared_messages(self):
"""
Make sure that the locmen backend populates the outbox.
"""
connection = locmem.EmailBackend()
connection2 = locmem.EmailBackend()
email = EmailMessage(to=["to@example.com"])
connection.send_messages([email])
connection2.send_messages([email])
self.assertEqual(len(mail.outbox), 2)
def test_validate_multiline_headers(self):
# Ticket #18861 - Validate emails when using the locmem backend
with self.assertRaises(ValueError):
send_mail(
"Subject\nMultiline", "Content", "from@example.com", ["to@example.com"]
)
def test_outbox_not_mutated_after_send(self):
email = EmailMessage(
subject="correct subject",
to=["to@example.com"],
)
email.send()
email.subject = "other subject"
email.to.append("other@example.com")
self.assertEqual(mail.outbox[0].subject, "correct subject")
self.assertEqual(mail.outbox[0].to, ["to@example.com"])
| LocmemBackendTests |
python | huggingface__transformers | src/transformers/models/biogpt/modeling_biogpt.py | {
"start": 4682,
"end": 10280
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Optional[BioGptConfig] = None,
layer_idx: Optional[int] = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
self.config = config
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
if layer_idx is None and self.is_decoder:
logger.warning_once(
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
"when creating this class."
)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
cache_position: Optional[torch.Tensor] = None,
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
# determine input shapes
bsz, tgt_len = hidden_states.shape[:-1]
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
kv_input_shape = (bsz, src_len, -1, self.head_dim)
# get query proj
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
is_updated = False
if past_key_values is not None:
if isinstance(past_key_values, EncoderDecoderCache):
is_updated = past_key_values.is_updated.get(self.layer_idx)
if is_cross_attention:
# after the first generated id, we can subsequently re-use all key/value_states from cache
curr_past_key_values = past_key_values.cross_attention_cache
else:
curr_past_key_values = past_key_values.self_attention_cache
else:
curr_past_key_values = past_key_values
current_states = key_value_states if is_cross_attention else hidden_states
if is_cross_attention and past_key_values is not None and is_updated:
# reuse k,v, cross_attentions
key_states = curr_past_key_values.layers[self.layer_idx].keys
value_states = curr_past_key_values.layers[self.layer_idx].values
else:
key_states = self.k_proj(current_states)
value_states = self.v_proj(current_states)
key_states = key_states.view(*kv_input_shape).transpose(1, 2)
value_states = value_states.view(*kv_input_shape).transpose(1, 2)
if past_key_values is not None:
# save all key/value_states to cache to be re-used for fast auto-regressive generation
cache_position = cache_position if not is_cross_attention else None
key_states, value_states = curr_past_key_values.update(
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
)
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
past_key_values.is_updated[self.layer_idx] = True
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
output_attentions=output_attentions,
**kwargs,
)
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
| BioGptAttention |
python | rq__rq | tests/test_scheduler.py | {
"start": 967,
"end": 6451
} | class ____(RQTestCase):
def test_get_jobs_to_enqueue(self):
"""Getting job ids to enqueue from ScheduledJobRegistry."""
queue = Queue(connection=self.connection)
registry = ScheduledJobRegistry(queue=queue)
timestamp = current_timestamp()
self.connection.zadd(registry.key, {'foo': 1})
self.connection.zadd(registry.key, {'bar': timestamp + 10})
self.connection.zadd(registry.key, {'baz': timestamp + 30})
self.assertEqual(registry.get_jobs_to_enqueue(), ['foo'])
self.assertEqual(registry.get_jobs_to_enqueue(timestamp + 20), ['foo', 'bar'])
def test_get_jobs_to_schedule_with_chunk_size(self):
"""Max amount of jobs returns by get_jobs_to_schedule() equal to chunk_size"""
queue = Queue(connection=self.connection)
registry = ScheduledJobRegistry(queue=queue)
timestamp = current_timestamp()
chunk_size = 5
for index in range(0, chunk_size * 2):
self.connection.zadd(registry.key, {f'foo_{index}': 1})
self.assertEqual(len(registry.get_jobs_to_schedule(timestamp, chunk_size)), chunk_size)
self.assertEqual(len(registry.get_jobs_to_schedule(timestamp, chunk_size * 2)), chunk_size * 2)
def test_get_scheduled_time(self):
"""get_scheduled_time() returns job's scheduled datetime"""
queue = Queue(connection=self.connection)
registry = ScheduledJobRegistry(queue=queue)
job = Job.create('myfunc', connection=self.connection)
job.save()
dt = datetime(2019, 1, 1, tzinfo=timezone.utc)
registry.schedule(job, datetime(2019, 1, 1, tzinfo=timezone.utc))
self.assertEqual(registry.get_scheduled_time(job), dt)
# get_scheduled_time() should also work with job ID
self.assertEqual(registry.get_scheduled_time(job.id), dt)
# registry.get_scheduled_time() raises NoSuchJobError if
# job.id is not found
self.assertRaises(NoSuchJobError, registry.get_scheduled_time, '123')
def test_schedule(self):
"""Adding job with the correct score to ScheduledJobRegistry"""
queue = Queue(connection=self.connection)
job = Job.create('myfunc', connection=self.connection)
job.save()
registry = ScheduledJobRegistry(queue=queue)
from datetime import timezone
# If we pass in a datetime with no timezone, `schedule()`
# assumes local timezone so depending on your local timezone,
# the timestamp maybe different
#
# we need to account for the difference between a timezone
# with DST active and without DST active. The time.timezone
# property isn't accurate when time.daylight is non-zero,
# we'll test both.
#
# first, time.daylight == 0 (not in DST).
# mock the sitatuoin for American/New_York not in DST (UTC - 5)
# time.timezone = 18000
# time.daylight = 0
# time.altzone = 14400
mock_day = mock.patch('time.daylight', 0)
mock_tz = mock.patch('time.timezone', 18000)
mock_atz = mock.patch('time.altzone', 14400)
with mock_tz, mock_day, mock_atz:
registry.schedule(job, datetime(2019, 1, 1))
self.assertEqual(
self.connection.zscore(registry.key, job.id), 1546300800 + 18000
) # 2019-01-01 UTC in Unix timestamp
# second, time.daylight != 0 (in DST)
# mock the sitatuoin for American/New_York not in DST (UTC - 4)
# time.timezone = 18000
# time.daylight = 1
# time.altzone = 14400
mock_day = mock.patch('time.daylight', 1)
mock_tz = mock.patch('time.timezone', 18000)
mock_atz = mock.patch('time.altzone', 14400)
with mock_tz, mock_day, mock_atz:
registry.schedule(job, datetime(2019, 1, 1))
self.assertEqual(
self.connection.zscore(registry.key, job.id), 1546300800 + 14400
) # 2019-01-01 UTC in Unix timestamp
# Score is always stored in UTC even if datetime is in a different tz
tz = timezone(timedelta(hours=7))
job = Job.create('myfunc', connection=self.connection)
job.save()
registry.schedule(job, datetime(2019, 1, 1, 7, tzinfo=tz))
self.assertEqual(
self.connection.zscore(registry.key, job.id), 1546300800
) # 2019-01-01 UTC in Unix timestamp
def test_remove_jobs(self):
"""Removing job ids from ScheduledJobRegistry. Will be deprecated in the future."""
queue = Queue(connection=self.connection)
registry = ScheduledJobRegistry(queue=queue)
timestamp = current_timestamp()
self.connection.zadd(registry.key, {'foo': 1})
self.connection.zadd(registry.key, {'bar': timestamp + 10})
self.connection.zadd(registry.key, {'baz': timestamp + 30})
with pytest.deprecated_call():
# without timestamp it should remove everything till the current timestamp
registry.remove_jobs()
self.assertListEqual(registry.get_jobs_to_schedule(timestamp=timestamp + 100), ['bar', 'baz'])
registry.remove_jobs(timestamp=timestamp + 15)
# should remove bar job
self.assertListEqual(registry.get_jobs_to_schedule(timestamp=timestamp + 100), ['baz'])
| TestScheduledJobRegistry |
python | gevent__gevent | src/greentest/3.14/test_threading_local.py | {
"start": 6520,
"end": 6606
} | class ____(unittest.TestCase, BaseLocalTest):
_local = _thread._local
| ThreadLocalTest |
python | gevent__gevent | src/greentest/3.9/test_ssl.py | {
"start": 44571,
"end": 74745
} | class ____(unittest.TestCase):
def test_constructor(self):
for protocol in PROTOCOLS:
if has_tls_protocol(protocol):
with warnings_helper.check_warnings():
ctx = ssl.SSLContext(protocol)
self.assertEqual(ctx.protocol, protocol)
with warnings_helper.check_warnings():
ctx = ssl.SSLContext()
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertRaises(ValueError, ssl.SSLContext, -1)
self.assertRaises(ValueError, ssl.SSLContext, 42)
def test_protocol(self):
for proto in PROTOCOLS:
if has_tls_protocol(proto):
with warnings_helper.check_warnings():
ctx = ssl.SSLContext(proto)
self.assertEqual(ctx.protocol, proto)
def test_ciphers(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.set_ciphers("ALL")
ctx.set_ciphers("DEFAULT")
with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
ctx.set_ciphers("^$:,;?*'dorothyx")
@unittest.skipUnless(PY_SSL_DEFAULT_CIPHERS == 1,
"Test applies only to Python default ciphers")
def test_python_ciphers(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ciphers = ctx.get_ciphers()
for suite in ciphers:
name = suite['name']
self.assertNotIn("PSK", name)
self.assertNotIn("SRP", name)
self.assertNotIn("MD5", name)
self.assertNotIn("RC4", name)
self.assertNotIn("3DES", name)
@unittest.skipIf(ssl.OPENSSL_VERSION_INFO < (1, 0, 2, 0, 0), 'OpenSSL too old')
def test_get_ciphers(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.set_ciphers('AESGCM')
names = set(d['name'] for d in ctx.get_ciphers())
expected = {
'AES128-GCM-SHA256',
'ECDHE-ECDSA-AES128-GCM-SHA256',
'ECDHE-RSA-AES128-GCM-SHA256',
'DHE-RSA-AES128-GCM-SHA256',
'AES256-GCM-SHA384',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES256-GCM-SHA384',
'DHE-RSA-AES256-GCM-SHA384',
}
intersection = names.intersection(expected)
self.assertGreaterEqual(
len(intersection), 2, f"\ngot: {sorted(names)}\nexpected: {sorted(expected)}"
)
def test_options(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# OP_ALL | OP_NO_SSLv2 | OP_NO_SSLv3 is the default value
default = (ssl.OP_ALL | ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3)
# SSLContext also enables these by default
default |= (OP_NO_COMPRESSION | OP_CIPHER_SERVER_PREFERENCE |
OP_SINGLE_DH_USE | OP_SINGLE_ECDH_USE |
OP_ENABLE_MIDDLEBOX_COMPAT |
OP_IGNORE_UNEXPECTED_EOF)
self.assertEqual(default, ctx.options)
ctx.options |= ssl.OP_NO_TLSv1
self.assertEqual(default | ssl.OP_NO_TLSv1, ctx.options)
if can_clear_options():
ctx.options = (ctx.options & ~ssl.OP_NO_TLSv1)
self.assertEqual(default, ctx.options)
ctx.options = 0
# Ubuntu has OP_NO_SSLv3 forced on by default
self.assertEqual(0, ctx.options & ~ssl.OP_NO_SSLv3)
else:
with self.assertRaises(ValueError):
ctx.options = 0
def test_verify_mode_protocol(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
# Default value
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
ctx.verify_mode = ssl.CERT_OPTIONAL
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL)
ctx.verify_mode = ssl.CERT_REQUIRED
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
ctx.verify_mode = ssl.CERT_NONE
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
with self.assertRaises(TypeError):
ctx.verify_mode = None
with self.assertRaises(ValueError):
ctx.verify_mode = 42
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
self.assertFalse(ctx.check_hostname)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
self.assertTrue(ctx.check_hostname)
def test_hostname_checks_common_name(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertTrue(ctx.hostname_checks_common_name)
if ssl.HAS_NEVER_CHECK_COMMON_NAME:
ctx.hostname_checks_common_name = True
self.assertTrue(ctx.hostname_checks_common_name)
ctx.hostname_checks_common_name = False
self.assertFalse(ctx.hostname_checks_common_name)
ctx.hostname_checks_common_name = True
self.assertTrue(ctx.hostname_checks_common_name)
else:
with self.assertRaises(AttributeError):
ctx.hostname_checks_common_name = True
@requires_minimum_version
@unittest.skipIf(IS_LIBRESSL, "see bpo-34001")
def test_min_max_version(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# OpenSSL default is MINIMUM_SUPPORTED, however some vendors like
# Fedora override the setting to TLS 1.0.
minimum_range = {
# stock OpenSSL
ssl.TLSVersion.MINIMUM_SUPPORTED,
# Fedora 29 uses TLS 1.0 by default
ssl.TLSVersion.TLSv1,
# RHEL 8 uses TLS 1.2 by default
ssl.TLSVersion.TLSv1_2
}
maximum_range = {
# stock OpenSSL
ssl.TLSVersion.MAXIMUM_SUPPORTED,
# Fedora 32 uses TLS 1.3 by default
ssl.TLSVersion.TLSv1_3
}
self.assertIn(
ctx.minimum_version, minimum_range
)
self.assertIn(
ctx.maximum_version, maximum_range
)
ctx.minimum_version = ssl.TLSVersion.TLSv1_1
ctx.maximum_version = ssl.TLSVersion.TLSv1_2
self.assertEqual(
ctx.minimum_version, ssl.TLSVersion.TLSv1_1
)
self.assertEqual(
ctx.maximum_version, ssl.TLSVersion.TLSv1_2
)
ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED
ctx.maximum_version = ssl.TLSVersion.TLSv1
self.assertEqual(
ctx.minimum_version, ssl.TLSVersion.MINIMUM_SUPPORTED
)
self.assertEqual(
ctx.maximum_version, ssl.TLSVersion.TLSv1
)
ctx.maximum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED
self.assertEqual(
ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED
)
ctx.maximum_version = ssl.TLSVersion.MINIMUM_SUPPORTED
self.assertIn(
ctx.maximum_version,
{ssl.TLSVersion.TLSv1, ssl.TLSVersion.TLSv1_1, ssl.TLSVersion.SSLv3}
)
ctx.minimum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED
self.assertIn(
ctx.minimum_version,
{ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_3}
)
with self.assertRaises(ValueError):
ctx.minimum_version = 42
if has_tls_protocol(ssl.PROTOCOL_TLSv1_1):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1)
self.assertIn(
ctx.minimum_version, minimum_range
)
self.assertEqual(
ctx.maximum_version, ssl.TLSVersion.MAXIMUM_SUPPORTED
)
with self.assertRaises(ValueError):
ctx.minimum_version = ssl.TLSVersion.MINIMUM_SUPPORTED
with self.assertRaises(ValueError):
ctx.maximum_version = ssl.TLSVersion.TLSv1
@unittest.skipUnless(have_verify_flags(),
"verify_flags need OpenSSL > 0.9.8")
def test_verify_flags(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# default value
tf = getattr(ssl, "VERIFY_X509_TRUSTED_FIRST", 0)
self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT | tf)
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF
self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_LEAF)
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN
self.assertEqual(ctx.verify_flags, ssl.VERIFY_CRL_CHECK_CHAIN)
ctx.verify_flags = ssl.VERIFY_DEFAULT
self.assertEqual(ctx.verify_flags, ssl.VERIFY_DEFAULT)
# supports any value
ctx.verify_flags = ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT
self.assertEqual(ctx.verify_flags,
ssl.VERIFY_CRL_CHECK_LEAF | ssl.VERIFY_X509_STRICT)
with self.assertRaises(TypeError):
ctx.verify_flags = None
def test_load_cert_chain(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# Combined key and cert in a single file
ctx.load_cert_chain(CERTFILE, keyfile=None)
ctx.load_cert_chain(CERTFILE, keyfile=CERTFILE)
self.assertRaises(TypeError, ctx.load_cert_chain, keyfile=CERTFILE)
with self.assertRaises(OSError) as cm:
ctx.load_cert_chain(NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(BADCERT)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(EMPTYCERT)
# Separate key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain(ONLYCERT, ONLYKEY)
ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYCERT)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(ONLYKEY)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)
# Mismatching key and cert
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"):
ctx.load_cert_chain(CAFILE_CACERT, ONLYKEY)
# Password protected key and cert
ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD)
ctx.load_cert_chain(CERTFILE_PROTECTED, password=KEY_PASSWORD.encode())
ctx.load_cert_chain(CERTFILE_PROTECTED,
password=bytearray(KEY_PASSWORD.encode()))
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD)
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED, KEY_PASSWORD.encode())
ctx.load_cert_chain(ONLYCERT, ONLYKEY_PROTECTED,
bytearray(KEY_PASSWORD.encode()))
with self.assertRaisesRegex(TypeError, "should be a string"):
ctx.load_cert_chain(CERTFILE_PROTECTED, password=True)
with self.assertRaises(ssl.SSLError):
ctx.load_cert_chain(CERTFILE_PROTECTED, password="badpass")
with self.assertRaisesRegex(ValueError, "cannot be longer"):
# openssl has a fixed limit on the password buffer.
# PEM_BUFSIZE is generally set to 1kb.
# Return a string larger than this.
ctx.load_cert_chain(CERTFILE_PROTECTED, password=b'a' * 102400)
# Password callback
def getpass_unicode():
return KEY_PASSWORD
def getpass_bytes():
return KEY_PASSWORD.encode()
def getpass_bytearray():
return bytearray(KEY_PASSWORD.encode())
def getpass_badpass():
return "badpass"
def getpass_huge():
return b'a' * (1024 * 1024)
def getpass_bad_type():
return 9
def getpass_exception():
raise Exception('getpass error')
class GetPassCallable:
def __call__(self):
return KEY_PASSWORD
def getpass(self):
return KEY_PASSWORD
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_unicode)
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytes)
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bytearray)
ctx.load_cert_chain(CERTFILE_PROTECTED, password=GetPassCallable())
ctx.load_cert_chain(CERTFILE_PROTECTED,
password=GetPassCallable().getpass)
with self.assertRaises(ssl.SSLError):
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_badpass)
with self.assertRaisesRegex(ValueError, "cannot be longer"):
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_huge)
with self.assertRaisesRegex(TypeError, "must return a string"):
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_bad_type)
with self.assertRaisesRegex(Exception, "getpass error"):
ctx.load_cert_chain(CERTFILE_PROTECTED, password=getpass_exception)
# Make sure the password function isn't called if it isn't needed
ctx.load_cert_chain(CERTFILE, password=getpass_exception)
def test_load_verify_locations(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_verify_locations(CERTFILE)
ctx.load_verify_locations(cafile=CERTFILE, capath=None)
ctx.load_verify_locations(BYTES_CERTFILE)
ctx.load_verify_locations(cafile=BYTES_CERTFILE, capath=None)
self.assertRaises(TypeError, ctx.load_verify_locations)
self.assertRaises(TypeError, ctx.load_verify_locations, None, None, None)
with self.assertRaises(OSError) as cm:
ctx.load_verify_locations(NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
ctx.load_verify_locations(BADCERT)
ctx.load_verify_locations(CERTFILE, CAPATH)
ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH)
# Issue #10989: crash if the second argument type is invalid
self.assertRaises(TypeError, ctx.load_verify_locations, None, True)
def test_load_verify_cadata(self):
# test cadata
with open(CAFILE_CACERT) as f:
cacert_pem = f.read()
cacert_der = ssl.PEM_cert_to_DER_cert(cacert_pem)
with open(CAFILE_NEURONIO) as f:
neuronio_pem = f.read()
neuronio_der = ssl.PEM_cert_to_DER_cert(neuronio_pem)
# test PEM
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 0)
ctx.load_verify_locations(cadata=cacert_pem)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 1)
ctx.load_verify_locations(cadata=neuronio_pem)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# cert already in hash table
ctx.load_verify_locations(cadata=neuronio_pem)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# combined
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
combined = "\n".join((cacert_pem, neuronio_pem))
ctx.load_verify_locations(cadata=combined)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# with junk around the certs
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
combined = ["head", cacert_pem, "other", neuronio_pem, "again",
neuronio_pem, "tail"]
ctx.load_verify_locations(cadata="\n".join(combined))
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# test DER
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_verify_locations(cadata=cacert_der)
ctx.load_verify_locations(cadata=neuronio_der)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# cert already in hash table
ctx.load_verify_locations(cadata=cacert_der)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# combined
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
combined = b"".join((cacert_der, neuronio_der))
ctx.load_verify_locations(cadata=combined)
self.assertEqual(ctx.cert_store_stats()["x509_ca"], 2)
# error cases
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertRaises(TypeError, ctx.load_verify_locations, cadata=object)
with self.assertRaisesRegex(
ssl.SSLError,
"no start line: cadata does not contain a certificate"
):
ctx.load_verify_locations(cadata="broken")
with self.assertRaisesRegex(
ssl.SSLError,
"not enough data: cadata does not contain a certificate"
):
ctx.load_verify_locations(cadata=b"broken")
@unittest.skipIf(Py_DEBUG_WIN32, "Avoid mixing debug/release CRT on Windows")
def test_load_dh_params(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_dh_params(DHFILE)
if os.name != 'nt':
ctx.load_dh_params(BYTES_DHFILE)
self.assertRaises(TypeError, ctx.load_dh_params)
self.assertRaises(TypeError, ctx.load_dh_params, None)
with self.assertRaises(FileNotFoundError) as cm:
ctx.load_dh_params(NONEXISTINGCERT)
self.assertEqual(cm.exception.errno, errno.ENOENT)
with self.assertRaises(ssl.SSLError) as cm:
ctx.load_dh_params(CERTFILE)
def test_session_stats(self):
for proto in PROTOCOLS:
if not has_tls_protocol(proto):
continue
with warnings_helper.check_warnings():
ctx = ssl.SSLContext(proto)
self.assertEqual(ctx.session_stats(), {
'number': 0,
'connect': 0,
'connect_good': 0,
'connect_renegotiate': 0,
'accept': 0,
'accept_good': 0,
'accept_renegotiate': 0,
'hits': 0,
'misses': 0,
'timeouts': 0,
'cache_full': 0,
})
def test_set_default_verify_paths(self):
# There's not much we can do to test that it acts as expected,
# so just check it doesn't crash or raise an exception.
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.set_default_verify_paths()
@unittest.skipUnless(ssl.HAS_ECDH, "ECDH disabled on this OpenSSL build")
def test_set_ecdh_curve(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.set_ecdh_curve("prime256v1")
ctx.set_ecdh_curve(b"prime256v1")
self.assertRaises(TypeError, ctx.set_ecdh_curve)
self.assertRaises(TypeError, ctx.set_ecdh_curve, None)
self.assertRaises(ValueError, ctx.set_ecdh_curve, "foo")
self.assertRaises(ValueError, ctx.set_ecdh_curve, b"foo")
@needs_sni
def test_sni_callback(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# set_servername_callback expects a callable, or None
self.assertRaises(TypeError, ctx.set_servername_callback)
self.assertRaises(TypeError, ctx.set_servername_callback, 4)
self.assertRaises(TypeError, ctx.set_servername_callback, "")
self.assertRaises(TypeError, ctx.set_servername_callback, ctx)
def dummycallback(sock, servername, ctx):
pass
ctx.set_servername_callback(None)
ctx.set_servername_callback(dummycallback)
@needs_sni
def test_sni_callback_refcycle(self):
# Reference cycles through the servername callback are detected
# and cleared.
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
def dummycallback(sock, servername, ctx, cycle=ctx):
pass
ctx.set_servername_callback(dummycallback)
wr = weakref.ref(ctx)
del ctx, dummycallback
gc.collect()
self.assertIs(wr(), None)
def test_cert_store_stats(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertEqual(ctx.cert_store_stats(),
{'x509_ca': 0, 'crl': 0, 'x509': 0})
ctx.load_cert_chain(CERTFILE)
self.assertEqual(ctx.cert_store_stats(),
{'x509_ca': 0, 'crl': 0, 'x509': 0})
ctx.load_verify_locations(CERTFILE)
self.assertEqual(ctx.cert_store_stats(),
{'x509_ca': 0, 'crl': 0, 'x509': 1})
ctx.load_verify_locations(CAFILE_CACERT)
self.assertEqual(ctx.cert_store_stats(),
{'x509_ca': 1, 'crl': 0, 'x509': 2})
def test_get_ca_certs(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertEqual(ctx.get_ca_certs(), [])
# CERTFILE is not flagged as X509v3 Basic Constraints: CA:TRUE
ctx.load_verify_locations(CERTFILE)
self.assertEqual(ctx.get_ca_certs(), [])
# but CAFILE_CACERT is a CA cert
ctx.load_verify_locations(CAFILE_CACERT)
self.assertEqual(ctx.get_ca_certs(),
[{'issuer': ((('organizationName', 'Root CA'),),
(('organizationalUnitName', 'http://www.cacert.org'),),
(('commonName', 'CA Cert Signing Authority'),),
(('emailAddress', 'support@cacert.org'),)),
'notAfter': asn1time('Mar 29 12:29:49 2033 GMT'),
'notBefore': asn1time('Mar 30 12:29:49 2003 GMT'),
'serialNumber': '00',
'crlDistributionPoints': ('https://www.cacert.org/revoke.crl',),
'subject': ((('organizationName', 'Root CA'),),
(('organizationalUnitName', 'http://www.cacert.org'),),
(('commonName', 'CA Cert Signing Authority'),),
(('emailAddress', 'support@cacert.org'),)),
'version': 3}])
with open(CAFILE_CACERT) as f:
pem = f.read()
der = ssl.PEM_cert_to_DER_cert(pem)
self.assertEqual(ctx.get_ca_certs(True), [der])
def test_load_default_certs(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_default_certs()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_default_certs(ssl.Purpose.SERVER_AUTH)
ctx.load_default_certs()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_default_certs(ssl.Purpose.CLIENT_AUTH)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertRaises(TypeError, ctx.load_default_certs, None)
self.assertRaises(TypeError, ctx.load_default_certs, 'SERVER_AUTH')
@unittest.skipIf(sys.platform == "win32", "not-Windows specific")
@unittest.skipIf(IS_LIBRESSL, "LibreSSL doesn't support env vars")
def test_load_default_certs_env(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with support.EnvironmentVarGuard() as env:
env["SSL_CERT_DIR"] = CAPATH
env["SSL_CERT_FILE"] = CERTFILE
ctx.load_default_certs()
self.assertEqual(ctx.cert_store_stats(), {"crl": 0, "x509": 1, "x509_ca": 0})
@unittest.skipUnless(sys.platform == "win32", "Windows specific")
@unittest.skipIf(hasattr(sys, "gettotalrefcount"), "Debug build does not share environment between CRTs")
def test_load_default_certs_env_windows(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_default_certs()
stats = ctx.cert_store_stats()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with support.EnvironmentVarGuard() as env:
env["SSL_CERT_DIR"] = CAPATH
env["SSL_CERT_FILE"] = CERTFILE
ctx.load_default_certs()
stats["x509"] += 1
self.assertEqual(ctx.cert_store_stats(), stats)
def _assert_context_options(self, ctx):
self.assertEqual(ctx.options & ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv2)
if OP_NO_COMPRESSION != 0:
self.assertEqual(ctx.options & OP_NO_COMPRESSION,
OP_NO_COMPRESSION)
if OP_SINGLE_DH_USE != 0:
self.assertEqual(ctx.options & OP_SINGLE_DH_USE,
OP_SINGLE_DH_USE)
if OP_SINGLE_ECDH_USE != 0:
self.assertEqual(ctx.options & OP_SINGLE_ECDH_USE,
OP_SINGLE_ECDH_USE)
if OP_CIPHER_SERVER_PREFERENCE != 0:
self.assertEqual(ctx.options & OP_CIPHER_SERVER_PREFERENCE,
OP_CIPHER_SERVER_PREFERENCE)
def test_create_default_context(self):
ctx = ssl.create_default_context()
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
self.assertTrue(ctx.check_hostname)
self._assert_context_options(ctx)
with open(SIGNING_CA) as f:
cadata = f.read()
ctx = ssl.create_default_context(cafile=SIGNING_CA, capath=CAPATH,
cadata=cadata)
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
self._assert_context_options(ctx)
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
self._assert_context_options(ctx)
def test__create_stdlib_context(self):
ctx = ssl._create_stdlib_context()
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
self.assertFalse(ctx.check_hostname)
self._assert_context_options(ctx)
if has_tls_protocol(ssl.PROTOCOL_TLSv1):
with warnings_helper.check_warnings():
ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1)
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
self._assert_context_options(ctx)
with warnings_helper.check_warnings():
ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1,
cert_reqs=ssl.CERT_REQUIRED,
check_hostname=True)
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
self.assertTrue(ctx.check_hostname)
self._assert_context_options(ctx)
ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH)
self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
self._assert_context_options(ctx)
def test_check_hostname(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS)
self.assertFalse(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
# Auto set CERT_REQUIRED
ctx.check_hostname = True
self.assertTrue(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_REQUIRED
self.assertFalse(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
# Changing verify_mode does not affect check_hostname
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.check_hostname = False
self.assertFalse(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
# Auto set
ctx.check_hostname = True
self.assertTrue(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_OPTIONAL
ctx.check_hostname = False
self.assertFalse(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL)
# keep CERT_OPTIONAL
ctx.check_hostname = True
self.assertTrue(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL)
# Cannot set CERT_NONE with check_hostname enabled
with self.assertRaises(ValueError):
ctx.verify_mode = ssl.CERT_NONE
ctx.check_hostname = False
self.assertFalse(ctx.check_hostname)
ctx.verify_mode = ssl.CERT_NONE
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
def test_context_client_server(self):
# PROTOCOL_TLS_CLIENT has sane defaults
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertTrue(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)
# PROTOCOL_TLS_SERVER has different but also sane defaults
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.assertFalse(ctx.check_hostname)
self.assertEqual(ctx.verify_mode, ssl.CERT_NONE)
def test_context_custom_class(self):
class MySSLSocket(ssl.SSLSocket):
pass
class MySSLObject(ssl.SSLObject):
pass
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.sslsocket_class = MySSLSocket
ctx.sslobject_class = MySSLObject
with ctx.wrap_socket(socket.socket(), server_side=True) as sock:
self.assertIsInstance(sock, MySSLSocket)
obj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO())
self.assertIsInstance(obj, MySSLObject)
@unittest.skipUnless(IS_OPENSSL_1_1_1, "Test requires OpenSSL 1.1.1")
def test_num_tickest(self):
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
self.assertEqual(ctx.num_tickets, 2)
ctx.num_tickets = 1
self.assertEqual(ctx.num_tickets, 1)
ctx.num_tickets = 0
self.assertEqual(ctx.num_tickets, 0)
with self.assertRaises(ValueError):
ctx.num_tickets = -1
with self.assertRaises(TypeError):
ctx.num_tickets = None
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.assertEqual(ctx.num_tickets, 2)
with self.assertRaises(ValueError):
ctx.num_tickets = 1
| ContextTests |
python | ray-project__ray | release/ray_release/tests/test_buildkite.py | {
"start": 1649,
"end": 1781
} | class ____(MockReturn):
def builds(self):
return self
def artifacts(self):
return self
| MockBuildkitePythonAPI |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_sagemaker_base.py | {
"start": 7928,
"end": 10200
} | class ____:
@patch(
"airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn",
new_callable=mock.PropertyMock,
)
def test_create_experiment(
self, conn_mock, session, clean_dags_dagruns_and_dagbundles, testing_dag_bundle
):
conn_mock().create_experiment.return_value = {"ExperimentArn": "abcdef"}
# putting a DAG around the operator so that jinja template gets rendered
logical_date = timezone.datetime(2020, 1, 1)
dag = DAG("test_experiment", schedule=None, start_date=logical_date)
op = SageMakerCreateExperimentOperator(
name="the name",
description="the desc",
tags={"jinja": "{{ task.task_id }}"},
task_id="tid",
dag=dag,
)
if AIRFLOW_V_3_0_PLUS:
from airflow.models.dag_version import DagVersion
sync_dag_to_db(dag)
dag_version = DagVersion.get_latest_version(dag.dag_id)
ti = TaskInstance(task=op, dag_version_id=dag_version.id)
dag_run = DagRun(
dag_id=dag.dag_id,
logical_date=logical_date,
run_id="test",
run_type=DagRunType.MANUAL,
state=DagRunState.RUNNING,
)
else:
dag_run = DagRun(
dag_id=dag.dag_id,
execution_date=logical_date,
run_id="test",
run_type=DagRunType.MANUAL,
state=DagRunState.RUNNING,
)
ti = TaskInstance(task=op)
ti.dag_run = dag_run
session.add(ti)
session.commit()
context = ti.get_template_context()
ti.render_templates(context)
ret = op.execute(None)
assert ret == "abcdef"
conn_mock().create_experiment.assert_called_once_with(
ExperimentName="the name",
Description="the desc",
Tags=[{"Key": "jinja", "Value": "tid"}],
)
def test_template_fields(self):
operator = SageMakerCreateExperimentOperator(
name="the name",
description="the desc",
task_id="tid",
)
validate_template_fields(operator)
| TestSageMakerExperimentOperator |
python | ray-project__ray | python/ray/dashboard/modules/usage_stats/usage_stats_head.py | {
"start": 429,
"end": 7996
} | class ____(dashboard_utils.DashboardHeadModule):
def __init__(self, config: dashboard_utils.DashboardHeadModuleConfig):
super().__init__(config)
self.usage_stats_enabled = ray_usage_lib.usage_stats_enabled()
self.usage_stats_prompt_enabled = ray_usage_lib.usage_stats_prompt_enabled()
self.cluster_config_to_report = None
self.client = ray_usage_lib.UsageReportClient()
# The total number of report succeeded.
self.total_success = 0
# The total number of report failed.
self.total_failed = 0
# The seq number of report. It increments whenever a new report is sent.
self.seq_no = 0
self._dashboard_url_base = (
f"http://{build_address(self.http_host, self.http_port)}"
)
# We want to record stats for anyone who has run ray with grafana or
# prometheus at any point in time during a ray session.
self._grafana_ran_before = False
self._prometheus_ran_before = False
if ray._private.utils.get_dashboard_dependency_error() is None:
import aiohttp
import ray.dashboard.optional_utils
routes = ray.dashboard.optional_utils.DashboardHeadRouteTable
@routes.get("/usage_stats_enabled")
async def get_usage_stats_enabled(self, req) -> aiohttp.web.Response:
return ray.dashboard.optional_utils.rest_response(
status_code=dashboard_utils.HTTPStatusCode.OK,
message="Fetched usage stats enabled",
usage_stats_enabled=self.usage_stats_enabled,
usage_stats_prompt_enabled=self.usage_stats_prompt_enabled,
)
@routes.get("/cluster_id")
async def get_cluster_id(self, req) -> aiohttp.web.Response:
return ray.dashboard.optional_utils.rest_response(
status_code=dashboard_utils.HTTPStatusCode.OK,
message="Fetched cluster id",
cluster_id=self.gcs_client.cluster_id.hex(),
)
def _check_grafana_running(self):
from ray._common.usage.usage_lib import TagKey, record_extra_usage_tag
if self._grafana_ran_before:
return
grafana_running = False
try:
resp = requests.get(f"{self._dashboard_url_base}/api/grafana_health")
if resp.status_code == 200:
json = resp.json()
grafana_running = (
json["result"] is True and json["data"]["grafanaHost"] != "DISABLED"
)
except Exception:
pass
record_extra_usage_tag(
TagKey.DASHBOARD_METRICS_GRAFANA_ENABLED,
str(grafana_running),
)
if grafana_running:
# Don't need to update the tag ever again
self._grafana_ran_before = True
def _check_prometheus_running(self):
from ray._common.usage.usage_lib import TagKey, record_extra_usage_tag
if self._prometheus_ran_before:
return
prometheus_running = False
try:
resp = requests.get(f"{self._dashboard_url_base}/api/prometheus_health")
if resp.status_code == 200:
json = resp.json()
prometheus_running = json["result"] is True
except Exception:
pass
record_extra_usage_tag(
TagKey.DASHBOARD_METRICS_PROMETHEUS_ENABLED,
str(prometheus_running),
)
if prometheus_running:
# Don't need to update the tag ever again
self._prometheus_ran_before = True
def _fetch_and_record_extra_usage_stats_data(self):
logger.debug("Recording dashboard metrics extra telemetry data...")
self._check_grafana_running()
self._check_prometheus_running()
def _report_usage_sync(self):
"""
- Always write usage_stats.json regardless of report success/failure.
- If report fails, the error message should be written to usage_stats.json
- If file write fails, the error will just stay at dashboard.log.
usage_stats.json won't be written.
"""
if not self.usage_stats_enabled:
return
try:
self._fetch_and_record_extra_usage_stats_data()
data = ray_usage_lib.generate_report_data(
self.cluster_config_to_report,
self.total_success,
self.total_failed,
self.seq_no,
self.gcs_address,
self.gcs_client.cluster_id.hex(),
)
error = None
try:
self.client.report_usage_data(
ray_usage_lib._usage_stats_report_url(), data
)
except Exception as e:
logger.info(f"Usage report request failed. {e}")
error = str(e)
self.total_failed += 1
else:
self.total_success += 1
finally:
self.seq_no += 1
data = ray_usage_lib.generate_write_data(data, error)
self.client.write_usage_data(data, self.session_dir)
except Exception as e:
logger.exception(e)
logger.info(f"Usage report failed: {e}")
async def _report_usage_async(self):
if not self.usage_stats_enabled:
return
loop = get_or_create_event_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
await loop.run_in_executor(executor, lambda: self._report_usage_sync())
def _report_disabled_usage_sync(self):
assert not self.usage_stats_enabled
try:
if ray_usage_lib.is_ray_init_cluster(self.gcs_client):
return
data = ray_usage_lib.generate_disabled_report_data()
self.client.report_usage_data(ray_usage_lib._usage_stats_report_url(), data)
except Exception as e:
logger.debug(f"Disabled usage report failed: {e}")
async def _report_disabled_usage_async(self):
assert not self.usage_stats_enabled
loop = get_or_create_event_loop()
with ThreadPoolExecutor(max_workers=1) as executor:
await loop.run_in_executor(
executor, lambda: self._report_disabled_usage_sync()
)
@async_loop_forever(ray_usage_lib._usage_stats_report_interval_s())
async def periodically_report_usage(self):
await self._report_usage_async()
async def run(self):
self.cluster_config_to_report = ray_usage_lib.get_cluster_config_to_report(
os.path.expanduser("~/ray_bootstrap_config.yaml")
)
if not self.usage_stats_enabled:
logger.info("Usage reporting is disabled.")
await self._report_disabled_usage_async()
return
else:
logger.info("Usage reporting is enabled.")
# Wait for 1 minutes to send the first report
# so autoscaler has the chance to set DEBUG_AUTOSCALING_STATUS.
await asyncio.sleep(min(60, ray_usage_lib._usage_stats_report_interval_s()))
await self._report_usage_async()
# Add a random offset before the second report to remove sample bias.
await asyncio.sleep(
random.randint(0, ray_usage_lib._usage_stats_report_interval_s())
)
await asyncio.gather(self.periodically_report_usage())
@staticmethod
def is_minimal_module():
return True
| UsageStatsHead |
python | ansible__ansible | lib/ansible/_internal/_errors/_alarm_timeout.py | {
"start": 145,
"end": 2519
} | class ____(BaseException):
"""A general purpose timeout."""
_MAX_TIMEOUT = 100_000_000
"""
The maximum supported timeout value.
This value comes from BSD's alarm limit, which is due to that function using setitimer.
"""
def __init__(self, timeout: int) -> None:
self.timeout = timeout
super().__init__(f"Timed out after {timeout} second(s).")
@classmethod
@contextlib.contextmanager
def alarm_timeout(cls, timeout: int | None) -> _t.Iterator[None]:
"""
Context for running code under an optional timeout.
Raises an instance of this class if the timeout occurs.
New usages of this timeout mechanism are discouraged.
"""
if timeout is not None:
if not isinstance(timeout, int):
raise TypeError(f"Timeout requires 'int' argument, not {datatag.native_type_name(timeout)!r}.")
if timeout < 0 or timeout > cls._MAX_TIMEOUT:
# On BSD based systems, alarm is implemented using setitimer.
# If out-of-bounds values are passed to alarm, they will return -1, which would be interpreted as an existing timer being set.
# To avoid that, bounds checking is performed in advance.
raise ValueError(f'Timeout {timeout} is invalid, it must be between 0 and {cls._MAX_TIMEOUT}.')
if not timeout:
yield # execute the context manager's body
return # no timeout to deal with, exit immediately
def on_alarm(_signal: int, _frame: types.FrameType) -> None:
raise cls(timeout)
if signal.signal(signal.SIGALRM, on_alarm):
raise RuntimeError("An existing alarm handler was present.")
try:
try:
if signal.alarm(timeout):
raise RuntimeError("An existing alarm was set.")
yield # execute the context manager's body
finally:
# Disable the alarm.
# If the alarm fires inside this finally block, the alarm is still disabled.
# This guarantees the cleanup code in the outer finally block runs without risk of encountering the `TaskTimeoutError` from the alarm.
signal.alarm(0)
finally:
signal.signal(signal.SIGALRM, signal.SIG_DFL)
| AnsibleTimeoutError |
python | sphinx-doc__sphinx | sphinx/domains/python/_object.py | {
"start": 4903,
"end": 4963
} | class ____(PyXrefMixin, GroupedField):
pass
| PyGroupedField |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 163700,
"end": 167410
} | class ____(Operation):
def __init__(self, pad_width, mode="constant", *, name=None):
super().__init__(name=name)
self.pad_width = self._process_pad_width(pad_width)
self.mode = mode
def _process_pad_width(self, pad_width):
if isinstance(pad_width, int):
return ((pad_width, pad_width),)
if isinstance(pad_width, (tuple, list)) and isinstance(
pad_width[0], int
):
return (pad_width,)
first_len = len(pad_width[0])
for i, pw in enumerate(pad_width):
if len(pw) != first_len:
raise ValueError(
"`pad_width` should be a list of tuples of length "
f"1 or 2. Received: pad_width={pad_width}"
)
if len(pw) == 1:
pad_width[i] = (pw[0], pw[0])
return pad_width
def call(self, x, constant_values=None):
if len(self.pad_width) > 1 and len(self.pad_width) != len(x.shape):
raise ValueError(
"`pad_width` must have the same length as `x.shape`. "
f"Received: pad_width={self.pad_width} "
f"(of length {len(self.pad_width)}) and x.shape={x.shape} "
f"(of length {len(x.shape)})"
)
return backend.numpy.pad(
x,
pad_width=self.pad_width,
mode=self.mode,
constant_values=constant_values,
)
def compute_output_spec(self, x, constant_values=None):
output_shape = list(x.shape)
if len(self.pad_width) == 1:
pad_width = [self.pad_width[0] for _ in range(len(output_shape))]
elif len(self.pad_width) == len(output_shape):
pad_width = self.pad_width
else:
raise ValueError(
"`pad_width` must have the same length as `x.shape`. "
f"Received: pad_width={self.pad_width} "
f"(of length {len(self.pad_width)}) and x.shape={x.shape} "
f"(of length {len(x.shape)})"
)
for i in range(len(output_shape)):
if output_shape[i] is None:
output_shape[i] = None
else:
output_shape[i] += pad_width[i][0] + pad_width[i][1]
return KerasTensor(output_shape, dtype=x.dtype)
@keras_export(["keras.ops.pad", "keras.ops.numpy.pad"])
def pad(x, pad_width, mode="constant", constant_values=None):
"""Pad a tensor.
Args:
x: Tensor to pad.
pad_width: Number of values padded to the edges of each axis.
`((before_1, after_1), ...(before_N, after_N))` unique pad
widths for each axis.
`((before, after),)` yields same before and after pad for
each axis.
`(pad,)` or `int` is a shortcut for `before = after = pad`
width for all axes.
mode: One of `"constant"`, `"edge"`, `"linear_ramp"`,
`"maximum"`, `"mean"`, `"median"`, `"minimum"`,
`"reflect"`, `"symmetric"`, `"wrap"`, `"empty"`,
`"circular"`. Defaults to `"constant"`.
constant_values: value to pad with if `mode == "constant"`.
Defaults to `0`. A `ValueError` is raised if not None and
`mode != "constant"`.
Note:
Torch backend only supports modes `"constant"`, `"reflect"`,
`"symmetric"` and `"circular"`.
Only Torch backend supports `"circular"` mode.
Note:
Tensorflow backend only supports modes `"constant"`, `"reflect"`
and `"symmetric"`.
Returns:
Padded tensor.
"""
return Pad(pad_width, mode=mode)(x, constant_values=constant_values)
| Pad |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 1298,
"end": 5095
} | class ____(BaseManager["Incident"]):
CACHE_KEY = "incidents:active:%s:%s:%s"
def fetch_for_organization(self, organization, projects):
return self.filter(organization=organization, projects__in=projects).distinct()
@classmethod
def _build_active_incident_cache_key(cls, alert_rule_id, project_id, subscription_id=None):
return cls.CACHE_KEY % (alert_rule_id, project_id, subscription_id)
def get_active_incident(self, alert_rule, project, subscription=None):
"""
fetches the latest incident for a given alert rule and project (and subscription) that is not closed
"""
cache_key = self._build_active_incident_cache_key(
alert_rule_id=alert_rule.id,
project_id=project.id,
subscription_id=(subscription.id if subscription else None),
)
incident = cache.get(cache_key)
if incident is None:
try:
incident_query = Incident.objects.filter(
type=IncidentType.ALERT_TRIGGERED.value,
alert_rule=alert_rule,
projects=project,
subscription=subscription,
)
incident = incident_query.exclude(status=IncidentStatus.CLOSED.value).order_by(
"-date_added"
)[0]
except IndexError:
# Set this to False so that we can have a negative cache as well.
incident = False
cache.set(cache_key, incident)
if incident is False:
incident = None
elif not incident:
# If we had a falsey not None value in the cache, then we stored that there
# are no current active incidents. Just set to None
incident = None
return incident
@classmethod
def clear_active_incident_cache(cls, instance, **kwargs):
# instance is an Incident
for project in instance.projects.all():
subscription = instance.subscription
key = cls._build_active_incident_cache_key(
instance.alert_rule_id, project.id, subscription.id if subscription else None
)
cache.delete(key)
assert cache.get(key) is None
@classmethod
def clear_active_incident_project_cache(cls, instance, **kwargs):
# instance is an IncidentProject
project_id = instance.project_id
incident = instance.incident
subscription_id = incident.subscription_id if incident.subscription else None
key = cls._build_active_incident_cache_key(
incident.alert_rule_id, project_id, subscription_id
)
cache.delete(key)
assert cache.get(key) is None
@TimedRetryPolicy.wrap(timeout=5, exceptions=(IntegrityError,))
def create(self, organization, **kwargs):
"""
Creates an Incident. Fetches the maximum identifier value for the org
and increments it by one. If two incidents are created for the
Organization at the same time then an integrity error will be thrown,
and we'll retry again several times. I prefer to lock optimistically
here since if we're creating multiple Incidents a second for an
Organization then we're likely failing at making Incidents useful.
"""
with transaction.atomic(router.db_for_write(Organization)):
result = self.filter(organization=organization).aggregate(models.Max("identifier"))
identifier = result["identifier__max"]
if identifier is None:
identifier = 1
else:
identifier += 1
return super().create(organization=organization, identifier=identifier, **kwargs)
| IncidentManager |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/context_editing.py | {
"start": 1239,
"end": 5368
} | class ____(ContextEdit):
"""Configuration for clearing tool outputs when token limits are exceeded."""
trigger: int = 100_000
"""Token count that triggers the edit."""
clear_at_least: int = 0
"""Minimum number of tokens to reclaim when the edit runs."""
keep: int = 3
"""Number of most recent tool results that must be preserved."""
clear_tool_inputs: bool = False
"""Whether to clear the originating tool call parameters on the AI message."""
exclude_tools: Sequence[str] = ()
"""List of tool names to exclude from clearing."""
placeholder: str = DEFAULT_TOOL_PLACEHOLDER
"""Placeholder text inserted for cleared tool outputs."""
def apply(
self,
messages: list[AnyMessage],
*,
count_tokens: TokenCounter,
) -> None:
"""Apply the clear-tool-uses strategy."""
tokens = count_tokens(messages)
if tokens <= self.trigger:
return
candidates = [
(idx, msg) for idx, msg in enumerate(messages) if isinstance(msg, ToolMessage)
]
if self.keep >= len(candidates):
candidates = []
elif self.keep:
candidates = candidates[: -self.keep]
cleared_tokens = 0
excluded_tools = set(self.exclude_tools)
for idx, tool_message in candidates:
if tool_message.response_metadata.get("context_editing", {}).get("cleared"):
continue
ai_message = next(
(m for m in reversed(messages[:idx]) if isinstance(m, AIMessage)), None
)
if ai_message is None:
continue
tool_call = next(
(
call
for call in ai_message.tool_calls
if call.get("id") == tool_message.tool_call_id
),
None,
)
if tool_call is None:
continue
if (tool_message.name or tool_call["name"]) in excluded_tools:
continue
messages[idx] = tool_message.model_copy(
update={
"artifact": None,
"content": self.placeholder,
"response_metadata": {
**tool_message.response_metadata,
"context_editing": {
"cleared": True,
"strategy": "clear_tool_uses",
},
},
}
)
if self.clear_tool_inputs:
messages[messages.index(ai_message)] = self._build_cleared_tool_input_message(
ai_message,
tool_message.tool_call_id,
)
if self.clear_at_least > 0:
new_token_count = count_tokens(messages)
cleared_tokens = max(0, tokens - new_token_count)
if cleared_tokens >= self.clear_at_least:
break
return
def _build_cleared_tool_input_message(
self,
message: AIMessage,
tool_call_id: str,
) -> AIMessage:
updated_tool_calls = []
cleared_any = False
for tool_call in message.tool_calls:
updated_call = dict(tool_call)
if updated_call.get("id") == tool_call_id:
updated_call["args"] = {}
cleared_any = True
updated_tool_calls.append(updated_call)
metadata = dict(getattr(message, "response_metadata", {}))
context_entry = dict(metadata.get("context_editing", {}))
if cleared_any:
cleared_ids = set(context_entry.get("cleared_tool_inputs", []))
cleared_ids.add(tool_call_id)
context_entry["cleared_tool_inputs"] = sorted(cleared_ids)
metadata["context_editing"] = context_entry
return message.model_copy(
update={
"tool_calls": updated_tool_calls,
"response_metadata": metadata,
}
)
| ClearToolUsesEdit |
python | modin-project__modin | modin/config/envvars.py | {
"start": 45208,
"end": 47032
} | class ____(EnvironmentVariable, type=bool):
"""
Set to true to use Modin's dynamic-partitioning implementation where possible.
Please refer to documentation for cases where enabling this options would be beneficial:
https://modin.readthedocs.io/en/stable/usage_guide/optimization_notes/index.html#dynamic-partitioning-in-modin
"""
varname = "MODIN_DYNAMIC_PARTITIONING"
default = False
def _check_vars() -> None:
"""
Check validity of environment variables.
Look out for any environment variables that start with "MODIN_" prefix
that are unknown - they might be a typo, so warn a user.
"""
valid_names = {
obj.varname
for obj in globals().values()
if isinstance(obj, type)
and issubclass(obj, EnvironmentVariable)
and not obj.is_abstract
}
found_names = {name for name in os.environ if name.startswith("MODIN_")}
unknown = found_names - valid_names
deprecated: dict[str, DeprecationDescriptor] = {
obj.varname: obj._deprecation_descriptor
for obj in globals().values()
if isinstance(obj, type)
and issubclass(obj, EnvironmentVariable)
and not obj.is_abstract
and obj.varname is not None
and obj._deprecation_descriptor is not None
}
found_deprecated = found_names & deprecated.keys()
if unknown:
warnings.warn(
f"Found unknown environment variable{'s' if len(unknown) > 1 else ''},"
+ f" please check {'their' if len(unknown) > 1 else 'its'} spelling: "
+ ", ".join(sorted(unknown))
)
for depr_var in found_deprecated:
warnings.warn(
deprecated[depr_var].deprecation_message(use_envvar_names=True),
FutureWarning,
)
_check_vars()
| DynamicPartitioning |
python | pandas-dev__pandas | pandas/tseries/frequencies.py | {
"start": 13031,
"end": 18529
} | class ____(_FrequencyInferer):
def _infer_daily_rule(self):
if self.is_unique:
return self._get_daily_rule()
def _is_multiple(us, mult: int) -> bool:
return us % mult == 0
def _maybe_add_count(base: str, count: float) -> str:
if count != 1:
assert count == int(count)
count = int(count)
return f"{count}{base}"
else:
return base
# ----------------------------------------------------------------------
# Frequency comparison
def is_subperiod(source, target) -> bool:
"""
Returns True if downsampling is possible between source and target
frequencies
Parameters
----------
source : str or DateOffset
Frequency converting from
target : str or DateOffset
Frequency converting to
Returns
-------
bool
"""
if target is None or source is None:
return False
source = _maybe_coerce_freq(source)
target = _maybe_coerce_freq(target)
if _is_annual(target):
if _is_quarterly(source):
return _quarter_months_conform(
get_rule_month(source), get_rule_month(target)
)
return source in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}
elif _is_quarterly(target):
return source in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}
elif _is_monthly(target):
return source in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif _is_weekly(target):
return source in {target, "D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif target == "B":
return source in {"B", "h", "min", "s", "ms", "us", "ns"}
elif target == "C":
return source in {"C", "h", "min", "s", "ms", "us", "ns"}
elif target == "D":
return source in {"D", "h", "min", "s", "ms", "us", "ns"}
elif target == "h":
return source in {"h", "min", "s", "ms", "us", "ns"}
elif target == "min":
return source in {"min", "s", "ms", "us", "ns"}
elif target == "s":
return source in {"s", "ms", "us", "ns"}
elif target == "ms":
return source in {"ms", "us", "ns"}
elif target == "us":
return source in {"us", "ns"}
elif target == "ns":
return source in {"ns"}
else:
return False
def is_superperiod(source, target) -> bool:
"""
Returns True if upsampling is possible between source and target
frequencies
Parameters
----------
source : str or DateOffset
Frequency converting from
target : str or DateOffset
Frequency converting to
Returns
-------
bool
"""
if target is None or source is None:
return False
source = _maybe_coerce_freq(source)
target = _maybe_coerce_freq(target)
if _is_annual(source):
if _is_annual(target):
return get_rule_month(source) == get_rule_month(target)
if _is_quarterly(target):
smonth = get_rule_month(source)
tmonth = get_rule_month(target)
return _quarter_months_conform(smonth, tmonth)
return target in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}
elif _is_quarterly(source):
return target in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}
elif _is_monthly(source):
return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif _is_weekly(source):
return target in {source, "D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif source == "B":
return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif source == "C":
return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif source == "D":
return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}
elif source == "h":
return target in {"h", "min", "s", "ms", "us", "ns"}
elif source == "min":
return target in {"min", "s", "ms", "us", "ns"}
elif source == "s":
return target in {"s", "ms", "us", "ns"}
elif source == "ms":
return target in {"ms", "us", "ns"}
elif source == "us":
return target in {"us", "ns"}
elif source == "ns":
return target in {"ns"}
else:
return False
def _maybe_coerce_freq(code) -> str:
"""we might need to coerce a code to a rule_code
and uppercase it
Parameters
----------
source : str or DateOffset
Frequency converting from
Returns
-------
str
"""
assert code is not None
if isinstance(code, DateOffset):
code = PeriodDtype(to_offset(code.name))._freqstr
if code in {"h", "min", "s", "ms", "us", "ns"}:
return code
else:
return code.upper()
def _quarter_months_conform(source: str, target: str) -> bool:
snum = MONTH_NUMBERS[source]
tnum = MONTH_NUMBERS[target]
return snum % 3 == tnum % 3
def _is_annual(rule: str) -> bool:
rule = rule.upper()
return rule == "Y" or rule.startswith("Y-")
def _is_quarterly(rule: str) -> bool:
rule = rule.upper()
return rule == "Q" or rule.startswith(("Q-", "BQ"))
def _is_monthly(rule: str) -> bool:
rule = rule.upper()
return rule in ("M", "BM")
def _is_weekly(rule: str) -> bool:
rule = rule.upper()
return rule == "W" or rule.startswith("W-")
__all__ = [
"Day",
"get_period_alias",
"infer_freq",
"is_subperiod",
"is_superperiod",
"to_offset",
]
| _TimedeltaFrequencyInferer |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/config.py | {
"start": 3868,
"end": 4552
} | class ____(HTTPServer):
organization: Optional[str] = None
token: Optional[str] = None
def __init__(self, host: tuple[str, int], nonce: str):
super().__init__(host, create_token_callback_handler(nonce))
def shutdown(self):
# Stop serving the token server
# https://stackoverflow.com/a/36017741
setattr(self, "_BaseServer__shutdown_request", True)
def set_result(self, organization: str, token: str):
self.organization = organization
self.token = token
def get_organization(self) -> Optional[str]:
return self.organization
def get_token(self) -> Optional[str]:
return self.token
| TokenServer |
python | wandb__wandb | wandb/sdk/wandb_setup.py | {
"start": 1661,
"end": 3213
} | class ____:
"""Early logger which captures logs in memory until logging can be configured."""
def __init__(self) -> None:
self._log: list[tuple] = []
self._exception: list[tuple] = []
# support old warn() as alias of warning()
self.warn = self.warning
def debug(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((logging.DEBUG, msg, args, kwargs))
def info(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((logging.INFO, msg, args, kwargs))
def warning(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((logging.WARNING, msg, args, kwargs))
def error(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((logging.ERROR, msg, args, kwargs))
def critical(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((logging.CRITICAL, msg, args, kwargs))
def exception(self, msg: str, *args: Any, **kwargs: Any) -> None:
self._exception.append((msg, args, kwargs))
def log(self, level: str, msg: str, *args: Any, **kwargs: Any) -> None:
self._log.append((level, msg, args, kwargs))
def _flush(self, new_logger: Logger) -> None:
assert self is not new_logger
for level, msg, args, kwargs in self._log:
new_logger.log(level, msg, *args, **kwargs)
for msg, args, kwargs in self._exception:
new_logger.exception(msg, *args, **kwargs)
Logger = Union[logging.Logger, _EarlyLogger]
| _EarlyLogger |
python | django__django | tests/messages_tests/base.py | {
"start": 920,
"end": 13980
} | class ____:
storage_class = default_storage
levels = {
"debug": constants.DEBUG,
"info": constants.INFO,
"success": constants.SUCCESS,
"warning": constants.WARNING,
"error": constants.ERROR,
}
@classmethod
def setUpClass(cls):
cls.enterClassContext(
override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": (
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
),
},
}
],
ROOT_URLCONF="messages_tests.urls",
MESSAGE_TAGS={},
MESSAGE_STORAGE=(
f"{cls.storage_class.__module__}.{cls.storage_class.__name__}"
),
SESSION_SERIALIZER="django.contrib.sessions.serializers.JSONSerializer",
)
)
super().setUpClass()
def get_request(self):
return HttpRequest()
def get_response(self):
return HttpResponse()
def get_storage(self, data=None):
"""
Return the storage backend, setting its loaded data to the ``data``
argument.
This method avoids the storage ``_get`` method from getting called so
that other parts of the storage backend can be tested independent of
the message retrieval logic.
"""
storage = self.storage_class(self.get_request())
storage._loaded_data = data or []
return storage
def test_repr(self):
request = self.get_request()
storage = self.storage_class(request)
self.assertEqual(
repr(storage),
f"<{self.storage_class.__qualname__}: request=<HttpRequest>>",
)
def test_add(self):
storage = self.get_storage()
self.assertFalse(storage.added_new)
storage.add(constants.INFO, "Test message 1")
self.assertTrue(storage.added_new)
storage.add(constants.INFO, "Test message 2", extra_tags="tag")
self.assertEqual(len(storage), 2)
def test_add_lazy_translation(self):
storage = self.get_storage()
response = self.get_response()
storage.add(constants.INFO, gettext_lazy("lazy message"))
storage.update(response)
storing = self.stored_messages_count(storage, response)
self.assertEqual(storing, 1)
def test_no_update(self):
storage = self.get_storage()
response = self.get_response()
storage.update(response)
storing = self.stored_messages_count(storage, response)
self.assertEqual(storing, 0)
def test_add_update(self):
storage = self.get_storage()
response = self.get_response()
storage.add(constants.INFO, "Test message 1")
storage.add(constants.INFO, "Test message 1", extra_tags="tag")
storage.update(response)
storing = self.stored_messages_count(storage, response)
self.assertEqual(storing, 2)
def test_existing_add_read_update(self):
storage = self.get_existing_storage()
response = self.get_response()
storage.add(constants.INFO, "Test message 3")
list(storage) # Simulates a read
storage.update(response)
storing = self.stored_messages_count(storage, response)
self.assertEqual(storing, 0)
def test_existing_read_add_update(self):
storage = self.get_existing_storage()
response = self.get_response()
list(storage) # Simulates a read
storage.add(constants.INFO, "Test message 3")
storage.update(response)
storing = self.stored_messages_count(storage, response)
self.assertEqual(storing, 1)
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
def test_full_request_response_cycle(self):
"""
With the message middleware enabled, messages are properly stored and
retrieved across the full request/redirect/response cycle.
"""
data = {
"messages": ["Test message %d" % x for x in range(5)],
}
show_url = reverse("show_message")
for level in ("debug", "info", "success", "warning", "error"):
add_url = reverse("add_message", args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertIn("messages", response.context)
messages = [Message(self.levels[level], msg) for msg in data["messages"]]
self.assertEqual(list(response.context["messages"]), messages)
for msg in data["messages"]:
self.assertContains(response, msg)
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
def test_with_template_response(self):
data = {
"messages": ["Test message %d" % x for x in range(5)],
}
show_url = reverse("show_template_response")
for level in self.levels:
add_url = reverse("add_template_response", args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertIn("messages", response.context)
for msg in data["messages"]:
self.assertContains(response, msg)
# there shouldn't be any messages on second GET request
response = self.client.get(show_url)
for msg in data["messages"]:
self.assertNotContains(response, msg)
def test_context_processor_message_levels(self):
show_url = reverse("show_template_response")
response = self.client.get(show_url)
self.assertIn("DEFAULT_MESSAGE_LEVELS", response.context)
self.assertEqual(response.context["DEFAULT_MESSAGE_LEVELS"], DEFAULT_LEVELS)
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
def test_multiple_posts(self):
"""
Messages persist properly when multiple POSTs are made before a GET.
"""
data = {
"messages": ["Test message %d" % x for x in range(5)],
}
show_url = reverse("show_message")
messages = []
for level in ("debug", "info", "success", "warning", "error"):
messages.extend(
Message(self.levels[level], msg) for msg in data["messages"]
)
add_url = reverse("add_message", args=(level,))
self.client.post(add_url, data)
response = self.client.get(show_url)
self.assertIn("messages", response.context)
self.assertEqual(list(response.context["messages"]), messages)
for msg in data["messages"]:
self.assertContains(response, msg)
@modify_settings(
INSTALLED_APPS={"remove": "django.contrib.messages"},
MIDDLEWARE={"remove": "django.contrib.messages.middleware.MessageMiddleware"},
)
@override_settings(
MESSAGE_LEVEL=constants.DEBUG,
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
}
],
)
def test_middleware_disabled(self):
"""
When the middleware is disabled, an exception is raised when one
attempts to store a message.
"""
data = {
"messages": ["Test message %d" % x for x in range(5)],
}
reverse("show_message")
for level in ("debug", "info", "success", "warning", "error"):
add_url = reverse("add_message", args=(level,))
with self.assertRaises(MessageFailure):
self.client.post(add_url, data, follow=True)
@modify_settings(
INSTALLED_APPS={"remove": "django.contrib.messages"},
MIDDLEWARE={"remove": "django.contrib.messages.middleware.MessageMiddleware"},
)
@override_settings(
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
}
],
)
def test_middleware_disabled_fail_silently(self):
"""
When the middleware is disabled, an exception is not raised
if 'fail_silently' is True.
"""
data = {
"messages": ["Test message %d" % x for x in range(5)],
"fail_silently": True,
}
show_url = reverse("show_message")
for level in ("debug", "info", "success", "warning", "error"):
add_url = reverse("add_message", args=(level,))
response = self.client.post(add_url, data, follow=True)
self.assertRedirects(response, show_url)
self.assertNotIn("messages", response.context)
def stored_messages_count(self, storage, response):
"""
Return the number of messages being stored after a
``storage.update()`` call.
"""
raise NotImplementedError("This method must be set by a subclass.")
def test_get(self):
raise NotImplementedError("This method must be set by a subclass.")
def get_existing_storage(self):
return self.get_storage(
[
Message(constants.INFO, "Test message 1"),
Message(constants.INFO, "Test message 2", extra_tags="tag"),
]
)
def test_existing_read(self):
"""
Reading the existing storage doesn't cause the data to be lost.
"""
storage = self.get_existing_storage()
self.assertFalse(storage.used)
# After iterating the storage engine directly, the used flag is set.
data = list(storage)
self.assertTrue(storage.used)
# The data does not disappear because it has been iterated.
self.assertEqual(data, list(storage))
def test_existing_add(self):
storage = self.get_existing_storage()
self.assertFalse(storage.added_new)
storage.add(constants.INFO, "Test message 3")
self.assertTrue(storage.added_new)
def test_default_level(self):
# get_level works even with no storage on the request.
request = self.get_request()
self.assertEqual(get_level(request), constants.INFO)
# get_level returns the default level if it hasn't been set.
storage = self.get_storage()
request._messages = storage
self.assertEqual(get_level(request), constants.INFO)
# Only messages of sufficient level get recorded.
add_level_messages(storage)
self.assertEqual(len(storage), 5)
def test_low_level(self):
request = self.get_request()
storage = self.storage_class(request)
request._messages = storage
self.assertTrue(set_level(request, 5))
self.assertEqual(get_level(request), 5)
add_level_messages(storage)
self.assertEqual(len(storage), 6)
def test_high_level(self):
request = self.get_request()
storage = self.storage_class(request)
request._messages = storage
self.assertTrue(set_level(request, 30))
self.assertEqual(get_level(request), 30)
add_level_messages(storage)
self.assertEqual(len(storage), 2)
@override_settings(MESSAGE_LEVEL=29)
def test_settings_level(self):
request = self.get_request()
storage = self.storage_class(request)
self.assertEqual(get_level(request), 29)
add_level_messages(storage)
self.assertEqual(len(storage), 3)
def test_tags(self):
storage = self.get_storage()
storage.level = 0
add_level_messages(storage)
storage.add(constants.INFO, "A generic info message", extra_tags=None)
tags = [msg.tags for msg in storage]
self.assertEqual(
tags, ["info", "", "extra-tag debug", "warning", "error", "success", "info"]
)
def test_level_tag(self):
storage = self.get_storage()
storage.level = 0
add_level_messages(storage)
tags = [msg.level_tag for msg in storage]
self.assertEqual(tags, ["info", "", "debug", "warning", "error", "success"])
@override_settings(
MESSAGE_TAGS={
constants.INFO: "info",
constants.DEBUG: "",
constants.WARNING: "",
constants.ERROR: "bad",
29: "custom",
}
)
def test_custom_tags(self):
storage = self.get_storage()
storage.level = 0
add_level_messages(storage)
tags = [msg.tags for msg in storage]
self.assertEqual(tags, ["info", "custom", "extra-tag", "", "bad", "success"])
| BaseTests |
python | walkccc__LeetCode | solutions/1823. Find the Winner of the Circular Game/1823.py | {
"start": 0,
"end": 474
} | class ____:
def findTheWinner(self, n: int, k: int) -> int:
# True if i-th friend is left
friends = [False] * n
friendCount = n
fp = 0 # friends' index
while friendCount > 1:
for _ in range(k):
while friends[fp % n]: # The friend is not there.
fp += 1 # Point to the next one.
fp += 1
friends[(fp - 1) % n] = True
friendCount -= 1
fp = 0
while friends[fp]:
fp += 1
return fp + 1
| Solution |
python | pypa__pip | src/pip/_vendor/pyproject_hooks/_in_process/_in_process.py | {
"start": 10180,
"end": 12216
} | class ____(Exception):
"""For internal use when backend raises UnsupportedOperation"""
def __init__(self, traceback):
self.traceback = traceback
def build_sdist(sdist_directory, config_settings):
"""Invoke the mandatory build_sdist hook."""
backend = _build_backend()
try:
return backend.build_sdist(sdist_directory, config_settings)
except getattr(backend, "UnsupportedOperation", _DummyException):
raise GotUnsupportedOperation(traceback.format_exc())
HOOK_NAMES = {
"get_requires_for_build_wheel",
"prepare_metadata_for_build_wheel",
"build_wheel",
"get_requires_for_build_editable",
"prepare_metadata_for_build_editable",
"build_editable",
"get_requires_for_build_sdist",
"build_sdist",
"_supported_features",
}
def main():
if len(sys.argv) < 3:
sys.exit("Needs args: hook_name, control_dir")
hook_name = sys.argv[1]
control_dir = sys.argv[2]
if hook_name not in HOOK_NAMES:
sys.exit("Unknown hook: %s" % hook_name)
# Remove the parent directory from sys.path to avoid polluting the backend
# import namespace with this directory.
here = os.path.dirname(__file__)
if here in sys.path:
sys.path.remove(here)
hook = globals()[hook_name]
hook_input = read_json(pjoin(control_dir, "input.json"))
json_out = {"unsupported": False, "return_val": None}
try:
json_out["return_val"] = hook(**hook_input["kwargs"])
except BackendUnavailable as e:
json_out["no_backend"] = True
json_out["traceback"] = e.traceback
json_out["backend_error"] = e.message
except GotUnsupportedOperation as e:
json_out["unsupported"] = True
json_out["traceback"] = e.traceback
except HookMissing as e:
json_out["hook_missing"] = True
json_out["missing_hook_name"] = e.hook_name or hook_name
write_json(json_out, pjoin(control_dir, "output.json"), indent=2)
if __name__ == "__main__":
main()
| GotUnsupportedOperation |
python | getsentry__sentry | tests/sentry/rules/processing/test_buffer_processing.py | {
"start": 3576,
"end": 8210
} | class ____(CreateEventTestCase, PerformanceIssueTestCase):
buffer_timestamp = (FROZEN_TIME + timedelta(seconds=1)).timestamp()
def assert_buffer_cleared(self, project_id):
rule_group_data = buffer.backend.get_hash(Project, {"project_id": project_id})
assert rule_group_data == {}
def setUp(self) -> None:
super().setUp()
self.tag_filter = {
"id": "sentry.rules.filters.tagged_event.TaggedEventFilter",
"key": "foo",
"match": "eq",
"value": "bar",
}
self.event_frequency_condition = self.create_event_frequency_condition()
self.event_frequency_condition2 = self.create_event_frequency_condition(value=2)
self.event_frequency_condition3 = self.create_event_frequency_condition(
interval="1h", value=1
)
self.user_frequency_condition = self.create_event_frequency_condition(
interval="1m",
id="EventUniqueUserFrequencyCondition",
)
event_frequency_percent_condition = self.create_event_frequency_condition(
interval="5m", id="EventFrequencyPercentCondition", value=1.0
)
self.rule1 = self.create_project_rule(
project=self.project,
condition_data=[self.event_frequency_condition],
environment_id=self.environment.id,
)
self.event1 = self.create_event(
self.project.id, FROZEN_TIME, "group-1", self.environment.name
)
self.create_event(self.project.id, FROZEN_TIME, "group-1", self.environment.name)
assert self.event1.group
self.group1 = self.event1.group
self.rule2 = self.create_project_rule(
project=self.project, condition_data=[self.user_frequency_condition]
)
self.event2 = self.create_event(
self.project.id, FROZEN_TIME, "group-2", self.environment.name
)
assert self.event2.group
self.create_event(self.project.id, FROZEN_TIME, "group-2", self.environment.name)
self.group2 = self.event2.group
self.rulegroup_event_mapping_one = {
f"{self.rule1.id}:{self.group1.id}": {self.event1.event_id},
f"{self.rule2.id}:{self.group2.id}": {self.event2.event_id},
}
self.project_two = self.create_project(organization=self.organization)
self.environment2 = self.create_environment(project=self.project_two)
self.rule3 = self.create_project_rule(
project=self.project_two,
condition_data=[self.event_frequency_condition2],
environment_id=self.environment2.id,
)
self.event3 = self.create_event(
self.project_two.id, FROZEN_TIME, "group-3", self.environment2.name
)
self.create_event(self.project_two.id, FROZEN_TIME, "group-3", self.environment2.name)
self.create_event(self.project_two.id, FROZEN_TIME, "group-3", self.environment2.name)
self.create_event(self.project_two.id, FROZEN_TIME, "group-3", self.environment2.name)
assert self.event3.group
self.group3 = self.event3.group
self.rule4 = self.create_project_rule(
project=self.project_two, condition_data=[event_frequency_percent_condition]
)
self.event4 = self.create_event(self.project_two.id, FROZEN_TIME, "group-4")
assert self.event4.group
self.create_event(self.project_two.id, FROZEN_TIME, "group-4")
self._make_sessions(60, project=self.project_two)
self.group4 = self.event4.group
self.rulegroup_event_mapping_two = {
f"{self.rule3.id}:{self.group3.id}": {self.event3.event_id},
f"{self.rule4.id}:{self.group4.id}": {self.event4.event_id},
}
self.buffer_mapping = {
self.project.id: self.rulegroup_event_mapping_one,
self.project_two.id: self.rulegroup_event_mapping_two,
}
buffer.backend.push_to_sorted_set(key=PROJECT_ID_BUFFER_LIST_KEY, value=self.project.id)
buffer.backend.push_to_sorted_set(key=PROJECT_ID_BUFFER_LIST_KEY, value=self.project_two.id)
def _push_base_events(self) -> None:
self.push_to_hash(self.project.id, self.rule1.id, self.group1.id, self.event1.event_id)
self.push_to_hash(self.project.id, self.rule2.id, self.group2.id, self.event2.event_id)
self.push_to_hash(self.project_two.id, self.rule3.id, self.group3.id, self.event3.event_id)
self.push_to_hash(self.project_two.id, self.rule4.id, self.group4.id, self.event4.event_id)
| ProcessDelayedAlertConditionsTestBase |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 103963,
"end": 104197
} | class ____(SendrecvmsgBase):
# Defines flags to be checked in msg_flags for SCTP sockets.
@property
def msg_flags_eor_indicator(self):
return super().msg_flags_eor_indicator | socket.MSG_EOR
| SendrecvmsgSCTPFlagsBase |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_capture_strategies.py | {
"start": 9040,
"end": 10566
} | class ____(CaptureStrategy):
def _capture(
self, model, args, kwargs, dynamic_shapes
) -> torch.export.ExportedProgram:
ep = torch.export.draft_export(
model, args, kwargs=kwargs, dynamic_shapes=dynamic_shapes
)
report = ep._report # type: ignore[attr-defined]
if not report.successful():
self._exception = RuntimeError(str(report))
self._verbose_print(f"Draft Export report:\n{report}")
return ep
def _enter(self, model) -> None:
model_repr = _take_first_line(repr(model))
self._verbose_print(
f"Obtain model graph for `{model_repr}` with `torch.export.draft_export`..."
)
def _success(self, model) -> None:
model_repr = _take_first_line(repr(model))
self._verbose_print(
f"Obtain model graph for `{model_repr}` with `torch.export.draft_export`... ✅"
)
def _failure(self, model, e) -> None:
del e # Unused
model_repr = _take_first_line(repr(model))
self._verbose_print(
f"Obtain model graph for `{model_repr}` with `torch.export.draft_export`... ❌"
)
CAPTURE_STRATEGIES: tuple[type[CaptureStrategy], ...] = (
TorchExportNonStrictStrategy, # strict=False is preferred over strict=True because it does not have dynamo issues
TorchExportStrictStrategy,
)
if _flags.ENABLE_DRAFT_EXPORT:
CAPTURE_STRATEGIES = (*CAPTURE_STRATEGIES, TorchExportDraftExportStrategy)
| TorchExportDraftExportStrategy |
python | huggingface__transformers | src/transformers/models/mistral3/modular_mistral3.py | {
"start": 9743,
"end": 14388
} | class ____(LlavaForConditionalGeneration):
def get_image_features(
self,
pixel_values: torch.FloatTensor,
image_sizes: torch.Tensor,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
**kwargs,
):
return self.model.get_image_features(
pixel_values=pixel_values,
image_sizes=image_sizes,
vision_feature_layer=vision_feature_layer,
**kwargs,
)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = 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,
logits_to_keep: Union[int, torch.Tensor] = 0,
image_sizes: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, Mistral3CausalLMOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
Example:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration
>>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
>>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
>>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(**inputs, max_new_tokens=15)
>>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"What is the image?The image depicts two cats lying on a pink blanket."
```"""
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
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.model(
input_ids=input_ids,
pixel_values=pixel_values,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
cache_position=cache_position,
image_sizes=image_sizes,
**kwargs,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(
logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs
)
return Mistral3CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
image_hidden_states=outputs.image_hidden_states,
)
__all__ = [
"Mistral3Model",
"Mistral3PreTrainedModel",
"Mistral3ForConditionalGeneration",
]
| Mistral3ForConditionalGeneration |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/input_util_test.py | {
"start": 21052,
"end": 22941
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
mesh = mesh_util.create_mesh(
devices=['CPU:%d' % i for i in range(8)],
mesh_dims=[(MESH_DIM_BATCH, 8)])
self.mesh = self.configTestMesh({'CPU': mesh})
self.images = stateless_random_ops.stateless_random_uniform(
[8, 8, 3], seed=(1, 2), minval=0, maxval=255)
def testToTensorList(self):
dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat(8)
images_layout = Layout.replicated(self.mesh, rank=4)
d_dataset = input_util.DTensorDataset(
dataset=dataset,
global_batch_size=4,
mesh=self.mesh,
layouts=images_layout)
d_iterator = iter(d_dataset)
spec = input_util._DTensorIteratorSpec(
global_element_spec=d_iterator._global_element_spec,
layouts_str=d_iterator._layouts_str)
value = d_iterator
tensor_list = spec._to_tensor_list(value)
self.assertListEqual(tensor_list, [d_iterator._iterator_resource_dtensor])
def testFromTensorList(self):
dataset = dataset_ops.DatasetV2.from_tensors(self.images).repeat(8)
images_layout = Layout.replicated(self.mesh, rank=4)
d_dataset = input_util.DTensorDataset(
dataset=dataset,
global_batch_size=4,
mesh=self.mesh,
layouts=images_layout)
d_iterator = iter(d_dataset)
spec = input_util._DTensorIteratorSpec(
global_element_spec=d_iterator._global_element_spec,
layouts_str=d_iterator._layouts_str)
tensor_list = [d_iterator._iterator_resource_dtensor]
value = spec._from_tensor_list(tensor_list)
self.assertIsInstance(value, input_util._DTensorIterator)
self.assertIs(value._global_element_spec, d_iterator._global_element_spec)
self.assertEqual(value._layouts, d_iterator._layouts)
if __name__ == '__main__':
tf_test.main()
| DTensorIteratorSpecTest |
python | scipy__scipy | scipy/interpolate/tests/test_bary_rational.py | {
"start": 11682,
"end": 12231
} | class ____:
# FloaterHormann class with reference batch behaviour
def __init__(self, x, y, axis):
y = np.moveaxis(y, axis, -1)
self._batch_shape = y.shape[:-1]
self._interps = [FloaterHormannInterpolator(x, yi,)
for yi in y.reshape(-1, y.shape[-1])]
self._axis = axis
def __call__(self, x):
y = [interp(x) for interp in self._interps]
y = np.reshape(y, self._batch_shape + x.shape)
return np.moveaxis(y, -1, self._axis) if x.shape else y
| BatchFloaterHormann |
python | pytorch__pytorch | torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py | {
"start": 237,
"end": 7778
} | class ____(BaseDataSparsifier):
r"""L1-Norm Sparsifier
This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the
ones with the lowest norm. The level of sparsity defines how many of the
blocks is removed.
This sparsifier is controlled by three variables:
1. `sparsity_level` defines the number of *sparse blocks* that are zeroed-out
2. `sparse_block_shape` defines the shape of the sparse blocks. Note that
the sparse blocks originate at the zero-index of the tensor.
3. `zeros_per_block` is the number of zeros that we are expecting in each
sparse block. By default we assume that all elements within a block are
zeroed-out. However, setting this variable sets the target number of
zeros per block. The zeros within each block are chosen as the *smallest
absolute values*.
Args:
sparsity_level: The target level of sparsity
sparse_block_shape: The shape of a sparse block
zeros_per_block: Number of zeros in a sparse block
Note::
All arguments to the DataNormSparsifier constructor are "default"
arguments and could be overridden by the configuration provided in the
`add_data` step.
"""
def __init__(
self,
data_list: list[tuple[str, Any]] | None = None,
sparsity_level: float = 0.5,
sparse_block_shape: tuple[int, int] = (1, 4),
zeros_per_block: int | None = None,
norm: str = "L1",
):
if zeros_per_block is None:
zeros_per_block = reduce(operator.mul, sparse_block_shape)
if norm not in ["L1", "L2"]:
raise AssertionError("only L1 and L2 norm supported at the moment")
defaults = {
"sparsity_level": sparsity_level,
"sparse_block_shape": sparse_block_shape,
"zeros_per_block": zeros_per_block,
}
self.norm = norm
super().__init__(data_list=data_list, **defaults)
def __get_scatter_folded_mask(
self, data, dim, indices, output_size, sparse_block_shape
):
mask = torch.ones_like(data)
mask.scatter_(dim=dim, index=indices, value=0) # zeroing out
mask = F.fold(
mask,
output_size=output_size,
kernel_size=sparse_block_shape,
stride=sparse_block_shape,
)
mask = mask.to(torch.int8)
return mask
def __get_block_level_mask(self, data, sparse_block_shape, zeros_per_block):
# Assume data is a squeezed tensor
height, width = data.shape[-2], data.shape[-1]
block_height, block_width = sparse_block_shape
values_per_block = block_height * block_width
# just return zeros if zeroing all elements in block
if values_per_block == zeros_per_block:
return torch.zeros_like(data, dtype=torch.int8)
# creating additional height and width to support padding
dh = (block_height - height % block_height) % block_height
dw = (block_width - width % block_width) % block_width
# create a new padded tensor like data (to match the block_shape)
padded_data = torch.ones(
height + dh, width + dw, dtype=data.dtype, device=data.device
)
padded_data = (
padded_data * torch.nan
) # can also be replaced with 0 to stop the removal of edge data
padded_data[0:height, 0:width] = data
unfolded_data = F.unfold(
padded_data[None, None, :],
kernel_size=sparse_block_shape,
stride=sparse_block_shape,
)
_, sorted_idx = torch.sort(unfolded_data, dim=1)
sorted_idx = sorted_idx[
:, :zeros_per_block, :
] # zero out zeros_per_block number of elements
mask = self.__get_scatter_folded_mask(
data=unfolded_data,
dim=1,
indices=sorted_idx,
output_size=padded_data.shape,
sparse_block_shape=sparse_block_shape,
)
mask = (
mask.squeeze(0).squeeze(0)[:height, :width].contiguous()
) # remove padding and make contiguous
return mask
def __get_data_level_mask(self, data, sparsity_level, sparse_block_shape):
height, width = data.shape[-2], data.shape[-1]
block_height, block_width = sparse_block_shape
dh = (block_height - height % block_height) % block_height
dw = (block_width - width % block_width) % block_width
data_norm = F.avg_pool2d(
data[None, None, :],
kernel_size=sparse_block_shape,
stride=sparse_block_shape,
ceil_mode=True,
)
values_per_block = reduce(operator.mul, sparse_block_shape)
data_norm = data_norm.flatten()
num_blocks = len(data_norm)
data_norm = data_norm.repeat(
1, values_per_block, 1
) # get similar shape after unfold
_, sorted_idx = torch.sort(data_norm, dim=2)
threshold_idx = round(sparsity_level * num_blocks) # number of blocks to remove
sorted_idx = sorted_idx[:, :, :threshold_idx]
mask = self.__get_scatter_folded_mask(
data=data_norm,
dim=2,
indices=sorted_idx,
output_size=(height + dh, width + dw),
sparse_block_shape=sparse_block_shape,
)
mask = mask.squeeze(0).squeeze(0)[
:height, :width
] # squeeze only the first 2 dimension
return mask
def update_mask( # type: ignore[override]
self, name, data, sparsity_level, sparse_block_shape, zeros_per_block, **kwargs
):
values_per_block = reduce(operator.mul, sparse_block_shape)
if zeros_per_block > values_per_block:
raise ValueError(
"Number of zeros per block cannot be more than "
"the total number of elements in that block."
)
if zeros_per_block < 0:
raise ValueError("Number of zeros per block should be positive.")
if self.norm == "L1":
data_norm = torch.abs(data).squeeze() # absolute value based (L1)
else:
data_norm = (data * data).squeeze() # square every element for L2
if len(data_norm.shape) > 2: # only supports 2 dimensional data at the moment
raise ValueError("only supports 2-D at the moment")
elif len(data_norm.shape) == 1: # in case the data is bias (or 1D)
data_norm = data_norm[None, :]
mask = self.get_mask(name)
if sparsity_level <= 0 or zeros_per_block == 0:
mask.data = torch.ones_like(mask)
elif sparsity_level >= 1.0 and (zeros_per_block == values_per_block):
mask.data = torch.zeros_like(mask)
# Fetch the high level mask that zeros out entire blocks
data_lvl_mask = self.__get_data_level_mask(
data=data_norm,
sparsity_level=sparsity_level,
sparse_block_shape=sparse_block_shape,
)
# Fetch block level mask that zeros out 'zeros_per_block' number of elements in every block
block_lvl_mask = self.__get_block_level_mask(
data=data_norm,
sparse_block_shape=sparse_block_shape,
zeros_per_block=zeros_per_block,
)
# zero out the entries inside those blocks whose block is sparsified
mask.data = torch.where(data_lvl_mask == 1, data_lvl_mask, block_lvl_mask)
| DataNormSparsifier |
python | apache__airflow | providers/standard/src/airflow/providers/standard/sensors/time.py | {
"start": 1773,
"end": 4513
} | class ____(BaseSensorOperator):
"""
Waits until the specified time of the day.
:param target_time: time after which the job succeeds
:param deferrable: whether to defer execution
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/operator:TimeSensor`
"""
start_trigger_args = StartTriggerArgs(
trigger_cls="airflow.providers.standard.triggers.temporal.DateTimeTrigger",
trigger_kwargs={"moment": "", "end_from_trigger": False},
next_method="execute_complete",
next_kwargs=None,
timeout=None,
)
start_from_trigger = False
def __init__(
self,
*,
target_time: datetime.time,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
start_from_trigger: bool = False,
end_from_trigger: bool = False,
trigger_kwargs: dict[str, Any] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
# Create a "date-aware" timestamp that will be used as the "target_datetime". This is a requirement
# of the DateTimeTrigger
# Get date considering dag.timezone
aware_time = timezone.coerce_datetime(
datetime.datetime.combine(
datetime.datetime.now(self.dag.timezone), target_time, self.dag.timezone
)
)
# Now that the dag's timezone has made the datetime timezone aware, we need to convert to UTC
self.target_datetime = timezone.convert_to_utc(aware_time)
self.deferrable = deferrable
self.start_from_trigger = start_from_trigger
self.end_from_trigger = end_from_trigger
if self.start_from_trigger:
self.start_trigger_args.trigger_kwargs = dict(
moment=self.target_datetime, end_from_trigger=self.end_from_trigger
)
def execute(self, context: Context) -> None:
if self.deferrable:
self.defer(
trigger=DateTimeTrigger(
moment=self.target_datetime, # This needs to be an aware timestamp
end_from_trigger=self.end_from_trigger,
),
method_name="execute_complete",
)
else:
super().execute(context)
def execute_complete(self, context: Context, event: Any = None) -> None:
return None
def poke(self, context: Context) -> bool:
self.log.info("Checking if the time (%s) has come", self.target_datetime)
# self.target_date has been converted to UTC, so we do not need to convert timezone
return timezone.utcnow() > self.target_datetime
| TimeSensor |
python | pypa__warehouse | tests/unit/manage/views/test_teams.py | {
"start": 995,
"end": 5820
} | class ____:
@pytest.mark.usefixtures("_enable_organizations")
def test_manage_team(self, db_request, organization_service, user_service):
team = TeamFactory.create()
view = team_views.ManageTeamSettingsViews(team, db_request)
result = view.manage_team()
form = result["save_team_form"]
assert view.request == db_request
assert view.organization_service == organization_service
assert view.user_service == user_service
assert result == {
"team": team,
"save_team_form": form,
}
@pytest.mark.usefixtures("_enable_organizations")
def test_save_team(self, db_request, pyramid_user, organization_service):
team = TeamFactory.create(name="Team Name")
db_request.POST = MultiDict({"name": "Team name"})
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foo/bar/")
view = team_views.ManageTeamSettingsViews(team, db_request)
result = view.save_team()
assert isinstance(result, HTTPSeeOther)
assert result.headers["Location"] == "/foo/bar/"
assert team.name == "Team name"
@pytest.mark.usefixtures("_enable_organizations")
def test_save_team_validation_fails(self, db_request, organization_service):
organization = OrganizationFactory.create()
team = TeamFactory.create(
name="Team Name",
organization=organization,
)
TeamFactory.create(
name="Existing Team Name",
organization=organization,
)
db_request.POST = MultiDict({"name": "Existing Team Name"})
view = team_views.ManageTeamSettingsViews(team, db_request)
result = view.save_team()
form = result["save_team_form"]
assert result == {
"team": team,
"save_team_form": form,
}
assert team.name == "Team Name"
assert form.name.errors == [
"This team name has already been used. Choose a different team name."
]
@pytest.mark.usefixtures("_enable_organizations")
def test_delete_team(
self,
db_request,
pyramid_user,
organization_service,
user_service,
monkeypatch,
):
team = TeamFactory.create()
db_request.POST = MultiDict({"confirm_team_name": team.name})
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foo/bar/")
send_email = pretend.call_recorder(lambda *a, **kw: None)
monkeypatch.setattr(team_views, "send_team_deleted_email", send_email)
view = team_views.ManageTeamSettingsViews(team, db_request)
result = view.delete_team()
assert isinstance(result, HTTPSeeOther)
assert result.headers["Location"] == "/foo/bar/"
assert send_email.calls == [
pretend.call(
db_request,
set(),
organization_name=team.organization.name,
team_name=team.name,
),
]
@pytest.mark.usefixtures("_enable_organizations")
def test_delete_team_no_confirm(
self,
db_request,
pyramid_user,
organization_service,
user_service,
monkeypatch,
):
team = TeamFactory.create()
db_request.POST = MultiDict()
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foo/bar/")
view = team_views.ManageTeamSettingsViews(team, db_request)
with pytest.raises(HTTPSeeOther):
view.delete_team()
assert db_request.session.flash.calls == [
pretend.call("Confirm the request", queue="error")
]
@pytest.mark.usefixtures("_enable_organizations")
def test_delete_team_wrong_confirm(
self,
db_request,
pyramid_user,
organization_service,
user_service,
monkeypatch,
):
team = TeamFactory.create(name="Team Name")
db_request.POST = MultiDict({"confirm_team_name": "TEAM NAME"})
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.route_path = pretend.call_recorder(lambda *a, **kw: "/foo/bar/")
view = team_views.ManageTeamSettingsViews(team, db_request)
with pytest.raises(HTTPSeeOther):
view.delete_team()
assert db_request.session.flash.calls == [
pretend.call(
(
"Could not delete team - "
"'TEAM NAME' is not the same as 'Team Name'"
),
queue="error",
)
]
| TestManageTeamSettings |
python | getsentry__sentry | src/sentry/backup/crypto.py | {
"start": 1440,
"end": 1678
} | class ____(ABC):
"""
A `IO[bytes]`-wrapper that contains relevant information and methods to encrypt some an in-memory JSON-ifiable dict.
"""
@abstractmethod
def get_public_key_pem(self) -> bytes:
pass
| Encryptor |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 93946,
"end": 94948
} | class ____:
def __init__(self, type_):
"""Supported are GRAY, RGB and CMYK."""
if isinstance( type_, mupdf.FzColorspace):
self.this = type_
elif type_ == CS_GRAY:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_GRAY)
elif type_ == CS_CMYK:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_CMYK)
elif type_ == CS_RGB:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_RGB)
else:
self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_RGB)
def __repr__(self):
x = ("", "GRAY", "", "RGB", "CMYK")[self.n]
return "Colorspace(CS_%s) - %s" % (x, self.name)
def _name(self):
return mupdf.fz_colorspace_name(self.this)
@property
def n(self):
"""Size of one pixel."""
return mupdf.fz_colorspace_n(self.this)
@property
def name(self):
"""Name of the Colorspace."""
return self._name()
| Colorspace |
python | HIPS__autograd | autograd/core.py | {
"start": 8318,
"end": 8361
} | class ____(Box):
__slots__ = []
| SparseBox |
python | allegroai__clearml | clearml/utilities/deferred.py | {
"start": 1177,
"end": 1520
} | class ____(dict):
def __init__(self, factory: Callable[[Any], Any], *args: Any, **kwargs: Any) -> None:
super(ParameterizedDefaultDict, self).__init__(*args, **kwargs)
self._factory = factory
def __missing__(self, key: Any) -> Any:
self[key] = self._factory(key)
return self[key]
| ParameterizedDefaultDict |
python | tensorflow__tensorflow | tensorflow/python/tpu/tpu_test.py | {
"start": 3136,
"end": 4248
} | class ____(test.TestCase):
def testUsingInfeedQueueWithRegularizer(self):
"""Test that Layer regularizers can reference data created in loops."""
with ops.Graph().as_default():
def make_regularizer(scale):
def regularizer(inputs):
return scale * math_ops.reduce_sum(math_ops.square(inputs))
return regularizer
def training_step(inputs, scale):
outputs = convolutional.conv2d(
inputs,
filters=16,
kernel_size=(3, 3),
data_format="channels_first",
kernel_regularizer=make_regularizer(scale))
loss = math_ops.reduce_mean(math_ops.square(outputs))
return loss.op
inputs = array_ops.zeros(shape=(128, 32, 32, 16))
scale = array_ops.ones(shape=())
infeed = tpu_feed.InfeedQueue(
tuple_types=[dtypes.float32, dtypes.float32],
tuple_shapes=[inputs.shape, scale.shape])
def loop():
return training_loop.repeat(5, training_step, infeed_queue=infeed)
# This should not throw an error.
tpu.rewrite(loop)
| TPULayerRewriteTest |
python | pytorch__pytorch | test/torch_np/test_ufuncs_basic.py | {
"start": 4259,
"end": 6334
} | class ____(TestCase):
def get_xy(self, ufunc):
return np.arange(5, dtype="float64"), np.arange(8, 13, dtype="float64")
@parametrize_binary_ufuncs
def test_scalar(self, ufunc):
# check that ufunc accepts a scalar and the result is convertible to scalar
xy = self.get_xy(ufunc)
x, y = xy[0][0], xy[1][0]
float(ufunc(x, y))
@parametrize_binary_ufuncs
def test_vector_vs_scalar(self, ufunc):
x, y = self.get_xy(ufunc)
assert_equal(ufunc(x, y), [ufunc(a, b) for a, b in zip(x, y)])
@parametrize_casting
@parametrize_binary_ufuncs
@parametrize("out_dtype", ["float64", "complex128", "float32"])
def test_xy_and_out_casting(self, ufunc, casting, out_dtype):
x, y = self.get_xy(ufunc)
out = np.empty_like(x, dtype=out_dtype)
if ufunc in no_complex and np.issubdtype(out_dtype, np.complexfloating):
raise SkipTest(f"{ufunc} does not accept complex.")
can_cast_x = np.can_cast(x, out_dtype, casting=casting)
can_cast_y = np.can_cast(y, out_dtype, casting=casting)
if not (can_cast_x and can_cast_y):
with assert_raises(TypeError):
ufunc(x, out=out, casting=casting)
else:
result = ufunc(x, y, out=out, casting=casting)
assert result.dtype == out_dtype
assert result is out
@parametrize_binary_ufuncs
def test_xy_and_out_broadcast(self, ufunc):
x, y = self.get_xy(ufunc)
y = y[:, None]
out = np.empty((2, y.shape[0], x.shape[0]))
x_b = np.broadcast_to(x, out.shape)
y_b = np.broadcast_to(y, out.shape)
res_out = ufunc(x, y, out=out)
res_bcast = ufunc(x_b, y_b)
# TODO: switching the order causes a graph break, failing the test.
# See test/dynamo/test_misc.py -k test_numpy_graph_break
assert res_out is out
assert_equal(res_out, res_bcast)
dtypes_numeric = [np.int32, np.float32, np.float64, np.complex128]
@instantiate_parametrized_tests
| TestBinaryUfuncs |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 73534,
"end": 74859
} | class ____(Operation):
def __init__(self, axis=None, dtype=None, *, name=None):
super().__init__(name=name)
self.axis = axis
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
def call(self, x):
return backend.numpy.cumsum(x, axis=self.axis, dtype=self.dtype)
def compute_output_spec(self, x):
if self.axis is None:
if None in x.shape:
output_shape = (None,)
else:
output_shape = (int(np.prod(x.shape)),)
else:
output_shape = x.shape
output_dtype = (
backend.standardize_dtype(x.dtype)
if self.dtype is None
else self.dtype
)
if output_dtype == "bool":
output_dtype = "int32"
return KerasTensor(output_shape, output_dtype)
@keras_export(["keras.ops.cumsum", "keras.ops.numpy.cumsum"])
def cumsum(x, axis=None, dtype=None):
"""Returns the cumulative sum of elements along a given axis.
Args:
x: Input tensor.
axis: Axis along which the cumulative sum is computed.
By default the input is flattened.
dtype: dtype of returned tensor. Defaults to x.dtype.
Returns:
Output tensor.
"""
return Cumsum(axis=axis, dtype=dtype)(x)
| Cumsum |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called.py | {
"start": 1410,
"end": 1581
} | class ____(ctypes.Union):
def __init__(self):
pass
# Should not be called on abstract __init__ methods
# https://github.com/pylint-dev/pylint/issues/3975
| MyUnion |
python | encode__django-rest-framework | rest_framework/fields.py | {
"start": 62139,
"end": 64294
} | class ____(Field):
child = _UnvalidatedField()
initial = {}
default_error_messages = {
'not_a_dict': _('Expected a dictionary of items but got type "{input_type}".'),
'empty': _('This dictionary may not be empty.'),
}
def __init__(self, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child))
self.allow_empty = kwargs.pop('allow_empty', True)
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
assert self.child.source is None, (
"The `source` argument is not meaningful when applied to a `child=` field. "
"Remove `source=` from the field declaration."
)
super().__init__(**kwargs)
self.child.bind(field_name='', parent=self)
def get_value(self, dictionary):
# We override the default field access in order to support
# dictionaries in HTML forms.
if html.is_html_input(dictionary):
return html.parse_html_dict(dictionary, prefix=self.field_name)
return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
"""
Dicts of native values <- Dicts of primitive datatypes.
"""
if html.is_html_input(data):
data = html.parse_html_dict(data)
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
self.fail('empty')
return self.run_child_validation(data)
def to_representation(self, value):
return {
str(key): self.child.to_representation(val) if val is not None else None
for key, val in value.items()
}
def run_child_validation(self, data):
result = {}
errors = {}
for key, value in data.items():
key = str(key)
try:
result[key] = self.child.run_validation(value)
except ValidationError as e:
errors[key] = e.detail
if not errors:
return result
raise ValidationError(errors)
| DictField |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 5538,
"end": 5682
} | class ____(BaseModel):
prompt_tokens: int | None = None
completion_tokens: int | None = None
total_tokens: int | None = None
| ChatUsage |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 24852,
"end": 24994
} | class ____(FloatingPoint):
"""
Handles the double datatype. Double-precision IEEE
floating-point.
"""
format = "f8"
| Double |
python | ethereum__web3.py | web3/types.py | {
"start": 10102,
"end": 10202
} | class ____(TypedDict):
difficulty: int
head: HexStr
network: int
version: int
| Protocol |
python | astropy__astropy | astropy/table/mixins/dask.py | {
"start": 109,
"end": 225
} | class ____(ParentDtypeInfo):
@staticmethod
def default_format(val):
return f"{val.compute()}"
| DaskInfo |
python | tqdm__tqdm | examples/tqdm_wget.py | {
"start": 1767,
"end": 3511
} | class ____(tqdm):
"""Alternative Class-based version of the above.
Provides `update_to(n)` which uses `tqdm.update(delta_n)`.
Inspired by [twine#242](https://github.com/pypa/twine/pull/242),
[here](https://github.com/pypa/twine/commit/42e55e06).
"""
def update_to(self, b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks transferred so far [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
self.total = tsize
return self.update(b * bsize - self.n) # also sets self.n = b * bsize
opts = docopt(__doc__)
eg_link = opts['--url']
eg_file = eg_link.replace('/', ' ').split()[-1]
eg_out = opts['--output'].replace("/dev/null", devnull)
# with tqdm(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
# desc=eg_file) as t: # all optional kwargs
# urllib.urlretrieve(eg_link, filename=eg_out,
# reporthook=my_hook(t), data=None)
with TqdmUpTo(unit='B', unit_scale=True, unit_divisor=1024, miniters=1,
desc=eg_file) as t: # all optional kwargs
urllib.urlretrieve( # nosec
eg_link, filename=eg_out, reporthook=t.update_to, data=None)
t.total = t.n
# Even simpler progress by wrapping the output file's `write()`
response = urllib.urlopen(eg_link) # nosec
with tqdm.wrapattr(open(eg_out, "wb"), "write",
miniters=1, desc=eg_file,
total=getattr(response, 'length', None)) as fout:
for chunk in response:
fout.write(chunk)
| TqdmUpTo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.