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 | pytorch__pytorch | torch/ao/pruning/_experimental/data_sparsifier/lightning/tests/test_callbacks.py | {
"start": 5142,
"end": 12022
} | class ____(TestCase):
"""Class to test in-training version of lightning callback
Simulates model training and makes sure that each hook is doing what is expected
"""
def _check_on_train_start(
self, pl_module, callback, sparsifier_args, scheduler_args
):
"""Makes sure that the data_sparsifier and data_scheduler objects are being created
correctly.
Basically, confirms that the input args and sparsifier/scheduler args are in-line.
"""
callback.on_train_start(42, pl_module) # 42 is a dummy value
# sparsifier and scheduler instantiated
assert (
callback.data_scheduler is not None and callback.data_sparsifier is not None
)
# data sparsifier args are correct
for key, value in sparsifier_args.items():
assert callback.data_sparsifier.defaults[key] == value
# data scheduler args are correct
for key, value in scheduler_args.items():
assert getattr(callback.data_scheduler, key) == value
def _simulate_update_param_model(self, pl_module):
"""This function might not be needed as the model is being copied
during train_epoch_end() but good to have if things change in the future
"""
for _, param in pl_module.model.named_parameters():
param.data = param + 1
def _check_on_train_epoch_start(self, pl_module, callback):
"""Basically ensures that the sparsifier's state is correctly being restored.
The state_dict() comparison is needed. Consider the flow -
**Epoch: 1**
1. on_train_epoch_start(): Nothing happens (for now)
2. on_train_epoch_end():
a) the model is copied into the data_sparsifier
b) .step() is called
c) internally, the state of each layer of the model inside
data sparsifier changes
**Epoch: 2**
1. on_train_epoch_start(): Assume nothing happens
2. on_train_epoch_end():
a) the model is copied into the data_sparsifier.
But wait! you need the config to attach layer
of the module to the sparsifier. If config is None,
the data_sparsifier uses the default config which we
do not want as the config of each layer changes after
.step()
Hence, we need to dump and restore the state_dict() every time because we're
copying the model after each epoch.
Hence, it is essential to make sure that the sparsifier's state_dict() is being
correctly dumped and restored.
"""
# check if each component of state dict is being loaded correctly
callback.on_train_epoch_start(42, pl_module)
if callback.data_sparsifier_state_dict is None:
return
data_sparsifier_state_dict = callback.data_sparsifier.state_dict()
# compare container objects
container_obj1 = data_sparsifier_state_dict["_container"]
container_obj2 = callback.data_sparsifier_state_dict["_container"]
assert len(container_obj1) == len(container_obj2)
for key, value in container_obj2.items():
assert key in container_obj1
assert torch.all(value == container_obj1[key])
# compare state objects
state_obj1 = data_sparsifier_state_dict["state"]
state_obj2 = callback.data_sparsifier_state_dict["state"]
assert len(state_obj1) == len(state_obj2)
for key, value in state_obj2.items():
assert key in state_obj1
assert "mask" in value and "mask" in state_obj1[key]
assert torch.all(value["mask"] == state_obj1[key]["mask"])
# compare data_groups dict
data_grp1 = data_sparsifier_state_dict["data_groups"]
data_grp2 = callback.data_sparsifier_state_dict["data_groups"]
assert len(data_grp1) == len(data_grp2)
for key, value in data_grp2.items():
assert key in data_grp1
assert value == data_grp1[key]
def _check_on_train_epoch_end(self, pl_module, callback):
"""Checks the following -
1. sparsity is correctly being achieved after .step()
2. scheduler and data_sparsifier sparsity levels are in-line
"""
callback.on_train_epoch_end(42, pl_module)
data_scheduler = callback.data_scheduler
base_sl = data_scheduler.base_param
for name, _ in pl_module.model.named_parameters():
valid_name = _get_valid_name(name)
mask = callback.data_sparsifier.get_mask(name=valid_name)
# check sparsity levels
assert (1.0 - mask.float().mean()) > 0 # some sparsity level achieved
last_sl = data_scheduler.get_last_param()
last_epoch = data_scheduler.last_epoch
# check sparsity levels of scheduler
log_last_sl = math.log(last_sl[valid_name])
log_actual_sl = math.log(
base_sl[valid_name] * (data_scheduler.gamma**last_epoch)
)
assert log_last_sl == log_actual_sl
def _check_on_train_end(self, pl_module, callback):
"""Confirms that the mask is squashed after the training ends
This is achieved by making sure that each parameter in the internal container
are not parametrized.
"""
callback.on_train_end(42, pl_module)
# check that the masks have been squashed
for name, _ in pl_module.model.named_parameters():
valid_name = _get_valid_name(name)
assert not is_parametrized(callback.data_sparsifier._continer, valid_name)
@unittest.skipIf(
not importlib.util.find_spec("pytorch_lightning"), "No pytorch_lightning"
)
def test_train_aware_callback(self):
sparsifier_args = {
"sparsity_level": 0.5,
"sparse_block_shape": (1, 4),
"zeros_per_block": 4,
}
scheduler_args = {"gamma": 2, "step_size": 1}
callback = TrainingAwareDataSparsity(
data_sparsifier_class=DataNormSparsifier,
data_sparsifier_args=sparsifier_args,
data_scheduler_class=StepSLScheduler,
data_scheduler_args=scheduler_args,
)
pl_module = _make_lightning_module(100, [128, 256, 16])
# simulate the training process and check all steps
self._check_on_train_start(pl_module, callback, sparsifier_args, scheduler_args)
num_epochs = 5
for _ in range(num_epochs):
self._check_on_train_epoch_start(pl_module, callback)
self._simulate_update_param_model(pl_module)
self._check_on_train_epoch_end(pl_module, callback)
if __name__ == "__main__":
run_tests()
| TestTrainingAwareCallback |
python | getsentry__sentry | src/social_auth/fields.py | {
"start": 323,
"end": 2141
} | class ____(TextField):
"""Simple JSON field that stores python structures as JSON strings
on database.
"""
def contribute_to_class(self, cls: type[Model], name: str, private_only: bool = False) -> None:
"""
Add a descriptor for backwards compatibility
with previous Django behavior.
"""
super().contribute_to_class(cls, name, private_only=private_only)
setattr(cls, name, Creator(self))
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if self.blank and not value:
return None
if isinstance(value, str):
try:
return json.loads(value)
except Exception as e:
raise ValidationError(str(e))
else:
return value
def validate(self, value, model_instance):
"""Check value is a valid JSON string, raise ValidationError on
error."""
if isinstance(value, str):
super().validate(value, model_instance)
try:
json.loads(value)
except Exception as e:
raise ValidationError(str(e))
def get_prep_value(self, value):
"""Convert value to JSON string before save"""
try:
return json.dumps(value)
except Exception as e:
raise ValidationError(str(e))
def value_to_string(self, obj):
"""Return value from object converted to string properly"""
return smart_str(self.value_from_object(obj))
def value_from_object(self, obj):
"""Return value dumped to string."""
return self.get_prep_value(super().value_from_object(obj))
| JSONField |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_compute.py | {
"start": 20348,
"end": 25848
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.__init__",
new=mock_base_gcp_hook_no_default_project_id,
):
self.gce_hook_no_project_id = ComputeEngineHook(gcp_conn_id="test")
@mock.patch("airflow.providers.google.cloud.hooks.compute.ComputeEngineHook._authorize")
@mock.patch("airflow.providers.google.cloud.hooks.compute.build")
def test_gce_client_creation(self, mock_build, mock_authorize):
result = self.gce_hook_no_project_id.get_conn()
mock_build.assert_called_once_with(
"compute", "v1", http=mock_authorize.return_value, cache_discovery=False
)
assert mock_build.return_value == result
@mock.patch("airflow.providers.google.cloud.hooks.compute.ComputeEngineHook.get_conn")
@mock.patch(
"airflow.providers.google.cloud.hooks.compute.ComputeEngineHook._wait_for_operation_to_complete"
)
def test_start_instance_overridden_project_id(self, wait_for_operation_to_complete, get_conn):
start_method = get_conn.return_value.instances.return_value.start
execute_method = start_method.return_value.execute
execute_method.return_value = {"name": "operation_id"}
wait_for_operation_to_complete.return_value = None
res = self.gce_hook_no_project_id.start_instance(
project_id="example-project", zone=GCE_ZONE, resource_id=GCE_INSTANCE
)
assert res is None
start_method.assert_called_once_with(instance="instance", project="example-project", zone="zone")
execute_method.assert_called_once_with(num_retries=5)
wait_for_operation_to_complete.assert_called_once_with(
project_id="example-project", operation_name="operation_id", zone="zone"
)
@mock.patch("airflow.providers.google.cloud.hooks.compute.ComputeEngineHook.get_conn")
@mock.patch(
"airflow.providers.google.cloud.hooks.compute.ComputeEngineHook._wait_for_operation_to_complete"
)
def test_stop_instance_overridden_project_id(self, wait_for_operation_to_complete, get_conn):
stop_method = get_conn.return_value.instances.return_value.stop
execute_method = stop_method.return_value.execute
execute_method.return_value = {"name": "operation_id"}
wait_for_operation_to_complete.return_value = None
res = self.gce_hook_no_project_id.stop_instance(
project_id="example-project", zone=GCE_ZONE, resource_id=GCE_INSTANCE
)
assert res is None
stop_method.assert_called_once_with(instance="instance", project="example-project", zone="zone")
execute_method.assert_called_once_with(num_retries=5)
wait_for_operation_to_complete.assert_called_once_with(
project_id="example-project", operation_name="operation_id", zone="zone"
)
@mock.patch("airflow.providers.google.cloud.hooks.compute.ComputeEngineHook.get_conn")
@mock.patch(
"airflow.providers.google.cloud.hooks.compute.ComputeEngineHook._wait_for_operation_to_complete"
)
def test_set_machine_type_overridden_project_id(self, wait_for_operation_to_complete, get_conn):
set_machine_type_method = get_conn.return_value.instances.return_value.setMachineType
execute_method = set_machine_type_method.return_value.execute
execute_method.return_value = {"name": "operation_id"}
wait_for_operation_to_complete.return_value = None
res = self.gce_hook_no_project_id.set_machine_type(
body={}, project_id="example-project", zone=GCE_ZONE, resource_id=GCE_INSTANCE
)
assert res is None
set_machine_type_method.assert_called_once_with(
body={}, instance="instance", project="example-project", zone="zone"
)
execute_method.assert_called_once_with(num_retries=5)
wait_for_operation_to_complete.assert_called_once_with(
project_id="example-project", operation_name="operation_id", zone="zone"
)
@mock.patch("airflow.providers.google.cloud.hooks.compute.ComputeEngineHook.get_conn")
@mock.patch(
"airflow.providers.google.cloud.hooks.compute.ComputeEngineHook._wait_for_operation_to_complete"
)
def test_patch_instance_group_manager_overridden_project_id(
self, wait_for_operation_to_complete, get_conn
):
patch_method = get_conn.return_value.instanceGroupManagers.return_value.patch
execute_method = patch_method.return_value.execute
execute_method.return_value = {"name": "operation_id"}
wait_for_operation_to_complete.return_value = None
res = self.gce_hook_no_project_id.patch_instance_group_manager(
project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST,
zone=GCE_ZONE,
resource_id=GCE_INSTANCE_GROUP_MANAGER,
body={},
request_id=GCE_REQUEST_ID,
)
assert res is None
patch_method.assert_called_once_with(
body={},
instanceGroupManager="instance_group_manager",
project="example-project",
requestId="request_id",
zone="zone",
)
execute_method.assert_called_once_with(num_retries=5)
wait_for_operation_to_complete.assert_called_once_with(
operation_name="operation_id", project_id="example-project", zone="zone"
)
| TestGcpComputeHookNoDefaultProjectId |
python | openai__openai-python | tests/api_resources/test_models.py | {
"start": 4391,
"end": 8753
} | class ____:
parametrize = pytest.mark.parametrize(
"async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"]
)
@parametrize
async def test_method_retrieve(self, async_client: AsyncOpenAI) -> None:
model = await async_client.models.retrieve(
"gpt-4o-mini",
)
assert_matches_type(Model, model, path=["response"])
@parametrize
async def test_raw_response_retrieve(self, async_client: AsyncOpenAI) -> None:
response = await async_client.models.with_raw_response.retrieve(
"gpt-4o-mini",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = response.parse()
assert_matches_type(Model, model, path=["response"])
@parametrize
async def test_streaming_response_retrieve(self, async_client: AsyncOpenAI) -> None:
async with async_client.models.with_streaming_response.retrieve(
"gpt-4o-mini",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = await response.parse()
assert_matches_type(Model, model, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
async def test_path_params_retrieve(self, async_client: AsyncOpenAI) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"):
await async_client.models.with_raw_response.retrieve(
"",
)
@parametrize
async def test_method_list(self, async_client: AsyncOpenAI) -> None:
model = await async_client.models.list()
assert_matches_type(AsyncPage[Model], model, path=["response"])
@parametrize
async def test_raw_response_list(self, async_client: AsyncOpenAI) -> None:
response = await async_client.models.with_raw_response.list()
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = response.parse()
assert_matches_type(AsyncPage[Model], model, path=["response"])
@parametrize
async def test_streaming_response_list(self, async_client: AsyncOpenAI) -> None:
async with async_client.models.with_streaming_response.list() as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = await response.parse()
assert_matches_type(AsyncPage[Model], model, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
async def test_method_delete(self, async_client: AsyncOpenAI) -> None:
model = await async_client.models.delete(
"ft:gpt-4o-mini:acemeco:suffix:abc123",
)
assert_matches_type(ModelDeleted, model, path=["response"])
@parametrize
async def test_raw_response_delete(self, async_client: AsyncOpenAI) -> None:
response = await async_client.models.with_raw_response.delete(
"ft:gpt-4o-mini:acemeco:suffix:abc123",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = response.parse()
assert_matches_type(ModelDeleted, model, path=["response"])
@parametrize
async def test_streaming_response_delete(self, async_client: AsyncOpenAI) -> None:
async with async_client.models.with_streaming_response.delete(
"ft:gpt-4o-mini:acemeco:suffix:abc123",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
model = await response.parse()
assert_matches_type(ModelDeleted, model, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
async def test_path_params_delete(self, async_client: AsyncOpenAI) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `model` but received ''"):
await async_client.models.with_raw_response.delete(
"",
)
| TestAsyncModels |
python | pydata__xarray | asv_bench/benchmarks/groupby.py | {
"start": 2941,
"end": 3488
} | class ____(GroupBy):
"""Run groupby tests using dask DataFrame."""
def setup(self, *args, **kwargs):
# Skip testing in CI as it won't ever change in a commit:
_skip_slow()
requires_dask()
super().setup(**kwargs)
self.ds1d = self.ds1d.chunk({"dim_0": 50}).to_dask_dataframe()
self.ds1d_mean = self.ds1d.groupby("b").mean().compute()
def time_binary_op_2d(self):
raise NotImplementedError
def peakmem_binary_op_2d(self):
raise NotImplementedError
| GroupByDaskDataFrame |
python | pytorch__pytorch | benchmarks/serialization/simple_measurement.py | {
"start": 87,
"end": 1062
} | class ____(Benchmark):
def benchmark(self):
x = [torch.ones(200, 200) for i in range(30)]
with Timer() as big1:
torch.save(x, "big_tensor.zip", _use_new_zipfile_serialization=use_new)
with Timer() as big2:
torch.load("big_tensor.zip")
x = [torch.ones(10, 10) for i in range(200)]
with Timer() as small1:
torch.save(x, "small_tensor.zip", _use_new_zipfile_serialization=use_new)
with Timer() as small2:
torch.load("small_tensor.zip")
return {
"Big Tensors Save": big1.ms_duration,
"Big Tensors Load": big2.ms_duration,
"Small Tensors Save": small1.ms_duration,
"Small Tensors Load": small2.ms_duration,
}
if __name__ == "__main__":
bench = Basic(*default_args.bench())
print("Use zipfile serialization:", use_new)
results = bench.run()
bench.print_stats(results, stats=["mean", "median"])
| Basic |
python | pytorch__pytorch | test/test_sparse_semi_structured.py | {
"start": 9985,
"end": 23528
} | class ____(TestCase):
def setUp(self):
if len(SEMI_STRUCTURED_SUPPORTED_BACKENDS) == 0:
self.skipTest('semi-structured sparsity has no available backend!')
if IS_WINDOWS:
self.skipTest("torch.compile not supported on windows")
@inference_dtypes
@parametrize_backends
def test_to_sparse_semi_structured(self, dtype, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
A = rand_sparse_semi_structured_mask(128, 256, dtype=dtype)
A_sparse = to_sparse_semi_structured(A)
assert A.shape == A_sparse.shape
assert A.device == A_sparse.device
assert A.dtype == A_sparse.dtype
assert isinstance(A, torch.Tensor)
assert isinstance(A_sparse, SparseSemiStructuredTensor)
@inference_dtypes
@parametrize_backends
@parametrize("dense_input_shape", [(128, 1), (128, 64), (128, 128)])
def test_mm_sparse_first_NN(self, dense_input_shape, dtype, device, backend):
"""
Ensure torch.mm(A_sparse, B) is correct for float16 and will throw error for int8
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
A = rand_sparse_semi_structured_mask(256, 128, dtype=dtype)
A_sparse = to_sparse_semi_structured(A)
B = torch.rand(dense_input_shape, device=A_sparse.device).to(dtype)
# Currently we don't support int matmul on GPU, so evaluate on CPU and copy over
if dtype is torch.int8:
if backend == "cutlass":
with self.assertRaisesRegex(RuntimeError, "spgemm_cutlass_dispatch_layouts"):
sparse_result = torch.mm(A_sparse, B)
else:
with self.assertRaisesRegex(RuntimeError,
"CUDA error: operation not supported when calling `cusparseLtMatmulDescriptorInit"):
sparse_result = torch.mm(A_sparse, B)
else:
dense_result = torch.mm(A, B)
sparse_result = torch.mm(A_sparse, B)
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
@inference_dtypes
@parametrize_backends
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128)])
def test_mm_sparse_first_NT(self, dense_input_shape, dtype, device, backend):
"""
Ensure torch.mm(A_sparse, B.t()) is correct for float16/bfloat16
and will throw an error for int8 + padding
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
A = rand_sparse_semi_structured_mask(256, 128, dtype=dtype)
A_sparse = to_sparse_semi_structured(A)
B = torch.rand(dense_input_shape, device=A_sparse.device).to(dtype)
# Currently we don't support int matmul on GPU, so evaluate on CPU and copy over
if dtype is torch.int8 and dense_input_shape in {(1, 128)}:
# padding with int8 throws an error because transposing B yields a contiguous output
# and row-row 2:4 sparse @ dense with NN is not supported by cuSPARSELt or CUTLASS.
if backend == "cutlass":
with self.assertRaisesRegex(RuntimeError, "spgemm_cutlass_dispatch_layouts"):
sparse_result = torch.mm(A_sparse, B.t())
else:
with self.assertRaisesRegex(RuntimeError,
"CUDA error: operation not supported when calling `cusparseLtMatmulDescriptorInit"):
sparse_result = torch.mm(A_sparse, B.t())
elif dtype is torch.int8:
# test transpose
dense_result = torch.mm(A.cpu(), B.t().cpu()).to(device, dtype=torch.int8)
sparse_result = torch.mm(A_sparse, B.t())
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
else:
# test transpose
dense_result = torch.mm(A, B.t())
sparse_result = torch.mm(A_sparse, B.t())
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
@inference_dtypes
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128)])
@parametrize_backends
def test_mm_sparse_first_TN(self, dtype, dense_input_shape, device, backend):
"""
Ensure torch.mm(A_sparse.t(), B) throws error
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = rand_sparse_semi_structured_mask(128, 256, dtype=dtype)
A_sparse = to_sparse_semi_structured(A)
B = torch.rand(dense_input_shape, device=A_sparse.device).to(dtype)
with self.assertRaisesRegex(
NotImplementedError,
r"`SparseSemiStructuredTensor.*` matmul: operation is not supported",
):
torch.mm(A_sparse.t(), B)
@inference_dtypes
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128)])
@parametrize_backends
def test_mm_sparse_second_NT(self, dense_input_shape, dtype, device, backend):
"""
Ensure torch.mm(A, B_sparse.t()) is correct
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
B = rand_sparse_semi_structured_mask(256, 128, dtype=dtype)
B_sparse = to_sparse_semi_structured(B)
A = torch.rand(dense_input_shape, device=B_sparse.device).to(dtype)
# Currently we don't support int matmul on GPU, so evaluate on CPU and copy over
if dtype is torch.int8:
dense_result = torch.mm(A.cpu(), B.t().cpu()).to(device, dtype=torch.int8)
sparse_result = torch.mm(A, B_sparse.t())
else:
dense_result = torch.mm(A, B.t())
sparse_result = torch.mm(A, B_sparse.t())
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
@inference_dtypes
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128)])
@parametrize_backends
def test_mm_sparse_second_NN(self, dense_input_shape, dtype, device, backend):
"""
Ensure torch.mm(A, B_sparse) throws error
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
B = rand_sparse_semi_structured_mask(256, 128, dtype=dtype)
B_sparse = to_sparse_semi_structured(B)
A = torch.rand(dense_input_shape, device=B_sparse.device).to(dtype)
with self.assertRaisesRegex(
NotImplementedError,
r"`SparseSemiStructuredTensor.*` matmul: operation is not supported",
):
sparse_result = torch.mm(A, B_sparse)
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128), (64, 128, 128)])
@parametrize("inference_mode", [subtest(True), subtest(False)])
@parametrize_backends
def test_linear(self, dense_input_shape, inference_mode, device, backend):
"""
Test nn.Linear has the same numerics
"""
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
input = torch.rand((dense_input_shape), device=device).half()
model = nn.Linear(128, 256).to(device).half()
m, n = model.weight.shape
mask = rand_sparse_semi_structured_mask(m, n, device=device, dtype=torch.bool)
# set masked weight
model.weight = nn.Parameter(model.weight * mask)
dense_result = model(input)
model.weight = nn.Parameter(to_sparse_semi_structured(model.weight))
if inference_mode:
with torch.inference_mode():
sparse_result = model(input)
else:
sparse_result = model(input)
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
@parametrize("dense_input_shape", [(1, 128), (64, 128), (128, 128), (64, 128, 128)])
@parametrize_backends
def test_mlp(self, device, dense_input_shape, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
input = torch.rand(dense_input_shape, device=device).half()
model = (
nn.Sequential(
nn.Linear(128, 256),
nn.Linear(256, 128),
)
.half()
.to(device)
)
for i in range(2):
m, n = model[i].weight.shape
mask = rand_sparse_semi_structured_mask(
m, n, device=device, dtype=torch.bool
)
# set masked weight
model[i].weight = nn.Parameter(model[i].weight * mask)
dense_result = model(input)
for i in range(2):
model[i].weight = nn.Parameter(to_sparse_semi_structured(model[i].weight))
sparse_result = model(input)
torch.testing.assert_close(dense_result, sparse_result, rtol=1e-3, atol=1e-3)
@parametrize_backends
def test_values(self, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = rand_sparse_semi_structured_mask(128, 128)
A_sparse = to_sparse_semi_structured(A)
assert A_sparse.values().shape == (128, 64)
assert (A_sparse.values() == 1).all()
@parametrize_backends
def test_indices(self, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = rand_sparse_semi_structured_mask(128, 128)
A_sparse = to_sparse_semi_structured(A)
assert A_sparse.indices().shape == (128, 8)
@inference_dtypes
@parametrize_backends
def test_min_sparse_shape(self, dtype, device, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
config = SEMI_STRUCTURED_SUPPORTED_BACKENDS[backend]._DTYPE_SHAPE_CONSTRAINTS[dtype]
A = rand_sparse_semi_structured_mask(config.sparse_min_rows, config.sparse_min_cols, dtype=dtype, device=device)
A_sparse = to_sparse_semi_structured(A)
B = torch.rand((config.sparse_min_cols, config.dense_min_cols), device=device).to(dtype)
if dtype == torch.int8:
dense_res = torch.mm(A.cpu(), B.cpu()).to(device, dtype=torch.int8)
# int8 sparse matmul not supported for R/R -> R layout, so we transpose one of the arguments to get R/C -> R
B_t = B.t().contiguous()
sparse_res = torch.mm(A_sparse, B_t.t())
else:
dense_res = torch.mm(A, B)
sparse_res = torch.mm(A_sparse, B)
torch.testing.assert_close(sparse_res, dense_res, rtol=1e-3, atol=1e-3)
@inference_dtypes
@parametrize_backends
def test_unsupported_shape(self, dtype, device, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = rand_sparse_semi_structured_mask(2, 2, dtype=dtype, device=device)
with self.assertRaisesRegex(RuntimeError, "Error original_tensor.shape"):
A_sparse = to_sparse_semi_structured(A)
@dtypes(*all_types_and_complex())
@parametrize_backends
def test_unsupported_dtype(self, dtype, device, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = rand_sparse_semi_structured_mask(128, 128, dtype=dtype, device=device)
if dtype not in SEMI_STRUCTURED_SUPPORTED_BACKENDS[backend]._DTYPE_SHAPE_CONSTRAINTS:
with self.assertRaisesRegex(RuntimeError, "Error original_tensor.dtype"):
A_sparse = to_sparse_semi_structured(A)
else:
A_sparse = to_sparse_semi_structured(A)
@parametrize_backends
def test_unsupported_dim(self, device, backend):
SparseSemiStructuredTensor._FORCE_CUTLASS = (backend == "cutlass")
if backend == "cutlass" and IS_WINDOWS:
self.skipTest("CUTLASS not supported on Windows")
A = torch.rand(128, 128, 128, device=device, dtype=torch.float16)
with self.assertRaisesRegex(RuntimeError, "Error original_tensor.dim"):
A_sparse = to_sparse_semi_structured(A)
def create_random_mask(shape) -> torch.Tensor:
r = random.Random(0)
mask = torch.zeros(shape, dtype=torch.bool)
for line in range(mask.shape[0]):
for col in range(0, mask.shape[1], 4):
sparsity = r.choice(
[
[False, False, True, True],
[False, True, False, True],
[True, False, False, True],
[False, True, True, False],
[True, False, True, False],
[True, True, False, False],
]
)
mask[line, col : col + 4] = torch.tensor(sparsity, dtype=torch.bool)
return mask
| TestSparseSemiStructured |
python | python-poetry__poetry | src/poetry/utils/env/python/manager.py | {
"start": 1341,
"end": 11052
} | class ____:
@overload
def __init__(self, *, python: findpython.PythonVersion) -> None: ...
@overload
def __init__(
self, executable: str | Path, version: Version | None = None
) -> None: ...
# we overload __init__ to ensure we do not break any downstream plugins
# that use the this
def __init__(
self,
executable: str | Path | None = None,
version: Version | None = None,
python: findpython.PythonVersion | None = None,
) -> None:
if python and (executable or version):
raise ValueError(
"When python is provided, neither executable or version must be specified"
)
if python:
self._python = python
elif executable:
self._python = findpython.PythonVersion(
executable=Path(executable),
_version=packaging.version.Version(str(version)) if version else None,
)
else:
raise ValueError("Either python or executable must be provided")
@classmethod
def find_all(cls) -> Iterator[Python]:
venv_path: Path | None = (
Path(os.environ["VIRTUAL_ENV"]) if "VIRTUAL_ENV" in os.environ else None
)
for python in findpython.find_all():
if venv_path and python.executable.is_relative_to(venv_path):
continue
yield cls(python=python)
@classmethod
def find_poetry_managed_pythons(cls) -> Iterator[Python]:
finder = findpython.Finder(
selected_providers=[PoetryPythonPathProvider.name()],
)
for python in finder.find_all():
yield cls(python=python)
@classmethod
def find_all_versions(
cls,
constraint: VersionConstraint | str | None = None,
implementation: str | None = None,
free_threaded: bool | None = None,
) -> Iterator[PythonInfo]:
if isinstance(constraint, str):
constraint = parse_constraint(constraint)
constraint = constraint or parse_constraint("*")
if implementation:
implementation = implementation.lower()
seen = set()
for python in cls.find_all():
if (
python.executable in seen
or not constraint.allows(python.version)
or (implementation and python.implementation.lower() != implementation)
or (
free_threaded is not None
and python.free_threaded is not free_threaded
)
):
continue
seen.add(python.executable)
yield PythonInfo(
major=python.major,
minor=python.minor,
patch=python.patch,
implementation=python.implementation.lower(),
free_threaded=python.free_threaded,
executable=python.executable,
)
@classmethod
def find_downloadable_versions(
cls,
constraint: VersionConstraint | str | None = None,
*,
include_incompatible: bool = False,
) -> Iterator[PythonInfo]:
if isinstance(constraint, str):
constraint = parse_constraint(constraint)
constraint = constraint or parse_constraint("*")
for pv in PYTHON_VERSIONS:
for _ in {
k[1]
for k in PYTHON_VERSIONS[pv]
if include_incompatible or (k[0], k[1]) == (THIS_PLATFORM, THIS_ARCH)
}:
if not constraint.allows(
Version.from_parts(pv.major, pv.minor, pv.micro)
):
continue
yield PythonInfo(
major=pv.major,
minor=pv.minor,
patch=pv.micro,
implementation=pv.implementation.lower(),
free_threaded=pv.freethreaded,
executable=None,
)
@property
def python(self) -> findpython.PythonVersion:
return self._python
@property
def name(self) -> str:
return cast("str", self._python.name)
@property
def executable(self) -> Path:
return cast("Path", self._python.interpreter)
@property
def implementation(self) -> str:
return cast("str", self._python.implementation.lower())
@property
def free_threaded(self) -> bool:
return cast("bool", self._python.freethreaded)
@property
def major(self) -> int:
return cast("int", self._python.major)
@property
def minor(self) -> int:
return cast("int", self._python.minor)
@property
def patch(self) -> int:
return cast("int", self._python.patch)
@property
def version(self) -> Version:
return Version.parse(str(self._python.version))
@cached_property
def patch_version(self) -> Version:
return Version.from_parts(
major=self.version.major,
minor=self.version.minor,
patch=self.version.patch,
)
@cached_property
def minor_version(self) -> Version:
return Version.from_parts(major=self.version.major, minor=self.version.minor)
@classmethod
def get_active_python(cls) -> Python | None:
"""
Fetches the active Python interpreter from available system paths or falls
back to finding the first valid Python executable named "python".
An "active Python interpreter" in this context is an executable (or a symlink)
with the name `python`. This is done so to detect cases where pyenv or
alternatives are used.
This method first uses the `ShutilWhichPythonProvider` to detect Python
executables in the path. If no interpreter is found using, it attempts
to locate a Python binary named "python" via the `findpython` library.
:return: An instance representing the detected active Python,
or None if no valid environment is found.
"""
for python in ShutilWhichPythonProvider().find_pythons():
return cls(python=python)
# fallback to findpython, restrict to finding only executables
# named "python" as the intention here is just that, nothing more
if python := findpython.find("python"):
return cls(python=python)
return None
@classmethod
def get_system_python(cls) -> Python:
"""
Creates and returns an instance of the class representing the Poetry's Python executable.
"""
return cls(
python=findpython.PythonVersion(
executable=Path(sys.executable),
_version=packaging.version.Version(
".".join(str(v) for v in sys.version_info[:3])
),
)
)
@classmethod
def get_by_name(cls, python_name: str) -> Python | None:
# Ignore broken installations.
with contextlib.suppress(ValueError):
if python := ShutilWhichPythonProvider.find_python_by_name(python_name):
return cls(python=python)
if python := findpython.find(python_name):
return cls(python=python)
return None
@classmethod
def get_preferred_python(cls, config: Config, io: IO | None = None) -> Python:
"""
Determine and return the "preferred" Python interpreter based on the provided
configuration and optional input/output stream.
This method first attempts to get the active Python interpreter if the configuration
does not mandate using Poetry's Python. If an active interpreter is found, it is returned.
Otherwise, the method defaults to retrieving the Poetry's Python interpreter (System Python).
This method **does not** attempt to sort versions or determine Python version constraint
compatibility.
"""
io = io or NullIO()
if not config.get("virtualenvs.use-poetry-python") and (
active_python := Python.get_active_python()
):
io.write_error_line(
f"Found: {active_python.executable}", verbosity=Verbosity.VERBOSE
)
return active_python
return cls.get_system_python()
@classmethod
def get_compatible_python(cls, poetry: Poetry, io: IO | None = None) -> Python:
"""
Retrieve a compatible Python version based on the given poetry configuration
and Python constraints derived from the project.
This method iterates through all available Python candidates and checks if any
match the supported Python constraint as defined in the specified poetry package.
:param poetry: The poetry configuration containing package information,
including Python constraints.
:param io: The input/output stream for error and status messages. Defaults
to a null I/O if not provided.
:return: A Python instance representing a compatible Python version.
:raises NoCompatiblePythonVersionFoundError: If no Python version matches
the supported constraint.
"""
io = io or NullIO()
supported_python = poetry.package.python_constraint
for python in cls.find_all():
if python.version.allows_any(supported_python):
io.write_error_line(
f"Using <c1>{python.name}</c1> ({python.patch_version})"
)
return python
raise NoCompatiblePythonVersionFoundError(poetry.package.python_versions)
| Python |
python | getsentry__sentry-python | sentry_sdk/scope.py | {
"start": 3183,
"end": 3304
} | class ____(Enum):
CURRENT = "current"
ISOLATION = "isolation"
GLOBAL = "global"
MERGED = "merged"
| ScopeType |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/cfg.py | {
"start": 5495,
"end": 8445
} | class ____(object):
"""Base class for a CFG visitors.
This implementation is not thread safe.
The visitor has some facilities to simplify dataflow analyses. In particular,
it allows revisiting the nodes at the decision of the subclass. This can be
used to visit the graph until the state reaches a fixed point.
For more details on dataflow analysis, see
https://www.seas.harvard.edu/courses/cs252/2011sp/slides/Lec02-Dataflow.pdf
Note: the literature generally suggests visiting successor nodes only when the
state of the current node changed, regardless of whether that successor has
ever been visited. This implementation visits every successor at least once.
Attributes:
graph: Graph
in_: Dict[Node, Any], stores node-keyed state during a visit
out: Dict[Node, Any], stores node-keyed state during a visit
"""
def __init__(self, graph):
self.graph = graph
self.reset()
def init_state(self, node):
"""State initialization function.
Optional to overload.
An in/out state slot will be created for each node in the graph. Subclasses
must overload this to control what that is initialized to.
Args:
node: Node
"""
raise NotImplementedError('Subclasses must implement this.')
# TODO(mdan): Rename to flow?
def visit_node(self, node):
"""Visitor function.
Args:
node: Node
Returns:
bool, whether the node should be revisited; subclasses can visit every
reachable node exactly once by always returning False
"""
raise NotImplementedError('Subclasses must implement this.')
def reset(self):
self.in_ = {
node: self.init_state(node) for node in self.graph.index.values()
}
self.out = {
node: self.init_state(node) for node in self.graph.index.values()
}
def can_ignore(self, node):
"""Returns True if the node can safely be assumed not to touch variables."""
ast_node = node.ast_node
if anno.hasanno(ast_node, anno.Basic.SKIP_PROCESSING):
return True
return isinstance(ast_node,
(gast.Break, gast.Continue, gast.Raise, gast.Pass))
def _visit_internal(self, mode):
"""Visits the CFG, breadth-first."""
assert mode in (_WalkMode.FORWARD, _WalkMode.REVERSE)
if mode == _WalkMode.FORWARD:
open_ = [self.graph.entry]
elif mode == _WalkMode.REVERSE:
open_ = list(self.graph.exit)
closed = set()
while open_:
node = open_.pop(0)
closed.add(node)
should_revisit = self.visit_node(node)
if mode == _WalkMode.FORWARD:
children = node.next
elif mode == _WalkMode.REVERSE:
children = node.prev
for next_ in children:
if should_revisit or next_ not in closed:
open_.append(next_)
def visit_forward(self):
self._visit_internal(_WalkMode.FORWARD)
def visit_reverse(self):
self._visit_internal(_WalkMode.REVERSE)
| GraphVisitor |
python | plotly__plotly.py | plotly/graph_objs/scattergeo/_stream.py | {
"start": 233,
"end": 3526
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergeo"
_path_str = "scattergeo.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set to 50, only the newest
50 points will be displayed on the plot.
The 'maxpoints' property is a number and may be specified as:
- An int or float in the interval [0, 10000]
Returns
-------
int|float
"""
return self["maxpoints"]
@maxpoints.setter
def maxpoints(self, val):
self["maxpoints"] = val
@property
def token(self):
"""
The stream id number links a data trace on a plot with a
stream. See https://chart-studio.plotly.com/settings for more
details.
The 'token' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["token"]
@token.setter
def token(self, val):
self["token"] = val
@property
def _prop_descriptions(self):
return """\
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
"""
def __init__(self, arg=None, maxpoints=None, token=None, **kwargs):
"""
Construct a new Stream object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scattergeo.Stream`
maxpoints
Sets the maximum number of points to keep on the plots
from an incoming stream. If `maxpoints` is set to 50,
only the newest 50 points will be displayed on the
plot.
token
The stream id number links a data trace on a plot with
a stream. See https://chart-studio.plotly.com/settings
for more details.
Returns
-------
Stream
"""
super().__init__("stream")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scattergeo.Stream
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattergeo.Stream`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("maxpoints", arg, maxpoints)
self._set_property("token", arg, token)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Stream |
python | walkccc__LeetCode | solutions/2834. Find the Minimum Possible Sum of a Beautiful Array/2834.py | {
"start": 0,
"end": 793
} | class ____:
# Same as 2829. Determine the Minimum Sum of a k-avoiding Array
def minimumPossibleSum(self, n: int, target: int) -> int:
# These are the unique pairs that sum up to k (target):
# (1, k - 1), (2, k - 2), ..., (ceil(k // 2), floor(k // 2)).
# Our optimal strategy is to select 1, 2, ..., floor(k // 2), and then
# choose k, k + 1, ... if necessary, as selecting any number in the range
# [ceil(k // 2), k - 1] will result in a pair summing up to k.
MOD = 1_000_000_007
def trapezoid(a: int, b: int) -> int:
"""Returns sum(a..b)."""
return (a + b) * (b - a + 1) // 2
mid = target // 2 # floor(k // 2)
if n <= mid:
return trapezoid(1, n)
return (trapezoid(1, mid) + trapezoid(target, target + (n - mid - 1))) % MOD
| Solution |
python | readthedocs__readthedocs.org | readthedocs/core/views/__init__.py | {
"start": 3070,
"end": 4952
} | class ____(TemplateView):
"""
Render templated error pages.
This can be used both for testing and as a generic error view. This supports
multiple subpaths for errors, as we need to show application themed errors
for dashboard users and minimal error pages for documentation readers.
Template resolution also uses fallback to generic 4xx/5xx error templates.
View arguments:
status_code
This can also be a kwarg, like in the case of a testing view for all
errors. Set through ``as_view(status_code=504)``, this view will always
render the same template and status code.
base_path
Base path for templates. Dashboard templates can be loaded from a
separate path from Proxito error templates.
"""
base_path = "errors/dashboard"
status_code = None
template_name = None
def get_status_code(self):
return self.kwargs.get("status_code", self.status_code)
def get_template_name(self):
return self.kwargs.get("template_name", self.template_name)
def get_template_names(self):
template_names = []
if (template_name := self.get_template_name()) is not None:
template_names.append(template_name.rstrip("/"))
if (status_code := self.get_status_code()) is not None:
template_names.append(str(status_code))
return [f"{self.base_path}/{file}.html" for file in template_names]
def get_context_data(self, **kwargs):
context_data = super().get_context_data(**kwargs)
context_data["status_code"] = self.get_status_code()
return context_data
def dispatch(self, request, *args, **kwargs):
context = self.get_context_data()
status_code = self.get_status_code()
return self.render_to_response(
context,
status=status_code,
)
| ErrorView |
python | kamyu104__LeetCode-Solutions | Python/minimum-right-shifts-to-sort-the-array.py | {
"start": 37,
"end": 445
} | class ____(object):
def minimumRightShifts(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = next((i for i in xrange(len(nums)) if not nums[i] < nums[(i+1)%len(nums)]), len(nums))
j = next((j for j in xrange(i+1, len(nums)) if not nums[j%len(nums)] < nums[(j+1)%len(nums)]), len(nums))
return len(nums)-(i+1) if j == len(nums) else -1
| Solution |
python | celery__celery | celery/worker/pidbox.py | {
"start": 2155,
"end": 3630
} | class ____(Pidbox):
"""Worker pidbox (greenlet)."""
_node_shutdown = None
_node_stopped = None
_resets = 0
def start(self, c):
c.pool.spawn_n(self.loop, c)
def on_stop(self):
if self._node_stopped:
self._node_shutdown.set()
debug('Waiting for broadcast thread to shutdown...')
self._node_stopped.wait()
self._node_stopped = self._node_shutdown = None
def reset(self):
self._resets += 1
def _do_reset(self, c, connection):
self._close_channel(c)
self.node.channel = connection.channel()
self.consumer = self.node.listen(callback=self.on_message)
self.consumer.consume()
def loop(self, c):
resets = [self._resets]
shutdown = self._node_shutdown = threading.Event()
stopped = self._node_stopped = threading.Event()
try:
with c.connection_for_read() as connection:
info('pidbox: Connected to %s.', connection.as_uri())
self._do_reset(c, connection)
while not shutdown.is_set() and c.connection:
if resets[0] < self._resets:
resets[0] += 1
self._do_reset(c, connection)
try:
connection.drain_events(timeout=1.0)
except socket.timeout:
pass
finally:
stopped.set()
| gPidbox |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property1.py | {
"start": 1434,
"end": 1626
} | class ____:
@property
def name(self) -> str:
return "bar"
p1: property = ClassA.read_only_prop
p2: property = ClassA.read_write_prop
p3: property = ClassA.deletable_prop
| ClassB |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 9032,
"end": 9294
} | class ____(PydanticValueError):
code = 'frozenset.min_items'
msg_template = 'ensure this value has at least {limit_value} items'
def __init__(self, *, limit_value: int) -> None:
super().__init__(limit_value=limit_value)
| FrozenSetMinLengthError |
python | scipy__scipy | benchmarks/benchmarks/cluster.py | {
"start": 250,
"end": 1017
} | class ____(XPBenchmark):
method = ['single', 'complete', 'average', 'weighted', 'centroid', 'median', 'ward']
param_names = (*XPBenchmark.param_names, "size", "method")
if is_xslow():
size = [100, 180, 325, 585, 1054, 1898, 3420, 6162, 11101, 20000]
else:
size = [2000]
params = (*XPBenchmark.params, size, method)
def setup(self, backend, size, method):
super().setup(backend, linkage, static_argnames="method")
rng = np.random.default_rng(0)
y = self.xp.asarray(rng.standard_normal((size, 2)))
self.y = self.synchronize(y)
if self.warmup:
self.func(self.y, method=method)
def time_linkage(self, backend, size, method):
self.func(self.y, method=method)
| Linkage |
python | huggingface__transformers | src/transformers/models/vilt/modeling_vilt.py | {
"start": 12038,
"end": 13361
} | class ____(nn.Module):
"""
Image to Patch Embedding.
"""
def __init__(self, config):
super().__init__()
image_size, patch_size = config.image_size, config.patch_size
num_channels, hidden_size = config.num_channels, config.hidden_size
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.num_patches = num_patches
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
def forward(self, pixel_values):
batch_size, num_channels, height, width = pixel_values.shape
if num_channels != self.num_channels:
raise ValueError(
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
)
target_dtype = self.projection.weight.dtype
x = self.projection(pixel_values.to(dtype=target_dtype))
return x
| ViltPatchEmbeddings |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/firebase/firenotes/backend/main.py | {
"start": 1050,
"end": 3860
} | class ____(ndb.Model):
"""NDB model class for a user's note.
Key is user id from decrypted token.
"""
friendly_id = ndb.StringProperty()
message = ndb.TextProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
# [START gae_python_query_database]
# This code is for illustration purposes only.
def query_database(user_id):
"""Fetches all notes associated with user_id.
Notes are ordered them by date created, with most recent note added
first.
"""
ancestor_key = ndb.Key(Note, user_id)
query = Note.query(ancestor=ancestor_key).order(-Note.created)
notes = query.fetch()
note_messages = []
for note in notes:
note_messages.append(
{
"friendly_id": note.friendly_id,
"message": note.message,
"created": note.created,
}
)
return note_messages
# [END gae_python_query_database]
@app.route("/notes", methods=["GET"])
def list_notes():
"""Returns a list of notes added by the current Firebase user."""
# Verify Firebase auth.
# [START gae_python_verify_token]
# This code is for illustration purposes only.
id_token = request.headers["Authorization"].split(" ").pop()
claims = google.oauth2.id_token.verify_firebase_token(
id_token, HTTP_REQUEST, audience=os.environ.get("GOOGLE_CLOUD_PROJECT")
)
if not claims:
return "Unauthorized", 401
# [END gae_python_verify_token]
notes = query_database(claims["sub"])
return jsonify(notes)
@app.route("/notes", methods=["POST", "PUT"])
def add_note():
"""
Adds a note to the user's notebook. The request should be in this format:
{
"message": "note message."
}
"""
# Verify Firebase auth.
id_token = request.headers["Authorization"].split(" ").pop()
claims = google.oauth2.id_token.verify_firebase_token(
id_token, HTTP_REQUEST, audience=os.environ.get("GOOGLE_CLOUD_PROJECT")
)
if not claims:
return "Unauthorized", 401
# [START gae_python_create_entity]
# This code is for illustration purposes only.
data = request.get_json()
# Populates note properties according to the model,
# with the user ID as the key name.
note = Note(parent=ndb.Key(Note, claims["sub"]), message=data["message"])
# Some providers do not provide one of these so either can be used.
note.friendly_id = claims.get("name", claims.get("email", "Unknown"))
# [END gae_python_create_entity]
# Stores note in database.
note.put()
return "OK", 200
@app.errorhandler(500)
def server_error(e):
# Log the error and stacktrace.
logging.exception("An error occurred during a request.")
return "An internal error occurred.", 500
| Note |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/exceptions.py | {
"start": 1033,
"end": 1146
} | class ____(AirflowException):
"""Raised when there is an error in sql execution."""
| DatabricksSqlExecutionError |
python | numpy__numpy | numpy/_core/tests/test_umath_complex.py | {
"start": 21059,
"end": 21737
} | class ____:
@pytest.mark.parametrize("arraysize",
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 18, 19])
@pytest.mark.parametrize("stride", [-4, -3, -2, -1, 1, 2, 3, 4])
@pytest.mark.parametrize("astype", [np.complex64, np.complex128])
# test to ensure masking and strides work as intended in the AVX implementation
def test_array(self, arraysize, stride, astype):
arr = np.ones(arraysize, dtype=astype)
abs_true = np.ones(arraysize, dtype=arr.real.dtype)
assert_equal(np.abs(arr[::stride]), abs_true[::stride])
# Testcase taken as is from https://github.com/numpy/numpy/issues/16660
| TestComplexAbsoluteAVX |
python | fastapi__sqlmodel | docs_src/tutorial/where/tutorial001.py | {
"start": 100,
"end": 1172
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.name == "Deadpond")
results = session.exec(statement)
for hero in results:
print(hero)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | matplotlib__matplotlib | lib/matplotlib/collections.py | {
"start": 71729,
"end": 78683
} | class ____(LineCollection):
"""
A collection of locations along a single axis at which an "event" occurred.
The events are given by a 1-dimensional array. They do not have an
amplitude and are displayed as parallel lines.
"""
_edge_default = True
def __init__(self,
positions, # Cannot be None.
orientation='horizontal',
*,
lineoffset=0,
linelength=1,
linewidth=None,
color=None,
linestyle='solid',
antialiased=None,
**kwargs
):
"""
Parameters
----------
positions : 1D array-like
Each value is an event.
orientation : {'horizontal', 'vertical'}, default: 'horizontal'
The sequence of events is plotted along this direction.
The marker lines of the single events are along the orthogonal
direction.
lineoffset : float, default: 0
The offset of the center of the markers from the origin, in the
direction orthogonal to *orientation*.
linelength : float, default: 1
The total height of the marker (i.e. the marker stretches from
``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
linewidth : float or list thereof, default: :rc:`lines.linewidth`
The line width of the event lines, in points.
color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color`
The color of the event lines.
linestyle : str or tuple or list thereof, default: 'solid'
Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
'-', '--', '-.', ':']. Dash tuples should be of the form::
(offset, onoffseq),
where *onoffseq* is an even length tuple of on and off ink
in points.
antialiased : bool or list thereof, default: :rc:`lines.antialiased`
Whether to use antialiasing for drawing the lines.
**kwargs
Forwarded to `.LineCollection`.
Examples
--------
.. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
"""
super().__init__([],
linewidths=linewidth, linestyles=linestyle,
colors=color, antialiaseds=antialiased,
**kwargs)
self._is_horizontal = True # Initial value, may be switched below.
self._linelength = linelength
self._lineoffset = lineoffset
self.set_orientation(orientation)
self.set_positions(positions)
def get_positions(self):
"""
Return an array containing the floating-point values of the positions.
"""
pos = 0 if self.is_horizontal() else 1
return [segment[0, pos] for segment in self.get_segments()]
def set_positions(self, positions):
"""Set the positions of the events."""
if positions is None:
positions = []
if np.ndim(positions) != 1:
raise ValueError('positions must be one-dimensional')
lineoffset = self.get_lineoffset()
linelength = self.get_linelength()
pos_idx = 0 if self.is_horizontal() else 1
segments = np.empty((len(positions), 2, 2))
segments[:, :, pos_idx] = np.sort(positions)[:, None]
segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
self.set_segments(segments)
def add_positions(self, position):
"""Add one or more events at the specified positions."""
if position is None or (hasattr(position, 'len') and
len(position) == 0):
return
positions = self.get_positions()
positions = np.hstack([positions, np.asanyarray(position)])
self.set_positions(positions)
extend_positions = append_positions = add_positions
def is_horizontal(self):
"""True if the eventcollection is horizontal, False if vertical."""
return self._is_horizontal
def get_orientation(self):
"""
Return the orientation of the event line ('horizontal' or 'vertical').
"""
return 'horizontal' if self.is_horizontal() else 'vertical'
def switch_orientation(self):
"""
Switch the orientation of the event line, either from vertical to
horizontal or vice versus.
"""
segments = self.get_segments()
for i, segment in enumerate(segments):
segments[i] = np.fliplr(segment)
self.set_segments(segments)
self._is_horizontal = not self.is_horizontal()
self.stale = True
def set_orientation(self, orientation):
"""
Set the orientation of the event line.
Parameters
----------
orientation : {'horizontal', 'vertical'}
"""
is_horizontal = _api.check_getitem(
{"horizontal": True, "vertical": False},
orientation=orientation)
if is_horizontal == self.is_horizontal():
return
self.switch_orientation()
def get_linelength(self):
"""Return the length of the lines used to mark each event."""
return self._linelength
def set_linelength(self, linelength):
"""Set the length of the lines used to mark each event."""
if linelength == self.get_linelength():
return
lineoffset = self.get_lineoffset()
segments = self.get_segments()
pos = 1 if self.is_horizontal() else 0
for segment in segments:
segment[0, pos] = lineoffset + linelength / 2.
segment[1, pos] = lineoffset - linelength / 2.
self.set_segments(segments)
self._linelength = linelength
def get_lineoffset(self):
"""Return the offset of the lines used to mark each event."""
return self._lineoffset
def set_lineoffset(self, lineoffset):
"""Set the offset of the lines used to mark each event."""
if lineoffset == self.get_lineoffset():
return
linelength = self.get_linelength()
segments = self.get_segments()
pos = 1 if self.is_horizontal() else 0
for segment in segments:
segment[0, pos] = lineoffset + linelength / 2.
segment[1, pos] = lineoffset - linelength / 2.
self.set_segments(segments)
self._lineoffset = lineoffset
def get_linewidth(self):
"""Get the width of the lines used to mark each event."""
return super().get_linewidth()[0]
def get_linewidths(self):
return super().get_linewidth()
def get_color(self):
"""Return the color of the lines used to mark each event."""
return self.get_colors()[0]
| EventCollection |
python | redis__redis-py | tests/test_pubsub.py | {
"start": 41808,
"end": 43328
} | class ____:
def test_base_exception(self, r: redis.Redis):
"""
Manually trigger a BaseException inside the parser's .read_response method
and verify that it isn't caught
"""
pubsub = r.pubsub()
pubsub.subscribe("foo")
def is_connected():
return pubsub.connection._sock is not None
assert is_connected()
def get_msg():
# blocking method to return messages
while True:
response = pubsub.parse_response(block=True)
message = pubsub.handle_message(
response, ignore_subscribe_messages=False
)
if message is not None:
return message
# get subscribe message
msg = get_msg()
assert msg is not None
# timeout waiting for another message which never arrives
assert is_connected()
with (
patch("redis._parsers._RESP2Parser.read_response") as mock1,
patch("redis._parsers._HiredisParser.read_response") as mock2,
patch("redis._parsers._RESP3Parser.read_response") as mock3,
):
mock1.side_effect = BaseException("boom")
mock2.side_effect = BaseException("boom")
mock3.side_effect = BaseException("boom")
with pytest.raises(BaseException):
get_msg()
# the timeout on the read should not cause disconnect
assert is_connected()
| TestBaseException |
python | sympy__sympy | sympy/matrices/expressions/factorizations.py | {
"start": 233,
"end": 338
} | class ____(Factorization):
@property
def predicates(self):
return (Q.lower_triangular,)
| LofLU |
python | spyder-ide__spyder | spyder/plugins/completion/tests/test_plugin.py | {
"start": 751,
"end": 7931
} | class ____(SpyderCompletionProvider):
COMPLETION_PROVIDER_NAME = 'fake'
CONF_DEFAULTS = [
('key1', 'value1'),
('key2', 'value2'),
('key3', 'value3'),
('key4', 4)
]
CONF_VERSION = "0.1.0"
@pytest.fixture
def completion_receiver(completion_plugin_all_started):
completion_plugin, _ = completion_plugin_all_started
receiver = DummyCompletionReceiver(None)
return completion_plugin, receiver
def test_configuration_merge(completion_plugin_all):
first_defaults = dict(FakeProvider.CONF_DEFAULTS)
first_version = FakeProvider.CONF_VERSION
# Check that a new completion provider configuration is registered without
# changes
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, {}
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == first_defaults
assert conf_defaults == first_defaults
# Add a new value to the initial default configuration without changing the
# version
second_config = first_defaults.copy()
second_config['extra_value'] = ['value']
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in second_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': first_defaults,
'defaults': first_defaults
}
}
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == second_config
assert conf_defaults == second_config
# Assert that default values cannot be changed without a bump in the minor
# version
config = first_defaults.copy()
config['key4'] = 5
third_config = first_defaults.copy()
third_config['key4'] = -1
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in third_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': config,
'defaults': first_defaults
}
}
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == config
assert conf_defaults == first_defaults
# Assert that default values can be replaced with new ones when the
# minor version number is bumped.
config['key1'] = 'othervalue'
expected_config = config.copy()
expected_config['key4'] = -1
FakeProvider.CONF_VERSION = "0.1.1"
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Ensure that default values cannot be removed if the major version is not
# bumped
fourth_config = third_config.copy()
fourth_config.pop('key2')
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in fourth_config.items()]
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Remove an option when the major version is bumped.
FakeProvider.CONF_VERSION = "1.0.0"
expected_config.pop('key2')
result = completion_plugin_all._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "1.0.0"
assert conf_values == expected_config
assert conf_defaults == fourth_config
def test_provider_detection(completion_plugin_all):
print(completion_plugin_all.providers)
assert len(completion_plugin_all.providers) == 3
@pytest.mark.order(1)
def test_plugin_completion_gather(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test.py',
'language': 'python',
'version': 1,
'text': "# This is some text with some classe\nimport os\n\ncla",
'response_instance': receiver,
'offset': 1,
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
# Parameters to perform a textDocument/completion request
params = {
'file': 'test.py',
'line': 2,
'column': 3,
'offset': 50,
'selection_start': 0,
'selection_end': 0,
'current_word': 'cla',
'codeeditor': receiver,
'response_instance': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_COMPLETION, params)
_, response = blocker.args
response = response['params']
provider_set = {x['provider'] for x in response}
# Assert the response contains information from all the providers
provider_set == {'LSP', 'Fallback', 'Snippets'}
@pytest.mark.order(1)
def test_plugin_first_response_request(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test2.py',
'language': 'python',
'version': 2,
'text': "# This is some text with some classe\nimport os\n\n",
'response_instance': receiver,
'offset': 1,
'diff': '',
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
params = {
'file': 'test2.py',
'line': 1,
'column': 8,
'offset': 43,
'diff': '',
'response_instance': receiver,
'codeeditor': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_HOVER, params)
_, response = blocker.args
assert len(response['params']) > 0
| FakeProvider |
python | wandb__wandb | wandb/vendor/pygments/lexers/objective.py | {
"start": 8561,
"end": 8900
} | class ____(objective(CppLexer)):
"""
For Objective-C++ source code with preprocessor directives.
"""
name = 'Objective-C++'
aliases = ['objective-c++', 'objectivec++', 'obj-c++', 'objc++']
filenames = ['*.mm', '*.hh']
mimetypes = ['text/x-objective-c++']
priority = 0.05 # Lower than C++
| ObjectiveCppLexer |
python | scikit-learn__scikit-learn | sklearn/cluster/_dbscan.py | {
"start": 7927,
"end": 20552
} | class ____(ClusterMixin, BaseEstimator):
"""Perform DBSCAN clustering from vector array or distance matrix.
DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
Finds core samples of high density and expands clusters from them.
This algorithm is particularly good for data which contains clusters of
similar density and can find clusters of arbitrary shape.
Unlike K-means, DBSCAN does not require specifying the number of clusters
in advance and can identify outliers as noise points.
This implementation has a worst case memory complexity of :math:`O({n}^2)`,
which can occur when the `eps` param is large and `min_samples` is low,
while the original DBSCAN only uses linear memory.
For further details, see the Notes below.
Read more in the :ref:`User Guide <dbscan>`.
Parameters
----------
eps : float, default=0.5
The maximum distance between two samples for one to be considered
as in the neighborhood of the other. This is not a maximum bound
on the distances of points within a cluster. This is the most
important DBSCAN parameter to choose appropriately for your data set
and distance function. Smaller values generally lead to more clusters.
min_samples : int, default=5
The number of samples (or total weight) in a neighborhood for a point to
be considered as a core point. This includes the point itself. If
`min_samples` is set to a higher value, DBSCAN will find denser clusters,
whereas if it is set to a lower value, the found clusters will be more
sparse.
metric : str, or callable, default='euclidean'
The metric to use when calculating distance between instances in a
feature array. If metric is a string or callable, it must be one of
the options allowed by :func:`sklearn.metrics.pairwise_distances` for
its metric parameter.
If metric is "precomputed", X is assumed to be a distance matrix and
must be square. X may be a :term:`sparse graph`, in which
case only "nonzero" elements may be considered neighbors for DBSCAN.
.. versionadded:: 0.17
metric *precomputed* to accept precomputed sparse matrix.
metric_params : dict, default=None
Additional keyword arguments for the metric function.
.. versionadded:: 0.19
algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
The algorithm to be used by the NearestNeighbors module
to compute pointwise distances and find nearest neighbors.
'auto' will attempt to decide the most appropriate algorithm
based on the values passed to :meth:`fit` method.
See :class:`~sklearn.neighbors.NearestNeighbors` documentation for
details.
leaf_size : int, default=30
Leaf size passed to BallTree or cKDTree. This can affect the speed
of the construction and query, as well as the memory required
to store the tree. The optimal value depends
on the nature of the problem.
p : float, default=None
The power of the Minkowski metric to be used to calculate distance
between points. If None, then ``p=2`` (equivalent to the Euclidean
distance). When p=1, this is equivalent to Manhattan distance.
n_jobs : int, default=None
The number of parallel jobs to run.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Attributes
----------
core_sample_indices_ : ndarray of shape (n_core_samples,)
Indices of core samples.
components_ : ndarray of shape (n_core_samples, n_features)
Copy of each core sample found by training.
labels_ : ndarray of shape (n_samples,)
Cluster labels for each point in the dataset given to fit().
Noisy samples are given the label -1. Non-negative integers
indicate cluster membership.
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
OPTICS : A similar clustering at multiple values of eps. Our implementation
is optimized for memory usage.
Notes
-----
This implementation bulk-computes all neighborhood queries, which increases
the memory complexity to O(n.d) where d is the average number of neighbors,
while original DBSCAN had memory complexity O(n). It may attract a higher
memory complexity when querying these nearest neighborhoods, depending
on the ``algorithm``.
One way to avoid the query complexity is to pre-compute sparse
neighborhoods in chunks using
:func:`NearestNeighbors.radius_neighbors_graph
<sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
``mode='distance'``, then using ``metric='precomputed'`` here.
Another way to reduce memory and computation time is to remove
(near-)duplicate points and use ``sample_weight`` instead.
:class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower memory
usage.
References
----------
Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based
Algorithm for Discovering Clusters in Large Spatial Databases with Noise"
<https://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf>`_.
In: Proceedings of the 2nd International Conference on Knowledge Discovery
and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996
Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
:doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN."
<10.1145/3068335>`
ACM Transactions on Database Systems (TODS), 42(3), 19.
Examples
--------
>>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
... [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0, 0, 0, 1, 1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)
For an example, see
:ref:`sphx_glr_auto_examples_cluster_plot_dbscan.py`.
For a comparison of DBSCAN with other clustering algorithms, see
:ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py`
"""
_parameter_constraints: dict = {
"eps": [Interval(Real, 0.0, None, closed="neither")],
"min_samples": [Interval(Integral, 1, None, closed="left")],
"metric": [
StrOptions(set(_VALID_METRICS) | {"precomputed"}),
callable,
],
"metric_params": [dict, None],
"algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})],
"leaf_size": [Interval(Integral, 1, None, closed="left")],
"p": [Interval(Real, 0.0, None, closed="left"), None],
"n_jobs": [Integral, None],
}
def __init__(
self,
eps=0.5,
*,
min_samples=5,
metric="euclidean",
metric_params=None,
algorithm="auto",
leaf_size=30,
p=None,
n_jobs=None,
):
self.eps = eps
self.min_samples = min_samples
self.metric = metric
self.metric_params = metric_params
self.algorithm = algorithm
self.leaf_size = leaf_size
self.p = p
self.n_jobs = n_jobs
@_fit_context(
# DBSCAN.metric is not validated yet
prefer_skip_nested_validation=False
)
def fit(self, X, y=None, sample_weight=None):
"""Perform DBSCAN clustering from features, or distance matrix.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
(n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``. If a sparse matrix is provided, it will
be converted into a sparse ``csr_matrix``.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least
``min_samples`` is by itself a core sample; a sample with a
negative weight may inhibit its eps-neighbor from being core.
Note that weights are absolute, and default to 1.
Returns
-------
self : object
Returns a fitted instance of self.
"""
X = validate_data(self, X, accept_sparse="csr")
if sample_weight is not None:
sample_weight = _check_sample_weight(sample_weight, X)
# Calculate neighborhood for all samples. This leaves the original
# point in, which needs to be considered later (i.e. point i is in the
# neighborhood of point i. While True, its useless information)
if self.metric == "precomputed" and sparse.issparse(X):
# set the diagonal to explicit values, as a point is its own
# neighbor
X = X.copy() # copy to avoid in-place modification
with warnings.catch_warnings():
warnings.simplefilter("ignore", sparse.SparseEfficiencyWarning)
X.setdiag(X.diagonal())
neighbors_model = NearestNeighbors(
radius=self.eps,
algorithm=self.algorithm,
leaf_size=self.leaf_size,
metric=self.metric,
metric_params=self.metric_params,
p=self.p,
n_jobs=self.n_jobs,
)
neighbors_model.fit(X)
# This has worst case O(n^2) memory complexity
neighborhoods = neighbors_model.radius_neighbors(X, return_distance=False)
if sample_weight is None:
n_neighbors = np.array([len(neighbors) for neighbors in neighborhoods])
else:
n_neighbors = np.array(
[np.sum(sample_weight[neighbors]) for neighbors in neighborhoods]
)
# Initially, all samples are noise.
labels = np.full(X.shape[0], -1, dtype=np.intp)
# A list of all core samples found.
core_samples = np.asarray(n_neighbors >= self.min_samples, dtype=np.uint8)
dbscan_inner(core_samples, neighborhoods, labels)
self.core_sample_indices_ = np.where(core_samples)[0]
self.labels_ = labels
if len(self.core_sample_indices_):
# fix for scipy sparse indexing issue
self.components_ = X[self.core_sample_indices_].copy()
else:
# no core samples
self.components_ = np.empty((0, X.shape[1]))
return self
def fit_predict(self, X, y=None, sample_weight=None):
"""Compute clusters from a data or distance matrix and predict labels.
This method fits the model and returns the cluster labels in a single step.
It is equivalent to calling fit(X).labels_.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or \
(n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``. If a sparse matrix is provided, it will
be converted into a sparse ``csr_matrix``.
y : Ignored
Not used, present here for API consistency by convention.
sample_weight : array-like of shape (n_samples,), default=None
Weight of each sample, such that a sample with a weight of at least
``min_samples`` is by itself a core sample; a sample with a
negative weight may inhibit its eps-neighbor from being core.
Note that weights are absolute, and default to 1.
Returns
-------
labels : ndarray of shape (n_samples,)
Cluster labels. Noisy samples are given the label -1.
Non-negative integers indicate cluster membership.
"""
self.fit(X, sample_weight=sample_weight)
return self.labels_
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.pairwise = self.metric == "precomputed"
tags.input_tags.sparse = True
return tags
| DBSCAN |
python | PyCQA__pylint | tests/functional/n/non/non_iterator_returned.py | {
"start": 1253,
"end": 1654
} | class ____:
def __init__(self, path):
self.path = path
self.file = None
def __iter__(self):
if self.file is not None:
self.file.close()
self.file = open(self.path, encoding="utf-8")
# self file has two inferred values: None and <instance of 'file'>
# we don't want to emit error in this case
return self.file
| FileBasedIterator |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 54952,
"end": 55066
} | class ____(Structure):
pass # opaque handle
c_nvmlDevice_t = POINTER(struct_c_nvmlDevice_t)
| struct_c_nvmlDevice_t |
python | kamyu104__LeetCode-Solutions | Python/make-array-elements-equal-to-zero.py | {
"start": 129,
"end": 621
} | class ____(object):
def countValidSelections(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
result = curr = 0
for x in nums:
if not x:
result += max(2-abs(curr-(total-curr)), 0)
else:
curr += x
return result
# Time: O(n)
# Space: O(n)
# prefix sum, CodeChef Starters 146 - Bouncing Ball (https://www.codechef.com/problems/BOUNCE_BALL)
| Solution |
python | astropy__astropy | astropy/io/ascii/sextractor.py | {
"start": 4534,
"end": 4634
} | class ____(core.BaseData):
start_line = 0
delimiter = " "
comment = r"\s*#"
| SExtractorData |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 11572,
"end": 11778
} | class ____(ObjectActivityMixin, JSONActivityFeed):
"""
JSON feed of Activity for a given object (where actions involve the given object as any of the entities).
"""
pass
| ObjectJSONActivityFeed |
python | spyder-ide__spyder | spyder/widgets/onecolumntree.py | {
"start": 514,
"end": 781
} | class ____:
CollapseAllAction = "collapse_all_action"
ExpandAllAction = "expand_all_action"
RestoreAction = "restore_action"
CollapseSelectionAction = "collapse_selection_action"
ExpandSelectionAction = "expand_selection_action"
| OneColumnTreeActions |
python | apache__airflow | providers/common/sql/src/airflow/providers/common/sql/operators/sql.py | {
"start": 50067,
"end": 55745
} | class ____(BaseSQLOperator):
"""
Insert rows (e.g. a collection of tuples) into a database table directly from an XCom or Python data structure.
:param table: the name of the table in which the rows will be inserted (templated).
:param conn_id: the connection ID used to connect to the database
:param schema: (optional) the name of schema in which the table is defined
:param database: name of database (e.g. schema) which overwrite the defined one in connection
:param columns: (optional) specify a list of columns being used for the insert when passing a list of
dictionaries.
:param ignore_columns: (optional) specify a list of columns being ignored for the insert. If no columns
where specified, the columns will be resolved dynamically from the metadata.
:param rows: the rows to insert into the table. Rows can be a list of tuples or a list of dictionaries.
When a list of dictionaries is provided, the column names are inferred from the dictionary keys and
will be matched with the column names, ignored columns will be filtered out.
:rows_processor: (optional) a function that will be applied to the rows before inserting them into the table.
:param preoperator: sql statement or list of statements to be executed prior to loading the data. (templated)
:param postoperator: sql statement or list of statements to be executed after loading the data. (templated)
:param insert_args: (optional) dictionary of additional arguments passed to the underlying hook's
`insert_rows` method. This allows you to configure options such as `replace`, `executemany`,
`fast_executemany`, and `autocommit`.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SQLInsertRowsOperator`
"""
template_fields: Sequence[str] = (
"table_name",
"conn_id",
"schema",
"database",
"_columns",
"ignored_columns",
"preoperator",
"postoperator",
"insert_args",
)
template_ext: Sequence[str] = (".sql",)
template_fields_renderers = {"preoperator": "sql"}
def __init__(
self,
*,
table_name: str,
conn_id: str | None = None,
schema: str | None = None,
database: str | None = None,
columns: Iterable[str] | None = None,
ignored_columns: Iterable[str] | None = None,
rows: list[Any] | XComArg | None = None,
rows_processor: Callable[[Any, Context], Any] = lambda rows, **context: rows,
preoperator: str | list[str] | None = None,
postoperator: str | list[str] | None = None,
hook_params: dict | None = None,
insert_args: dict | None = None,
**kwargs,
):
super().__init__(
conn_id=conn_id,
database=database,
hook_params=hook_params,
**kwargs,
)
self.table_name = table_name
self.schema = schema
self._columns: list | None = list(columns) if columns else None
self.ignored_columns = set(ignored_columns or {})
self.rows = rows or []
self._rows_processor = rows_processor
self.preoperator = preoperator
self.postoperator = postoperator
self.insert_args = insert_args or {}
self.do_xcom_push = False
def render_template_fields(
self,
context: Context,
jinja_env: jinja2.Environment | None = None,
) -> None:
super().render_template_fields(context=context, jinja_env=jinja_env)
if isinstance(self.rows, XComArg):
self.rows = self.rows.resolve(context=context)
@property
def table_name_with_schema(self) -> str:
if self.schema is not None:
return f"{self.schema}.{self.table_name}"
return self.table_name
@cached_property
def columns(self):
if self._columns is None:
self._columns = self.get_db_hook().dialect.get_column_names(self.table_name_with_schema)
return self._columns
@property
def column_names(self) -> list[str]:
if self.ignored_columns:
return [column for column in self.columns if column not in self.ignored_columns]
return self.columns
def _process_rows(self, context: Context):
return self._rows_processor(self.rows, **context) # type: ignore
def execute(self, context: Context) -> Any:
if not self.rows:
raise AirflowSkipException(f"Skipping task {self.task_id} because no rows.")
self.log.debug("Table: %s", self.table_name_with_schema)
self.log.debug("Column names: %s", self.column_names)
if self.preoperator:
self.log.debug("Running preoperator")
self.log.debug(self.preoperator)
self.get_db_hook().run(self.preoperator)
rows = self._process_rows(context=context)
self.get_db_hook().insert_rows(
table=self.table_name_with_schema,
rows=rows,
target_fields=self.column_names,
**self.insert_args,
)
if self.postoperator:
self.log.debug("Running postoperator")
self.log.debug(self.postoperator)
self.get_db_hook().run(self.postoperator)
def _initialize_partition_clause(clause: str | None) -> str | None:
"""Ensure the partition_clause contains only valid patterns."""
if clause is None:
return None
if ";" in clause:
raise ValueError("Invalid partition_clause: semicolons (;) not allowed.")
return clause
| SQLInsertRowsOperator |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 1282,
"end": 1325
} | class ____(Image):
tag: str
| ExternalImage |
python | getsentry__sentry | tests/sentry/uptime/endpoints/__init__.py | {
"start": 49,
"end": 188
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
| UptimeAlertBaseEndpointTest |
python | doocs__leetcode | solution/2000-2099/2008.Maximum Earnings From Taxi/Solution.py | {
"start": 0,
"end": 397
} | class ____:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(rides):
return 0
st, ed, tip = rides[i]
j = bisect_left(rides, ed, lo=i + 1, key=lambda x: x[0])
return max(dfs(i + 1), dfs(j) + ed - st + tip)
rides.sort()
return dfs(0)
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/source_google_ads/source.py | {
"start": 538,
"end": 1425
} | class ____(YamlDeclarativeSource):
def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: TState, **kwargs):
super().__init__(catalog=catalog, config=config, state=state, **{"path_to_yaml": "manifest.yaml"})
# Raise exceptions on missing streams
raise_exception_on_missing_stream = True
@staticmethod
def _validate_and_transform(config: Mapping[str, Any]):
if config.get("end_date") == "":
config.pop("end_date")
if "customer_id" in config:
config["customer_ids"] = config["customer_id"].split(",")
config.pop("customer_id")
return config
def streams(self, config: Mapping[str, Any]) -> List[Stream]:
config = self._validate_and_transform(config)
streams = super().streams(config=config)
return streams
| SourceGoogleAds |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/GraphicsItem.py | {
"start": 509,
"end": 1096
} | class ____(OrderedDict):
'Limit size, evicting the least recently looked-up key when full'
def __init__(self, maxsize=128, *args, **kwds):
self.maxsize = maxsize
super().__init__(*args, **kwds)
def __getitem__(self, key):
value = super().__getitem__(key)
self.move_to_end(key)
return value
def __setitem__(self, key, value):
if key in self:
self.move_to_end(key)
super().__setitem__(key, value)
if len(self) > self.maxsize:
oldest = next(iter(self))
del self[oldest]
| LRU |
python | has2k1__plotnine | plotnine/themes/theme_gray.py | {
"start": 224,
"end": 5226
} | class ____(theme):
"""
A gray background with white gridlines.
This is the default theme
Parameters
----------
base_size : int
Base font size. All text sizes are a scaled versions of
the base font size.
base_family : str
Base font family. If `None`, use [](`plotnine.options.base_family`).
"""
def __init__(self, base_size=11, base_family=None):
base_family = base_family or get_option("base_family")
half_line = base_size / 2
quarter_line = base_size / 4
fifth_line = base_size / 5
eighth_line = base_size / 8
m = get_option("base_margin")
super().__init__(
line=element_line(
color="black", size=1, linetype="solid", lineend="butt"
),
rect=element_rect(
fill="white", color="black", size=1, linetype="solid"
),
text=element_text(
family=base_family,
style="normal",
color="black",
ma="center",
size=base_size,
linespacing=0.9,
rotation=0,
margin=margin(),
),
aspect_ratio=get_option("aspect_ratio"),
axis_line=element_line(),
axis_line_x=element_blank(),
axis_line_y=element_blank(),
axis_text=element_text(size=base_size * 0.8, color="#4D4D4D"),
axis_text_x=element_text(va="top", margin=margin(t=fifth_line)),
axis_text_y=element_text(ha="right", margin=margin(r=fifth_line)),
axis_ticks=element_line(color="#333333"),
axis_ticks_length=0,
axis_ticks_length_major=quarter_line,
axis_ticks_length_minor=eighth_line,
axis_ticks_minor=element_blank(),
axis_title_x=element_text(
va="bottom", ha="center", margin=margin(t=m, unit="fig")
),
axis_title_y=element_text(
angle=90,
va="center",
ha="left",
margin=margin(r=m, unit="fig"),
),
dpi=get_option("dpi"),
figure_size=get_option("figure_size"),
# legend, None values are for parameters where the
# drawing routines can make better decisions than
# can be pre-determined in the theme.
legend_background=element_rect(color="none"),
legend_box_margin=0, # points
legend_box_spacing=m * 3, # figure units
legend_frame=element_blank(),
legend_key_spacing_x=6,
legend_key_spacing_y=2,
legend_key_size=base_size * 0.8 * 1.8,
legend_ticks_length=0.2,
legend_margin=0, # points
legend_position="right",
legend_spacing=10, # points
legend_text=element_text(
size=base_size * 0.8,
margin=margin_auto(m / 1.5, unit="fig"),
),
legend_ticks=element_line(color="#CCCCCC", size=1),
legend_title=element_text(
margin=margin(t=m, l=m * 2, b=m / 2, r=m * 2, unit="fig")
),
panel_background=element_rect(fill="#EBEBEB", color="none"),
panel_border=element_blank(),
panel_grid_major=element_line(color="white", size=1),
panel_grid_minor=element_line(color="white", size=0.5),
panel_spacing=m,
plot_background=element_rect(color="white"),
plot_caption=element_text(
size=base_size * 0.8,
ha="right",
va="bottom",
ma="left",
margin=margin(t=m, unit="fig"),
),
plot_margin=m,
plot_subtitle=element_text(
va="top",
ma="left",
margin=margin(b=m, unit="fig"),
),
plot_title=element_text(
size=base_size * 1.2,
va="top",
ma="left",
margin=margin(b=m, unit="fig"),
),
plot_tag=element_text(
size=base_size * 1.2,
va="center",
ha="center",
),
plot_title_position="panel",
plot_caption_position="panel",
plot_tag_location="margin",
plot_tag_position="topleft",
strip_align=0,
strip_background=element_rect(color="none", fill="#D9D9D9"),
strip_background_x=element_rect(width=1),
strip_background_y=element_rect(height=1),
strip_text=element_text(
color="#1A1A1A",
size=base_size * 0.8,
linespacing=1.5,
margin=margin_auto(half_line * 0.8),
),
strip_text_y=element_text(rotation=-90),
complete=True,
)
@alias
| theme_gray |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/param.py | {
"start": 1420,
"end": 5370
} | class ____:
"""
Class to hold the default value of a Param and rule set to do the validations.
Without the rule set it always validates and returns the default value.
:param default: The value this Param object holds
:param description: Optional help text for the Param
:param schema: The validation schema of the Param, if not given then all kwargs except
default & description will form the schema
"""
__version__: ClassVar[int] = 1
CLASS_IDENTIFIER = "__class"
def __init__(
self,
default: Any = NOTSET,
description: str | None = None,
source: Literal["dag", "task"] | None = None,
**kwargs,
):
if default is not NOTSET:
self._check_json(default)
self.value = default
self.description = description
self.schema = kwargs.pop("schema") if "schema" in kwargs else kwargs
self.source = source
def __copy__(self) -> Param:
return Param(
self.value,
self.description,
schema=self.schema,
source=self.source,
)
@staticmethod
def _check_json(value):
try:
json.dumps(value)
except Exception:
raise ParamValidationError(
f"All provided parameters must be json-serializable. The value '{value}' is not serializable."
)
def resolve(self, value: Any = NOTSET, suppress_exception: bool = False) -> Any:
"""
Run the validations and returns the Param's final value.
May raise ValueError on failed validations, or TypeError
if no value is passed and no value already exists.
We first check that value is json-serializable; if not, warn.
In future release we will require the value to be json-serializable.
:param value: The value to be updated for the Param
:param suppress_exception: To raise an exception or not when the validations fails.
If true and validations fails, the return value would be None.
"""
import jsonschema
from jsonschema import FormatChecker
from jsonschema.exceptions import ValidationError
if value is not NOTSET:
self._check_json(value)
final_val = self.value if value is NOTSET else value
if not is_arg_set(final_val):
if suppress_exception:
return None
raise ParamValidationError("No value passed and Param has no default value")
try:
jsonschema.validate(final_val, self.schema, format_checker=FormatChecker())
except ValidationError as err:
if suppress_exception:
return None
raise ParamValidationError(err) from None
self.value = final_val
return final_val
def dump(self) -> dict:
"""Dump the Param as a dictionary."""
out_dict: dict[str, str | None] = {
self.CLASS_IDENTIFIER: f"{self.__module__}.{self.__class__.__name__}"
}
out_dict.update(self.__dict__)
# Ensure that not set is translated to None
if self.value is NOTSET:
out_dict["value"] = None
return out_dict
@property
def has_value(self) -> bool:
return self.value is not NOTSET and self.value is not None
def serialize(self) -> dict:
return {
"value": self.value,
"description": self.description,
"schema": self.schema,
"source": self.source,
}
@staticmethod
def deserialize(data: dict[str, Any], version: int) -> Param:
if version > Param.__version__:
raise TypeError("serialized version > class version")
return Param(
default=data["value"],
description=data["description"],
schema=data["schema"],
source=data.get("source", None),
)
| Param |
python | facebook__pyre-check | client/command_arguments.py | {
"start": 1636,
"end": 1737
} | class ____(str, enum.Enum):
_value_: str
OBSCURE = "obscure"
TYPE = "type"
| MissingFlowsKind |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/components.py | {
"start": 204,
"end": 1044
} | class ____(RecordExtractor):
def extract_records(self, response: requests.Response) -> List[Mapping[str, Any]]:
try:
records = response.json().get("ticket_events") or []
except requests.exceptions.JSONDecodeError:
records = []
events = []
for record in records:
for event in record.get("child_events", []):
if event.get("event_type") == "Comment":
for prop in ["via_reference_id", "ticket_id", "timestamp"]:
event[prop] = record.get(prop)
# https://github.com/airbytehq/oncall/issues/1001
if not isinstance(event.get("via"), dict):
event["via"] = None
events.append(event)
return events
| ZendeskSupportExtractorEvents |
python | nedbat__coveragepy | coverage/types.py | {
"start": 3615,
"end": 4557
} | class ____(Protocol):
"""Something that can proxy to the coverage configuration settings."""
def get_option(self, option_name: str) -> TConfigValueOut | None:
"""Get an option from the configuration.
`option_name` is a colon-separated string indicating the section and
option name. For example, the ``branch`` option in the ``[run]``
section of the config file would be indicated with `"run:branch"`.
Returns the value of the option.
"""
def set_option(self, option_name: str, value: TConfigValueIn | TConfigSectionIn) -> None:
"""Set an option in the configuration.
`option_name` is a colon-separated string indicating the section and
option name. For example, the ``branch`` option in the ``[run]``
section of the config file would be indicated with `"run:branch"`.
`value` is the new value for the option.
"""
| TConfigurable |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 6707,
"end": 7144
} | class ____(_TestDCTBase):
def test_definition_ortho(self):
# Test orthornomal mode.
dt = np.result_type(np.float32, self.rdt)
for xr in X:
x = np.array(xr, dtype=self.rdt)
y = dct(x, norm='ortho', type=1)
y2 = naive_dct1(x, norm='ortho')
assert_equal(y.dtype, dt)
assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
| _TestDCTIBase |
python | pennersr__django-allauth | allauth/mfa/models.py | {
"start": 550,
"end": 2126
} | class ____(models.Model):
class Type(models.TextChoices):
RECOVERY_CODES = "recovery_codes", _("Recovery codes")
TOTP = "totp", _("TOTP Authenticator")
WEBAUTHN = "webauthn", _("WebAuthn")
objects = AuthenticatorManager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.CharField(max_length=20, choices=Type.choices)
data = models.JSONField()
created_at = models.DateTimeField(default=timezone.now)
last_used_at = models.DateTimeField(null=True)
class Meta:
constraints = [
UniqueConstraint(
fields=["user", "type"],
name="unique_authenticator_type",
condition=Q(
type__in=(
"totp",
"recovery_codes",
)
),
)
]
def __str__(self):
if self.type == self.Type.WEBAUTHN:
return self.wrap().name
return self.get_type_display()
def wrap(self):
from allauth.mfa.recovery_codes.internal.auth import RecoveryCodes
from allauth.mfa.totp.internal.auth import TOTP
from allauth.mfa.webauthn.internal.auth import WebAuthn
return {
self.Type.TOTP: TOTP,
self.Type.RECOVERY_CODES: RecoveryCodes,
self.Type.WEBAUTHN: WebAuthn,
}[self.type](self)
def record_usage(self) -> None:
self.last_used_at = timezone.now()
self.save(update_fields=["last_used_at"])
| Authenticator |
python | numpy__numpy | numpy/_core/tests/test_simd_module.py | {
"start": 892,
"end": 3950
} | class ____:
@pytest.mark.parametrize('sfx', all_sfx)
def test_num_lanes(self, sfx):
nlanes = getattr(npyv, "nlanes_" + sfx)
vector = getattr(npyv, "setall_" + sfx)(1)
assert len(vector) == nlanes
@pytest.mark.parametrize('sfx', all_sfx)
def test_type_name(self, sfx):
vector = getattr(npyv, "setall_" + sfx)(1)
assert vector.__name__ == "npyv_" + sfx
def test_raises(self):
a, b = [npyv.setall_u32(1)] * 2
for sfx in all_sfx:
vcb = lambda intrin: getattr(npyv, f"{intrin}_{sfx}")
pytest.raises(TypeError, vcb("add"), a)
pytest.raises(TypeError, vcb("add"), a, b, a)
pytest.raises(TypeError, vcb("setall"))
pytest.raises(TypeError, vcb("setall"), [1])
pytest.raises(TypeError, vcb("load"), 1)
pytest.raises(ValueError, vcb("load"), [1])
value = getattr(npyv, f"reinterpret_{sfx}_u32")(a)
pytest.raises(ValueError, vcb("store"), [1], value)
@pytest.mark.skipif(not npyv2, reason=(
"could not find a second SIMD extension with NPYV support"
))
def test_nomix(self):
# mix among submodules isn't allowed
a = npyv.setall_u32(1)
a2 = npyv2.setall_u32(1)
pytest.raises(TypeError, npyv.add_u32, a2, a2)
pytest.raises(TypeError, npyv2.add_u32, a, a)
@pytest.mark.parametrize('sfx', unsigned_sfx)
def test_unsigned_overflow(self, sfx):
nlanes = getattr(npyv, "nlanes_" + sfx)
maxu = (1 << int(sfx[1:])) - 1
maxu_72 = (1 << 72) - 1
lane = getattr(npyv, "setall_" + sfx)(maxu_72)[0]
assert lane == maxu
lanes = getattr(npyv, "load_" + sfx)([maxu_72] * nlanes)
assert lanes == [maxu] * nlanes
lane = getattr(npyv, "setall_" + sfx)(-1)[0]
assert lane == maxu
lanes = getattr(npyv, "load_" + sfx)([-1] * nlanes)
assert lanes == [maxu] * nlanes
@pytest.mark.parametrize('sfx', signed_sfx)
def test_signed_overflow(self, sfx):
nlanes = getattr(npyv, "nlanes_" + sfx)
maxs_72 = (1 << 71) - 1
lane = getattr(npyv, "setall_" + sfx)(maxs_72)[0]
assert lane == -1
lanes = getattr(npyv, "load_" + sfx)([maxs_72] * nlanes)
assert lanes == [-1] * nlanes
mins_72 = -1 << 71
lane = getattr(npyv, "setall_" + sfx)(mins_72)[0]
assert lane == 0
lanes = getattr(npyv, "load_" + sfx)([mins_72] * nlanes)
assert lanes == [0] * nlanes
def test_truncate_f32(self):
if not npyv.simd_f32:
pytest.skip("F32 isn't support by the SIMD extension")
f32 = npyv.setall_f32(0.1)[0]
assert f32 != 0.1
assert round(f32, 1) == 0.1
def test_compare(self):
data_range = range(npyv.nlanes_u32)
vdata = npyv.load_u32(data_range)
assert vdata == list(data_range)
assert vdata == tuple(data_range)
for i in data_range:
assert vdata[i] == data_range[i]
| Test_SIMD_MODULE |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 7588,
"end": 8098
} | class ____(BaseModel, alias_generator=lambda x: x + '_'):
# MYPY: error: Required dynamic aliases disallowed [pydantic-alias]
x: int = Field(..., alias='y')
# MYPY: error: Required dynamic aliases disallowed [pydantic-alias]
KwargsAliasGeneratorModel2(x=1)
# MYPY: error: Unexpected keyword argument "x" for "KwargsAliasGeneratorModel2" [call-arg]
KwargsAliasGeneratorModel2(y=1, z=1)
# MYPY: error: Unexpected keyword argument "z" for "KwargsAliasGeneratorModel2" [call-arg]
| KwargsAliasGeneratorModel2 |
python | davidhalter__parso | parso/python/errors.py | {
"start": 45338,
"end": 45516
} | class ____(_CheckAssignmentRule):
def is_issue(self, with_item):
self._check_assignment(with_item.children[2])
@ErrorFinder.register_rule(type='del_stmt')
| _WithItemRule |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 105122,
"end": 105335
} | class ____(ShapeGuardPythonPrinter):
def __init__(self, var_to_sources: Mapping[sympy.Symbol, list[Source]]):
super().__init__(var_to_sources, lambda n: n.name(), var_to_sources)
| LoggingShapeGuardPrinter |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 109755,
"end": 109962
} | class ____(TestCase):
def test_test_zero_rank(self):
x = np.array([1, 2, 3])
assert_(isinstance(x[0], (np.int_, np.ndarray)))
assert_(type(x[0, ...]) is np.ndarray)
| TestSubscripting |
python | davidhalter__jedi | jedi/inference/value/instance.py | {
"start": 19062,
"end": 19585
} | class ____(NameWrapper):
def __init__(self, instance, class_member_name):
super().__init__(class_member_name)
self._instance = instance
@iterator_to_value_set
def infer(self):
for result_value in self._wrapped_name.infer():
yield from result_value.py__get__(self._instance, self._instance.py__class__())
def get_signatures(self):
return self.infer().get_signatures()
def get_defining_qualified_value(self):
return self._instance
| LazyInstanceClassName |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 83,
"end": 119
} | class ____(a=1, *A, **k):
...
| Test |
python | readthedocs__readthedocs.org | readthedocs/storage/s3_storage.py | {
"start": 3685,
"end": 4098
} | class ____(S3PrivateBucketMixin, S3Boto3Storage):
bucket_name = getattr(settings, "S3_BUILD_TOOLS_STORAGE_BUCKET", None)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.bucket_name:
raise ImproperlyConfigured(
"AWS S3 not configured correctly. Ensure S3_BUILD_TOOLS_STORAGE_BUCKET is defined.",
)
| S3BuildToolsStorage |
python | ansible__ansible | lib/ansible/utils/collection_loader/_collection_finder.py | {
"start": 38057,
"end": 55019
} | class ____:
# FUTURE: introspect plugin loaders to get these dynamically?
VALID_REF_TYPES = frozenset(_to_text(r) for r in ['action', 'become', 'cache', 'callback', 'cliconf', 'connection',
'doc_fragments', 'filter', 'httpapi', 'inventory', 'lookup',
'module_utils', 'modules', 'netconf', 'role', 'shell', 'strategy',
'terminal', 'test', 'vars', 'playbook'])
# FIXME: tighten this up to match Python identifier reqs, etc
VALID_SUBDIRS_RE = re.compile(_to_text(r'^\w+(\.\w+)*$'))
VALID_FQCR_RE = re.compile(_to_text(r'^\w+(\.\w+){2,}$')) # can have 0-N included subdirs as well
def __init__(self, collection_name, subdirs, resource, ref_type):
"""
Create an AnsibleCollectionRef from components
:param collection_name: a collection name of the form 'namespace.collectionname'
:param subdirs: optional subdir segments to be appended below the plugin type (eg, 'subdir1.subdir2')
:param resource: the name of the resource being references (eg, 'mymodule', 'someaction', 'a_role')
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment'
"""
collection_name = _to_text(collection_name, strict=True)
if subdirs is not None:
subdirs = _to_text(subdirs, strict=True)
resource = _to_text(resource, strict=True)
ref_type = _to_text(ref_type, strict=True)
if not self.is_valid_collection_name(collection_name):
raise ValueError('invalid collection name (must be of the form namespace.collection): {0}'.format(_to_text(collection_name)))
if ref_type not in self.VALID_REF_TYPES:
raise ValueError('invalid collection ref_type: {0}'.format(ref_type))
self.collection = collection_name
if subdirs:
if not re.match(self.VALID_SUBDIRS_RE, subdirs):
raise ValueError('invalid subdirs entry: {0} (must be empty/None or of the form subdir1.subdir2)'.format(_to_text(subdirs)))
self.subdirs = subdirs
else:
self.subdirs = u''
self.resource = resource
self.ref_type = ref_type
package_components = [u'ansible_collections', self.collection]
fqcr_components = [self.collection]
self.n_python_collection_package_name = _to_text('.'.join(package_components))
if self.ref_type == u'role':
package_components.append(u'roles')
elif self.ref_type == u'playbook':
package_components.append(u'playbooks')
else:
# we assume it's a plugin
package_components += [u'plugins', self.ref_type]
if self.subdirs:
package_components.append(self.subdirs)
fqcr_components.append(self.subdirs)
if self.ref_type in (u'role', u'playbook'):
# playbooks and roles are their own resource
package_components.append(self.resource)
fqcr_components.append(self.resource)
self.n_python_package_name = _to_text('.'.join(package_components))
self._fqcr = u'.'.join(fqcr_components)
def __repr__(self):
return 'AnsibleCollectionRef(collection={0!r}, subdirs={1!r}, resource={2!r})'.format(self.collection, self.subdirs, self.resource)
@property
def fqcr(self):
return self._fqcr
@staticmethod
def from_fqcr(ref, ref_type):
"""
Parse a string as a fully-qualified collection reference, raises ValueError if invalid
:param ref: collection reference to parse (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource')
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment'
:return: a populated AnsibleCollectionRef object
"""
# assuming the fq_name is of the form (ns).(coll).(optional_subdir_N).(resource_name),
# we split the resource name off the right, split ns and coll off the left, and we're left with any optional
# subdirs that need to be added back below the plugin-specific subdir we'll add. So:
# ns.coll.resource -> ansible_collections.ns.coll.plugins.(plugintype).resource
# ns.coll.subdir1.resource -> ansible_collections.ns.coll.plugins.subdir1.(plugintype).resource
# ns.coll.rolename -> ansible_collections.ns.coll.roles.rolename
if not AnsibleCollectionRef.is_valid_fqcr(ref):
raise ValueError('{0} is not a valid collection reference'.format(_to_text(ref)))
ref = _to_text(ref, strict=True)
ref_type = _to_text(ref_type, strict=True)
ext = ''
if ref_type == u'playbook' and ref.endswith(PB_EXTENSIONS):
resource_splitname = ref.rsplit(u'.', 2)
package_remnant = resource_splitname[0]
resource = resource_splitname[1]
ext = '.' + resource_splitname[2]
else:
resource_splitname = ref.rsplit(u'.', 1)
package_remnant = resource_splitname[0]
resource = resource_splitname[1]
# split the left two components of the collection package name off, anything remaining is plugin-type
# specific subdirs to be added back on below the plugin type
package_splitname = package_remnant.split(u'.', 2)
if len(package_splitname) == 3:
subdirs = package_splitname[2]
else:
subdirs = u''
collection_name = u'.'.join(package_splitname[0:2])
return AnsibleCollectionRef(collection_name, subdirs, resource + ext, ref_type)
@staticmethod
def try_parse_fqcr(ref, ref_type):
"""
Attempt to parse a string as a fully-qualified collection reference, returning None on failure (instead of raising an error)
:param ref: collection reference to parse (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource')
:param ref_type: the type of the reference, eg 'module', 'role', 'doc_fragment'
:return: a populated AnsibleCollectionRef object on successful parsing, else None
"""
try:
return AnsibleCollectionRef.from_fqcr(ref, ref_type)
except ValueError:
pass
@staticmethod
def legacy_plugin_dir_to_plugin_type(legacy_plugin_dir_name):
"""
Utility method to convert from a PluginLoader dir name to a plugin ref_type
:param legacy_plugin_dir_name: PluginLoader dir name (eg, 'action_plugins', 'library')
:return: the corresponding plugin ref_type (eg, 'action', 'role')
"""
if legacy_plugin_dir_name is None:
plugin_type = None
else:
legacy_plugin_dir_name = _to_text(legacy_plugin_dir_name)
plugin_type = legacy_plugin_dir_name.removesuffix(u'_plugins')
if plugin_type == u'library':
plugin_type = u'modules'
if plugin_type not in AnsibleCollectionRef.VALID_REF_TYPES:
raise ValueError(f'{legacy_plugin_dir_name!r} cannot be mapped to a valid collection ref type')
return plugin_type
@staticmethod
def is_valid_fqcr(ref, ref_type=None):
"""
Validates if is string is a well-formed fully-qualified collection reference (does not look up the collection itself)
:param ref: candidate collection reference to validate (a valid ref is of the form 'ns.coll.resource' or 'ns.coll.subdir1.subdir2.resource')
:param ref_type: optional reference type to enable deeper validation, eg 'module', 'role', 'doc_fragment'
:return: True if the collection ref passed is well-formed, False otherwise
"""
ref = _to_text(ref)
if not ref_type:
return bool(re.match(AnsibleCollectionRef.VALID_FQCR_RE, ref))
return bool(AnsibleCollectionRef.try_parse_fqcr(ref, ref_type))
@staticmethod
def is_valid_collection_name(collection_name):
"""
Validates if the given string is a well-formed collection name (does not look up the collection itself)
:param collection_name: candidate collection name to validate (a valid name is of the form 'ns.collname')
:return: True if the collection name passed is well-formed, False otherwise
"""
collection_name = _to_text(collection_name)
if collection_name.count(u'.') != 1:
return False
return all(
# NOTE: keywords and identifiers are different in different Pythons
not iskeyword(ns_or_name) and ns_or_name.isidentifier()
for ns_or_name in collection_name.split(u'.')
)
def _get_collection_path(collection_name):
collection_name = _to_text(collection_name)
if not collection_name or not isinstance(collection_name, str) or len(collection_name.split('.')) != 2:
raise ValueError('collection_name must be a non-empty string of the form namespace.collection')
try:
collection_pkg = import_module('ansible_collections.' + collection_name)
except ImportError:
raise ValueError('unable to locate collection {0}'.format(collection_name))
return _to_text(os.path.dirname(_to_bytes(collection_pkg.__file__)))
def _get_collection_playbook_path(playbook):
acr = AnsibleCollectionRef.try_parse_fqcr(playbook, u'playbook')
if acr:
try:
# get_collection_path
pkg = import_module(acr.n_python_collection_package_name)
except (OSError, ModuleNotFoundError) as ex:
# leaving ex as debug target, even though not used in normal code
pkg = None
if pkg:
cpath = os.path.join(sys.modules[acr.n_python_collection_package_name].__file__.replace('__synthetic__', 'playbooks'))
if acr.subdirs:
paths = [_to_text(x) for x in acr.subdirs.split(u'.')]
paths.insert(0, cpath)
cpath = os.path.join(*paths)
path = os.path.join(cpath, _to_text(acr.resource))
if os.path.exists(_to_bytes(path)):
return acr.resource, path, acr.collection
elif not acr.resource.endswith(PB_EXTENSIONS):
for ext in PB_EXTENSIONS:
path = os.path.join(cpath, _to_text(acr.resource + ext))
if os.path.exists(_to_bytes(path)):
return acr.resource, path, acr.collection
return None
def _get_collection_role_path(role_name, collection_list=None):
return _get_collection_resource_path(role_name, u'role', collection_list)
def _get_collection_resource_path(name, ref_type, collection_list=None):
if ref_type == u'playbook':
# they are handled a bit diff due to 'extension variance' and no collection_list
return _get_collection_playbook_path(name)
acr = AnsibleCollectionRef.try_parse_fqcr(name, ref_type)
if acr:
# looks like a valid qualified collection ref; skip the collection_list
collection_list = [acr.collection]
subdirs = acr.subdirs
resource = acr.resource
elif not collection_list:
return None # not a FQ and no collection search list spec'd, nothing to do
else:
resource = name # treat as unqualified, loop through the collection search list to try and resolve
subdirs = ''
for collection_name in collection_list:
try:
acr = AnsibleCollectionRef(collection_name=collection_name, subdirs=subdirs, resource=resource, ref_type=ref_type)
# FIXME: error handling/logging; need to catch any import failures and move along
pkg = import_module(acr.n_python_package_name)
if pkg is not None:
# the package is now loaded, get the collection's package and ask where it lives
path = os.path.dirname(_to_bytes(sys.modules[acr.n_python_package_name].__file__))
return resource, _to_text(path), collection_name
except (OSError, ModuleNotFoundError) as ex:
continue
except Exception as ex:
# FIXME: pick out typical import errors first, then error logging
continue
return None
def _get_collection_name_from_path(path):
"""
Return the containing collection name for a given path, or None if the path is not below a configured collection, or
the collection cannot be loaded (eg, the collection is masked by another of the same name higher in the configured
collection roots).
:param path: path to evaluate for collection containment
:return: collection name or None
"""
# ensure we compare full paths since pkg path will be abspath
path = _to_text(os.path.abspath(_to_bytes(path)))
path_parts = path.split('/')
if path_parts.count('ansible_collections') != 1:
return None
ac_pos = path_parts.index('ansible_collections')
# make sure it's followed by at least a namespace and collection name
if len(path_parts) < ac_pos + 3:
return None
candidate_collection_name = '.'.join(path_parts[ac_pos + 1:ac_pos + 3])
try:
# we've got a name for it, now see if the path prefix matches what the loader sees
imported_pkg_path = _to_text(os.path.dirname(_to_bytes(import_module('ansible_collections.' + candidate_collection_name).__file__)))
except ImportError:
return None
# reassemble the original path prefix up the collection name, and it should match what we just imported. If not
# this is probably a collection root that's not configured.
original_path_prefix = os.path.join('/', *path_parts[0:ac_pos + 3])
imported_pkg_path = _to_text(os.path.abspath(_to_bytes(imported_pkg_path)))
if original_path_prefix != imported_pkg_path:
return None
return candidate_collection_name
def _get_import_redirect(collection_meta_dict, fullname):
if not collection_meta_dict:
return None
return _nested_dict_get(collection_meta_dict, ['import_redirection', fullname, 'redirect'])
def _get_ancestor_redirect(redirected_package_map, fullname):
# walk the requested module's ancestor packages to see if any have been previously redirected
cur_pkg = fullname
while cur_pkg:
cur_pkg = cur_pkg.rpartition('.')[0]
ancestor_redirect = redirected_package_map.get(cur_pkg)
if ancestor_redirect:
# rewrite the prefix on fullname so we import the target first, then alias it
redirect = ancestor_redirect + fullname[len(cur_pkg):]
return redirect
return None
def _nested_dict_get(root_dict, key_list):
cur_value = root_dict
for key in key_list:
cur_value = cur_value.get(key)
if not cur_value:
return None
return cur_value
def _iter_modules_impl(paths, prefix=''):
# NB: this currently only iterates what's on disk- redirected modules are not considered
if not prefix:
prefix = ''
else:
prefix = _to_text(prefix)
# yield (module_loader, name, ispkg) for each module/pkg under path
# TODO: implement ignore/silent catch for unreadable?
for b_path in map(_to_bytes, paths):
if not os.path.isdir(b_path):
continue
for b_basename in sorted(os.listdir(b_path)):
b_candidate_module_path = os.path.join(b_path, b_basename)
if os.path.isdir(b_candidate_module_path):
# exclude things that obviously aren't Python package dirs
# FIXME: this dir is adjustable in py3.8+, check for it
if b'.' in b_basename or b_basename == b'__pycache__':
continue
# TODO: proper string handling?
yield prefix + _to_text(b_basename), True
else:
# FIXME: match builtin ordering for package/dir/file, support compiled?
if b_basename.endswith(b'.py') and b_basename != b'__init__.py':
yield prefix + _to_text(os.path.splitext(b_basename)[0]), False
def _get_collection_metadata(collection_name):
collection_name = _to_text(collection_name)
if not collection_name or not isinstance(collection_name, str) or len(collection_name.split('.')) != 2:
raise ValueError('collection_name must be a non-empty string of the form namespace.collection')
try:
collection_pkg = import_module('ansible_collections.' + collection_name)
except ImportError as ex:
raise ValueError('unable to locate collection {0}'.format(collection_name)) from ex
_collection_meta = getattr(collection_pkg, '_collection_meta', None)
if _collection_meta is None:
raise ValueError('collection metadata was not loaded for collection {0}'.format(collection_name))
return _collection_meta
| AnsibleCollectionRef |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/datetime.py | {
"start": 11650,
"end": 14079
} | class ____(SearchStrategy):
def __init__(self, min_value, max_value):
super().__init__()
assert isinstance(min_value, dt.date)
assert isinstance(max_value, dt.date)
assert min_value < max_value
self.min_value = min_value
self.max_value = max_value
def do_draw(self, data):
return dt.date(
**draw_capped_multipart(data, self.min_value, self.max_value, DATENAMES)
)
def filter(self, condition):
if (
isinstance(condition, partial)
and len(args := condition.args) == 1
and not condition.keywords
and isinstance(arg := args[0], dt.date)
and condition.func in (op.lt, op.le, op.eq, op.ge, op.gt)
):
try:
arg += dt.timedelta(days={op.lt: 1, op.gt: -1}.get(condition.func, 0))
except OverflowError: # gt date.max, or lt date.min
return nothing()
lo, hi = {
# We're talking about op(arg, x) - the reverse of our usual intuition!
op.lt: (arg, self.max_value), # lambda x: arg < x
op.le: (arg, self.max_value), # lambda x: arg <= x
op.eq: (arg, arg), # lambda x: arg == x
op.ge: (self.min_value, arg), # lambda x: arg >= x
op.gt: (self.min_value, arg), # lambda x: arg > x
}[condition.func]
lo = max(lo, self.min_value)
hi = min(hi, self.max_value)
print(lo, hi)
if hi < lo:
return nothing()
if lo <= self.min_value and self.max_value <= hi:
return self
return dates(lo, hi)
return super().filter(condition)
@defines_strategy(force_reusable_values=True)
def dates(
min_value: dt.date = dt.date.min, max_value: dt.date = dt.date.max
) -> SearchStrategy[dt.date]:
"""dates(min_value=datetime.date.min, max_value=datetime.date.max)
A strategy for dates between ``min_value`` and ``max_value``.
Examples from this strategy shrink towards January 1st 2000.
"""
check_type(dt.date, min_value, "min_value")
check_type(dt.date, max_value, "max_value")
check_valid_interval(min_value, max_value, "min_value", "max_value")
if min_value == max_value:
return just(min_value)
return DateStrategy(min_value, max_value)
| DateStrategy |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/stream_reader.py | {
"start": 3575,
"end": 7978
} | class ____(AbstractFileBasedStreamReader):
_credentials = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._config = None
@property
def config(self) -> SourceAzureBlobStorageSpec:
return self._config
@config.setter
def config(self, value: SourceAzureBlobStorageSpec) -> None:
self._config = value
@property
def account_url(self) -> str:
if not self.config.azure_blob_storage_endpoint:
return f"https://{self.config.azure_blob_storage_account_name}.blob.core.windows.net"
return self.config.azure_blob_storage_endpoint
@property
def azure_container_client(self):
return ContainerClient(
self.account_url, container_name=self.config.azure_blob_storage_container_name, credential=self.azure_credentials
)
@property
def azure_blob_service_client(self):
return BlobServiceClient(self.account_url, credential=self._credentials)
@property
def azure_credentials(self) -> Union[str, AzureOauth2Authenticator, AzureClientCredentialsAuthenticator]:
if not self._credentials:
if self.config.credentials.auth_type == "storage_account_key":
self._credentials = self.config.credentials.azure_blob_storage_account_key
elif self.config.credentials.auth_type == "oauth2":
self._credentials = AzureOauth2Authenticator(
token_refresh_endpoint=f"https://login.microsoftonline.com/{self.config.credentials.tenant_id}/oauth2/v2.0/token",
client_id=self.config.credentials.client_id,
client_secret=self.config.credentials.client_secret,
refresh_token=self.config.credentials.refresh_token,
)
elif self.config.credentials.auth_type == "client_credentials":
self._credentials = AzureClientCredentialsAuthenticator(
tenant_id=self.config.credentials.app_tenant_id,
client_id=self.config.credentials.app_client_id,
client_secret=self.config.credentials.app_client_secret,
)
return self._credentials
def get_matching_files(
self,
globs: List[str],
prefix: Optional[str],
logger: logging.Logger,
) -> Iterable[AzureBlobStorageUploadableRemoteFile]:
prefixes = [prefix] if prefix else self.get_prefixes_from_globs(globs)
prefixes = prefixes or [None]
try:
for prefix in prefixes:
for blob in self.azure_container_client.list_blobs(name_starts_with=prefix):
remote_file = AzureBlobStorageUploadableRemoteFile(
uri=blob.name,
last_modified=blob.last_modified.astimezone(pytz.utc).replace(tzinfo=None),
blob_client=self.azure_blob_service_client,
blob_properties=blob,
created_at=blob.creation_time.astimezone(pytz.utc).replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
updated_at=blob.last_modified.astimezone(pytz.utc).replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
)
yield from self.filter_files_by_globs_and_start_date([remote_file], globs)
except ResourceNotFoundError as e:
raise AirbyteTracedException(failure_type=FailureType.config_error, internal_message=e.message, message=e.reason or e.message)
def open_file(
self, file: AzureBlobStorageUploadableRemoteFile, mode: FileReadMode, encoding: Optional[str], logger: logging.Logger
) -> IOBase:
try:
result = so_open(
f"azure://{self.config.azure_blob_storage_container_name}/{file.uri}",
transport_params={"client": self.azure_blob_service_client},
mode=mode.value,
encoding=encoding,
)
except OSError:
logger.warning(
f"We don't have access to {file.uri}. The file appears to have become unreachable during sync."
f"Check whether key {file.uri} exists in `{self.config.azure_blob_storage_container_name}` container and/or has proper ACL permissions"
)
return result
| SourceAzureBlobStorageStreamReader |
python | django__django | tests/admin_ordering/tests.py | {
"start": 4217,
"end": 7244
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.b1 = Band.objects.create(name="Pink Floyd", bio="", rank=1)
cls.b2 = Band.objects.create(name="Foo Fighters", bio="", rank=5)
def setUp(self):
# we need to register a custom ModelAdmin (instead of just using
# ModelAdmin) because the field creator tries to find the ModelAdmin
# for the related model
class SongAdmin(admin.ModelAdmin):
pass
site.register(Song, SongAdmin)
def tearDown(self):
site.unregister(Song)
if site.is_registered(Band):
site.unregister(Band)
def check_ordering_of_field_choices(self, correct_ordering):
fk_field = site.get_model_admin(Song).formfield_for_foreignkey(
Song.band.field, request=None
)
m2m_field = site.get_model_admin(Song).formfield_for_manytomany(
Song.other_interpreters.field, request=None
)
self.assertEqual(list(fk_field.queryset), correct_ordering)
self.assertEqual(list(m2m_field.queryset), correct_ordering)
def test_no_admin_fallback_to_model_ordering(self):
# should be ordered by name (as defined by the model)
self.check_ordering_of_field_choices([self.b2, self.b1])
def test_admin_with_no_ordering_fallback_to_model_ordering(self):
class NoOrderingBandAdmin(admin.ModelAdmin):
pass
site.register(Band, NoOrderingBandAdmin)
# should be ordered by name (as defined by the model)
self.check_ordering_of_field_choices([self.b2, self.b1])
def test_admin_ordering_beats_model_ordering(self):
class StaticOrderingBandAdmin(admin.ModelAdmin):
ordering = ("rank",)
site.register(Band, StaticOrderingBandAdmin)
# should be ordered by rank (defined by the ModelAdmin)
self.check_ordering_of_field_choices([self.b1, self.b2])
def test_custom_queryset_still_wins(self):
"""Custom queryset has still precedence (#21405)"""
class SongAdmin(admin.ModelAdmin):
# Exclude one of the two Bands from the querysets
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "band":
kwargs["queryset"] = Band.objects.filter(rank__gt=2)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "other_interpreters":
kwargs["queryset"] = Band.objects.filter(rank__gt=2)
return super().formfield_for_foreignkey(db_field, request, **kwargs)
class StaticOrderingBandAdmin(admin.ModelAdmin):
ordering = ("rank",)
site.unregister(Song)
site.register(Song, SongAdmin)
site.register(Band, StaticOrderingBandAdmin)
self.check_ordering_of_field_choices([self.b2])
| TestRelatedFieldsAdminOrdering |
python | openai__openai-python | src/openai/types/beta/threads/runs/run_step_delta_event.py | {
"start": 237,
"end": 585
} | class ____(BaseModel):
id: str
"""The identifier of the run step, which can be referenced in API endpoints."""
delta: RunStepDelta
"""The delta containing the fields that have changed on the run step."""
object: Literal["thread.run.step.delta"]
"""The object type, which is always `thread.run.step.delta`."""
| RunStepDeltaEvent |
python | walkccc__LeetCode | solutions/299. Bulls and Cows/299.py | {
"start": 0,
"end": 239
} | class ____:
def getHint(self, secret: str, guess: str) -> str:
bulls = sum(map(operator.eq, secret, guess))
bovine = sum(min(secret.count(x), guess.count(x)) for x in set(guess))
return '%dA%dB' % (bulls, bovine - bulls)
| Solution |
python | huggingface__transformers | src/transformers/models/clip/modeling_clip.py | {
"start": 37207,
"end": 39389
} | class ____(CLIPPreTrainedModel):
config: CLIPTextConfig
input_modalities = ("text",)
_no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer"]
def __init__(self, config: CLIPTextConfig):
super().__init__(config)
text_model = CLIPTextModel._from_config(config)
self.text_model = text_model.text_model
self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.text_model.embeddings.token_embedding
def set_input_embeddings(self, value):
self.text_model.embeddings.token_embedding = value
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> CLIPTextModelOutput:
r"""
Examples:
```python
>>> import torch
>>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
>>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
>>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> with torch.inference_mode():
... outputs = model(**inputs)
>>> text_embeds = outputs.text_embeds
```"""
text_outputs: BaseModelOutputWithPooling = self.text_model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
**kwargs,
)
pooled_output = text_outputs.pooler_output
text_embeds = self.text_projection(pooled_output)
return CLIPTextModelOutput(
text_embeds=text_embeds,
last_hidden_state=text_outputs.last_hidden_state,
)
@auto_docstring
| CLIPTextModelWithProjection |
python | sympy__sympy | sympy/core/coreerrors.py | {
"start": 303,
"end": 642
} | class ____:
"""Wrapper class that lets you specify an expensive to compute
error message that is only evaluated if the error is rendered."""
callback: Callable[[], str]
def __init__(self, callback: Callable[[], str]):
self.callback = callback
def __str__(self):
return self.callback()
| LazyExceptionMessage |
python | pytorch__pytorch | torch/ao/quantization/quantizer/xpu_inductor_quantizer.py | {
"start": 2029,
"end": 3797
} | class ____(X86InductorQuantizer):
"""
XPUInductorQuantizer is a class designed to facilitate
quantization capability at Intel GPU backend. The class
highly reuses the existing implementation of
X86InductorQuantizer as both are intended to take advantage
of the optimized kernels in oneDNN library.
"""
"""
Following annotate_xx overrides the impls in base class, as
no XPU implementation for these operators currently. We would
gradually enable the XPU implementation and remove following
overrides. We keep the annotate methods but make the function
body empty, aiming to let `_generate_qdq_quantized_model`
generate qdq around op and graph execute on fp32 dtype for
unsupported operators.
"""
def _annotate_qat_conv2d_fusion_pattern(
self,
model: torch.fx.GraphModule,
quantization_config: QuantizationConfig | None,
filter_fn: FilterFn | None = None,
):
pass
def _annotate_maxpool2d(
self,
node: Node,
quantization_config: QuantizationConfig | None,
) -> None:
"""
Here we skip the annotate logic for maxpool at XPU backend
as the quantized::max_pool2d is only implemented for CPU.
"""
return
def _annotate_output_for_int8_in_int8_out_pattern(
self,
node: Node,
) -> None:
if (node.target in int8_in_int8_out_ops) and (_is_any_annotated([node])):
if node.target is torch.ops.aten.max_pool2d.default:
return
else:
input_node = node.all_input_nodes[0]
self._annotate_output_share_observer_as_input(input_node, node)
return
| XPUInductorQuantizer |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 4064,
"end": 5676
} | class ____(nn.Embedding):
"""
This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
"""
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
super().__init__(num_embeddings, embedding_dim, padding_idx)
self.embed_scale = embed_scale
def forward(self, input_ids: torch.Tensor):
return super().forward(input_ids) * self.embed_scale
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: Optional[float] = None,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
if scaling is None:
scaling = query.size(-1) ** -0.5
# Take the dot product between "query" and "key" to get the raw attention scores.
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
if attention_mask is not None:
attention_mask = attention_mask[:, :, :, : key.shape[-2]]
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->MBart
| MBartScaledWordEmbedding |
python | doocs__leetcode | solution/2100-2199/2107.Number of Unique Flavors After Sharing K Candies/Solution.py | {
"start": 0,
"end": 377
} | class ____:
def shareCandies(self, candies: List[int], k: int) -> int:
cnt = Counter(candies[k:])
ans = len(cnt)
for i in range(k, len(candies)):
cnt[candies[i - k]] += 1
cnt[candies[i]] -= 1
if cnt[candies[i]] == 0:
cnt.pop(candies[i])
ans = max(ans, len(cnt))
return ans
| Solution |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_mlengine.py | {
"start": 29456,
"end": 47038
} | class ____:
def setup_method(self):
with mock.patch(
"airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.__init__",
new=mock_base_gcp_hook_default_project_id,
):
self.hook = hook.MLEngineHook()
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_create_version(self, mock_get_conn, mock_project_id):
model_name = "test-model"
version_name = "test-version"
version = {"name": version_name}
operation_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/operations/test-operation"
model_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}"
operation_done = {"name": operation_path, "done": True}
(
mock_get_conn.return_value.projects.return_value.models.return_value.versions.return_value.create.return_value.execute.return_value
) = version
(
mock_get_conn.return_value.projects.return_value.operations.return_value.get.return_value.execute.return_value
) = {"name": operation_path, "done": True}
create_version_response = self.hook.create_version(
model_name=model_name, version_spec=version, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST
)
assert create_version_response == operation_done
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().versions().create(body=version, parent=model_path),
mock.call().projects().models().versions().create().execute(num_retries=5),
mock.call().projects().operations().get(name=version_name),
mock.call().projects().operations().get().execute(num_retries=5),
],
any_order=True,
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_set_default_version(self, mock_get_conn, mock_project_id):
model_name = "test-model"
version_name = "test-version"
operation_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/operations/test-operation"
version_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}/versions/{version_name}"
operation_done = {"name": operation_path, "done": True}
(
mock_get_conn.return_value.projects.return_value.models.return_value.versions.return_value.setDefault.return_value.execute.return_value
) = operation_done
set_default_version_response = self.hook.set_default_version(
model_name=model_name,
version_name=version_name,
project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
assert set_default_version_response == operation_done
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().versions().setDefault(body={}, name=version_path),
mock.call().projects().models().versions().setDefault().execute(num_retries=5),
],
any_order=True,
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.time.sleep")
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_list_versions(self, mock_get_conn, mock_sleep, mock_project_id):
model_name = "test-model"
model_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}"
version_names = [f"ver_{ix}" for ix in range(3)]
response_bodies = [
{"nextPageToken": f"TOKEN-{ix}", "versions": [ver]} for ix, ver in enumerate(version_names)
]
response_bodies[-1].pop("nextPageToken")
pages_requests = [mock.Mock(**{"execute.return_value": body}) for body in response_bodies]
versions_mock = mock.Mock(
**{"list.return_value": pages_requests[0], "list_next.side_effect": pages_requests[1:] + [None]}
)
(
mock_get_conn.return_value.projects.return_value.models.return_value.versions.return_value
) = versions_mock
list_versions_response = self.hook.list_versions(
model_name=model_name, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST
)
assert list_versions_response == version_names
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().versions().list(pageSize=100, parent=model_path),
mock.call().projects().models().versions().list().execute(num_retries=5),
]
+ [
mock.call()
.projects()
.models()
.versions()
.list_next(previous_request=pages_requests[i], previous_response=response_bodies[i])
for i in range(3)
],
any_order=True,
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_delete_version(self, mock_get_conn, mock_project_id):
model_name = "test-model"
version_name = "test-version"
operation_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/operations/test-operation"
version_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}/versions/{version_name}"
version = {"name": operation_path}
operation_not_done = {"name": operation_path, "done": False}
operation_done = {"name": operation_path, "done": True}
(
mock_get_conn.return_value.projects.return_value.operations.return_value.get.return_value.execute.side_effect
) = [operation_not_done, operation_done]
(
mock_get_conn.return_value.projects.return_value.models.return_value.versions.return_value.delete.return_value.execute.return_value
) = version
delete_version_response = self.hook.delete_version(
model_name=model_name, version_name=version_name, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST
)
assert delete_version_response == operation_done
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().versions().delete(name=version_path),
mock.call().projects().models().versions().delete().execute(num_retries=5),
mock.call().projects().operations().get(name=operation_path),
mock.call().projects().operations().get().execute(num_retries=5),
],
any_order=True,
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_create_model(self, mock_get_conn, mock_project_id):
model_name = "test-model"
model = {
"name": model_name,
}
project_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}"
(
mock_get_conn.return_value.projects.return_value.models.return_value.create.return_value.execute.return_value
) = model
create_model_response = self.hook.create_model(model=model, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST)
assert create_model_response == model
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().create(body=model, parent=project_path),
mock.call().projects().models().create().execute(num_retries=5),
]
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_get_model(self, mock_get_conn, mock_project_id):
model_name = "test-model"
model = {"model": model_name}
model_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}"
(
mock_get_conn.return_value.projects.return_value.models.return_value.get.return_value.execute.return_value
) = model
get_model_response = self.hook.get_model(
model_name=model_name, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST
)
assert get_model_response == model
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().get(name=model_path),
mock.call().projects().models().get().execute(num_retries=5),
]
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_delete_model(self, mock_get_conn, mock_project_id):
model_name = "test-model"
model = {"model": model_name}
model_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/models/{model_name}"
(
mock_get_conn.return_value.projects.return_value.models.return_value.delete.return_value.execute.return_value
) = model
self.hook.delete_model(model_name=model_name, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST)
mock_get_conn.assert_has_calls(
[
mock.call().projects().models().delete(name=model_path),
mock.call().projects().models().delete().execute(num_retries=5),
]
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.time.sleep")
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_create_mlengine_job(self, mock_get_conn, mock_sleep, mock_project_id):
job_id = "test-job-id"
project_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}"
job_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/jobs/{job_id}"
new_job = {
"jobId": job_id,
"foo": 4815162342,
}
job_succeeded = {
"jobId": job_id,
"state": "SUCCEEDED",
}
job_queued = {
"jobId": job_id,
"state": "QUEUED",
}
(
mock_get_conn.return_value.projects.return_value.jobs.return_value.create.return_value.execute.return_value
) = job_queued
(
mock_get_conn.return_value.projects.return_value.jobs.return_value.get.return_value.execute.side_effect
) = [job_queued, job_succeeded]
create_job_response = self.hook.create_job(job=new_job, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST)
assert create_job_response == job_succeeded
mock_get_conn.assert_has_calls(
[
mock.call().projects().jobs().create(body=new_job, parent=project_path),
mock.call().projects().jobs().get(name=job_path),
mock.call().projects().jobs().get().execute(num_retries=5),
],
any_order=True,
)
@mock.patch(
"airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id",
new_callable=PropertyMock,
return_value=GCP_PROJECT_ID_HOOK_UNIT_TEST,
)
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineHook.get_conn")
def test_cancel_mlengine_job(self, mock_get_conn, mock_project_id):
job_id = "test-job-id"
job_path = f"projects/{GCP_PROJECT_ID_HOOK_UNIT_TEST}/jobs/{job_id}"
job_cancelled = {}
(
mock_get_conn.return_value.projects.return_value.jobs.return_value.cancel.return_value.execute.return_value
) = job_cancelled
cancel_job_response = self.hook.cancel_job(job_id=job_id, project_id=GCP_PROJECT_ID_HOOK_UNIT_TEST)
assert cancel_job_response == job_cancelled
mock_get_conn.assert_has_calls(
[
mock.call().projects().jobs().cancel(name=job_path),
mock.call().projects().jobs().cancel().execute(num_retries=5),
],
any_order=True,
)
def session():
return mock.Mock()
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineAsyncHook._get_link")
async def test_async_get_job_should_execute_successfully(mocked_link):
await mlengine_hook.get_job(project_id=PROJECT_ID, job_id=JOB_ID, session=session)
mocked_link.assert_awaited_once_with(
url=f"https://ml.googleapis.com/v1/projects/{PROJECT_ID}/jobs/{JOB_ID}", session=session
)
@pytest.mark.asyncio
async def test_async_get_job_should_fail_if_no_job_id():
with pytest.raises(
AirflowException, match=r"An unique job id is required for Google MLEngine training job."
):
await mlengine_hook.get_job(project_id=PROJECT_ID, job_id=None, session=session)
@pytest.mark.asyncio
async def test_async_get_job_should_fail_if_no_project_id():
with pytest.raises(AirflowException, match=r"Google Cloud project id is required."):
await mlengine_hook.get_job(project_id=None, job_id=JOB_ID, session=session)
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineAsyncHook.get_job")
async def test_async_get_job_status_should_execute_successfully(mocked_get):
mocked_get.return_value = ClientResponse(
"get",
URL(f"https://ml.googleapis.com/v1/projects/{PROJECT_ID}/jobs/{JOB_ID}"),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=mock.Mock(),
session=None,
)
mocked_get.return_value._headers = {"Content-Type": "application/json;charset=cp1251"}
mocked_get.return_value._body = b'{"state": "SUCCEEDED"}'
job_status = await mlengine_hook.get_job_status(job_id=JOB_ID, project_id=PROJECT_ID)
mocked_get.assert_awaited_once()
assert job_status == "success"
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineAsyncHook.get_job")
async def test_async_get_job_status_still_running_should_execute_successfully(mocked_get):
"""Assets that the MLEngineAsyncHook returns a pending response when job is still in running state"""
mocked_get.return_value = ClientResponse(
"get",
URL(f"https://ml.googleapis.com/v1/projects/{PROJECT_ID}/jobs/{JOB_ID}"),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=mock.Mock(),
session=None,
)
mocked_get.return_value._headers = {"Content-Type": "application/json;charset=cp1251"}
mocked_get.return_value._body = b'{"state": "RUNNING"}'
job_status = await mlengine_hook.get_job_status(job_id=JOB_ID, project_id=PROJECT_ID)
mocked_get.assert_awaited_once()
assert job_status == "pending"
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineAsyncHook.get_job")
async def test_async_get_job_status_with_oserror_should_execute_successfully(mocked_get):
"""Assets that the MLEngineAsyncHook returns a pending response when OSError is raised"""
mocked_get.side_effect = OSError()
job_status = await mlengine_hook.get_job_status(job_id=JOB_ID, project_id=PROJECT_ID)
mocked_get.assert_awaited_once()
assert job_status == "pending"
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.mlengine.MLEngineAsyncHook.get_job")
async def test_async_get_job_status_with_exception_should_execute_successfully(mocked_get, caplog):
"""Assets that the logging is done correctly when MLEngineAsyncHook raises Exception"""
caplog.set_level(logging.INFO)
mocked_get.side_effect = Exception()
await mlengine_hook.get_job_status(job_id=JOB_ID, project_id=PROJECT_ID)
assert "Query execution finished with errors..." in caplog.text
@pytest.mark.asyncio
async def test_async_get_job_status_should_fail_if_no_job_id():
with pytest.raises(
AirflowException, match=r"An unique job id is required for Google MLEngine training job."
):
await mlengine_hook.get_job_status(project_id=PROJECT_ID, job_id=None)
@pytest.mark.asyncio
async def test_async_get_job_status_should_fail_if_no_project_id():
with pytest.raises(AirflowException, match=r"Google Cloud project id is required."):
await mlengine_hook.get_job_status(project_id=None, job_id=JOB_ID)
| TestMLEngineHookWithDefaultProjectId |
python | mlflow__mlflow | tests/utils/test_annotations.py | {
"start": 1273,
"end": 8250
} | class ____:
"""
A deprecated dataclass with decorators in different order.
"""
m: int
n: int
def test_deprecated_method():
msg = "``tests.utils.test_annotations.MyClass.method`` is deprecated"
with pytest.warns(FutureWarning, match=re.escape(msg)):
assert MyClass().method() == 0
docstring = MyClass.method.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_function():
msg = "``tests.utils.test_annotations.function`` is deprecated"
with pytest.warns(FutureWarning, match=re.escape(msg)):
assert function() == 1
docstring = function.__doc__
assert docstring is not None
assert msg in docstring
def test_empty_docstring():
docstring = ""
expected_indent = ""
assert _get_min_indent_of_docstring(docstring) == expected_indent
def test_single_line_docstring():
docstring = """Single line with indent."""
expected_indent = ""
assert _get_min_indent_of_docstring(docstring) == expected_indent
def test_multi_line_docstring_first_line():
first_line_docstring = """Description
Args:
x: x
Returns:
y
"""
expected_indent = " "
assert _get_min_indent_of_docstring(first_line_docstring) == expected_indent
def test_multi_line_docstring_second_line():
second_line_docstring = """
Description
Args:
x: x
Returns:
y
"""
expected_indent = " "
assert _get_min_indent_of_docstring(second_line_docstring) == expected_indent
def test_deprecated_and_keyword_first():
docstring = deprecated_and_keyword_only_first.__doc__
assert docstring is not None
assert docstring.rstrip() == (
""" .. note:: This method requires all argument be specified by keyword.
.. Warning:: ``tests.utils.test_annotations.deprecated_and_keyword_only_first`` is deprecated since 0.0.0. This method will be removed in a future release.
Description
Args:
x: x
Returns:
y""" # noqa: E501
)
def test_deprecated_and_keyword_second():
docstring = deprecated_and_keyword_only_second.__doc__
assert docstring is not None
assert docstring.rstrip() == (
""" .. Warning:: ``tests.utils.test_annotations.deprecated_and_keyword_only_second`` is deprecated since 0.0.0. This method will be removed in a future release.
.. note:: This method requires all argument be specified by keyword.
Description
Args:
x: x
Returns:
y""" # noqa: E501
)
def test_deprecated_class():
msg = "``tests.utils.test_annotations.DeprecatedClass`` is deprecated"
with pytest.warns(FutureWarning, match=re.escape(msg)):
DeprecatedClass()
docstring = DeprecatedClass.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_class_method():
msg = "``tests.utils.test_annotations.DeprecatedClass`` is deprecated"
with pytest.warns(FutureWarning, match=re.escape(msg)):
instance = DeprecatedClass()
assert instance.greet() == "Hello"
docstring = DeprecatedClass.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_dataclass():
msg = "``tests.utils.test_annotations.DeprecatedDataClass`` is deprecated since 1.0.0"
with pytest.warns(FutureWarning, match=re.escape(msg)):
DeprecatedDataClass(x=10, y=20)
docstring = DeprecatedDataClass.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_dataclass_fields():
msg = "``tests.utils.test_annotations.DeprecatedDataClass`` is deprecated since 1.0.0"
with pytest.warns(FutureWarning, match=re.escape(msg)):
instance = DeprecatedDataClass(x=5, y=15)
assert instance.x == 5
assert instance.y == 15
docstring = DeprecatedDataClass.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_dataclass_method():
msg = "``tests.utils.test_annotations.AnotherDeprecatedDataClass`` is deprecated since 1.0.0"
with pytest.warns(FutureWarning, match=re.escape(msg)):
instance = AnotherDeprecatedDataClass(a=3, b=4)
assert instance.add() == 7
docstring = AnotherDeprecatedDataClass.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_dataclass_different_order():
msg = "``tests.utils.test_annotations.AnotherDeprecatedDataClassOrder`` is deprecated"
with pytest.warns(FutureWarning, match=re.escape(msg)):
AnotherDeprecatedDataClassOrder(m=7, n=8)
docstring = AnotherDeprecatedDataClassOrder.__doc__
assert docstring is not None
assert msg in docstring
def test_deprecated_dataclass_dunder_methods():
instance = DeprecatedDataClass(x=1, y=2)
assert instance.x == 1
assert instance.y == 2
expected_repr = "DeprecatedDataClass(x=1, y=2)"
assert repr(instance) == expected_repr
instance2 = DeprecatedDataClass(x=1, y=2)
instance3 = DeprecatedDataClass(x=2, y=3)
assert instance == instance2
assert instance != instance3
def test_deprecated_dataclass_preserves_fields():
instance = DeprecatedDataClass(x=100, y=200)
field_names = {f.name for f in fields(DeprecatedDataClass)}
assert field_names == {"x", "y"}
assert instance.x == 100
assert instance.y == 200
def test_deprecated_dataclass_preserves_methods():
instance = DeprecatedDataClass(x=10, y=20)
assert instance.add() == 30
def test_deprecated_dataclass_preserves_class_attributes():
assert DeprecatedDataClass.__module__ == "tests.utils.test_annotations"
assert DeprecatedDataClass.__qualname__ == "DeprecatedDataClass"
def test_deprecated_dataclass_dunder_methods_not_mutated():
instance = DeprecatedDataClass(x=5, y=10)
assert instance.x == 5
assert instance.y == 10
expected_repr = "DeprecatedDataClass(x=5, y=10)"
assert repr(instance) == expected_repr
same_instance = DeprecatedDataClass(x=5, y=10)
different_instance = DeprecatedDataClass(x=1, y=2)
assert instance == same_instance
assert instance != different_instance
assert instance.add() == 15
allowed_attrs = {"x", "y", "add"}
attrs = {attr for attr in dir(instance) if not attr.startswith("__")}
assert attrs == allowed_attrs
def test_deprecated_dataclass_special_methods_integrity():
instance = DeprecatedDataClass(x=42, y=84)
assert instance.x == 42
assert instance.y == 84
expected_repr = "DeprecatedDataClass(x=42, y=84)"
assert repr(instance) == expected_repr
same_instance = DeprecatedDataClass(x=42, y=84)
different_instance = DeprecatedDataClass(x=1, y=2)
assert instance == same_instance
assert instance != different_instance
assert instance.add() == 126
allowed_attrs = {"x", "y", "add"}
attrs = {attr for attr in dir(instance) if not attr.startswith("__")}
assert attrs == allowed_attrs
| AnotherDeprecatedDataClassOrder |
python | langchain-ai__langchain | libs/partners/deepseek/tests/unit_tests/test_chat_models.py | {
"start": 3527,
"end": 9436
} | class ____:
"""Custom tests specific to DeepSeek chat model."""
def test_create_chat_result_with_reasoning_content(self) -> None:
"""Test that reasoning_content is properly extracted from response."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
mock_message = MagicMock()
mock_message.content = "Main content"
mock_message.reasoning_content = "This is the reasoning content"
mock_message.role = "assistant"
mock_response = MockOpenAIResponse(
choices=[MagicMock(message=mock_message)],
error=None,
)
result = chat_model._create_chat_result(mock_response)
assert (
result.generations[0].message.additional_kwargs.get("reasoning_content")
== "This is the reasoning content"
)
def test_create_chat_result_with_model_extra_reasoning(self) -> None:
"""Test that reasoning is properly extracted from `model_extra`."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
mock_message = MagicMock(spec=ChatCompletionMessage)
mock_message.content = "Main content"
mock_message.role = "assistant"
mock_message.model_extra = {"reasoning": "This is the reasoning"}
mock_message.model_dump.return_value = {
"role": "assistant",
"content": "Main content",
"model_extra": {"reasoning": "This is the reasoning"},
}
mock_choice = MagicMock()
mock_choice.message = mock_message
mock_response = MockOpenAIResponse(choices=[mock_choice], error=None)
result = chat_model._create_chat_result(mock_response)
assert (
result.generations[0].message.additional_kwargs.get("reasoning_content")
== "This is the reasoning"
)
def test_convert_chunk_with_reasoning_content(self) -> None:
"""Test that reasoning_content is properly extracted from streaming chunk."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
chunk: dict[str, Any] = {
"choices": [
{
"delta": {
"content": "Main content",
"reasoning_content": "Streaming reasoning content",
},
},
],
}
chunk_result = chat_model._convert_chunk_to_generation_chunk(
chunk,
AIMessageChunk,
None,
)
if chunk_result is None:
msg = "Expected chunk_result not to be None"
raise AssertionError(msg)
assert (
chunk_result.message.additional_kwargs.get("reasoning_content")
== "Streaming reasoning content"
)
def test_convert_chunk_with_reasoning(self) -> None:
"""Test that reasoning is properly extracted from streaming chunk."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
chunk: dict[str, Any] = {
"choices": [
{
"delta": {
"content": "Main content",
"reasoning": "Streaming reasoning",
},
},
],
}
chunk_result = chat_model._convert_chunk_to_generation_chunk(
chunk,
AIMessageChunk,
None,
)
if chunk_result is None:
msg = "Expected chunk_result not to be None"
raise AssertionError(msg)
assert (
chunk_result.message.additional_kwargs.get("reasoning_content")
== "Streaming reasoning"
)
def test_convert_chunk_without_reasoning(self) -> None:
"""Test that chunk without reasoning fields works correctly."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
chunk: dict[str, Any] = {"choices": [{"delta": {"content": "Main content"}}]}
chunk_result = chat_model._convert_chunk_to_generation_chunk(
chunk,
AIMessageChunk,
None,
)
if chunk_result is None:
msg = "Expected chunk_result not to be None"
raise AssertionError(msg)
assert chunk_result.message.additional_kwargs.get("reasoning_content") is None
def test_convert_chunk_with_empty_delta(self) -> None:
"""Test that chunk with empty delta works correctly."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
chunk: dict[str, Any] = {"choices": [{"delta": {}}]}
chunk_result = chat_model._convert_chunk_to_generation_chunk(
chunk,
AIMessageChunk,
None,
)
if chunk_result is None:
msg = "Expected chunk_result not to be None"
raise AssertionError(msg)
assert chunk_result.message.additional_kwargs.get("reasoning_content") is None
def test_get_request_payload(self) -> None:
"""Test that tool message content is converted from list to string."""
chat_model = ChatDeepSeek(model=MODEL_NAME, api_key=SecretStr("api_key"))
tool_message = ToolMessage(content=[], tool_call_id="test_id")
payload = chat_model._get_request_payload([tool_message])
assert payload["messages"][0]["content"] == "[]"
tool_message = ToolMessage(content=["item1", "item2"], tool_call_id="test_id")
payload = chat_model._get_request_payload([tool_message])
assert payload["messages"][0]["content"] == '["item1", "item2"]'
tool_message = ToolMessage(content="test string", tool_call_id="test_id")
payload = chat_model._get_request_payload([tool_message])
assert payload["messages"][0]["content"] == "test string"
| TestChatDeepSeekCustomUnit |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/components.py | {
"start": 1046,
"end": 1969
} | class ____(DeclarativeOauth2Authenticator):
"""
This class extends the DeclarativeOauth2Authenticator functionality
and allows to pass custom headers to the refresh access token requests
"""
host: Union[InterpolatedString, str] = None
def __post_init__(self, parameters: Mapping[str, Any]) -> None:
super().__post_init__(parameters)
self._host = InterpolatedString.create(self.host, parameters=parameters)
def get_auth_header(self) -> Mapping[str, Any]:
return {
"host": self._host.eval(self.config),
"user-agent": "python-requests",
"x-amz-access-token": self.get_access_token(),
"x-amz-date": ab_datetime_now().strftime("%Y%m%dT%H%M%SZ"),
}
def get_refresh_request_headers(self) -> Mapping[str, Any]:
return {"Content-Type": "application/x-www-form-urlencoded"}
@dataclass
| AmazonSPOauthAuthenticator |
python | doocs__leetcode | solution/2700-2799/2746.Decremental String Concatenation/Solution.py | {
"start": 0,
"end": 440
} | class ____:
def minimizeConcatenatedLength(self, words: List[str]) -> int:
@cache
def dfs(i: int, a: str, b: str) -> int:
if i >= len(words):
return 0
s = words[i]
x = dfs(i + 1, a, s[-1]) - int(s[0] == b)
y = dfs(i + 1, s[0], b) - int(s[-1] == a)
return len(s) + min(x, y)
return len(words[0]) + dfs(1, words[0][0], words[0][-1])
| Solution |
python | google__jax | tests/shard_map_test.py | {
"start": 177299,
"end": 178134
} | class ____(jtu.JaxTestCase):
@staticmethod
def make_mesh(mesh_shape):
return jtu.create_mesh(tuple(mesh_shape.values()), tuple(mesh_shape))
@parameterized.parameters(
sample(jtu.NUM_GENERATED_CASES.value, sample_smap))
def test_against_ref(self, fun_spec, mesh_shape, in_axes, out_axes, axis_name, args):
fun = fun_spec.fun
mesh = self.make_mesh(mesh_shape)
args = map(jnp.array, args)
with jax.set_mesh(mesh):
fun_ = jax.smap(fun, in_axes=in_axes, out_axes=out_axes,
axis_name=axis_name)
out = jax.jit(fun_)(*args)
fun_ref = smap_ref(fun, in_axes=in_axes, out_axes=out_axes, axis_name=axis_name,
axis_size=mesh_shape[axis_name])
expected = fun_ref(*args)
self.assertAllClose(out, expected, check_dtypes=False)
| SmapSystematicTest |
python | getsentry__sentry | src/sentry/integrations/jira/actions/create_ticket.py | {
"start": 358,
"end": 1544
} | class ____(TicketEventAction):
id = "sentry.integrations.jira.notify_action.JiraCreateTicketAction"
label = "Create a Jira issue in {integration} with these "
ticket_type = "a Jira issue"
link = "https://docs.sentry.io/product/integrations/issue-tracking/jira/#issue-sync"
provider = IntegrationProviderSlug.JIRA.value
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
fix_versions = self.data.get("fixVersions")
if fix_versions and not isinstance(fix_versions, list):
self.data["fixVersions"] = [fix_versions]
def generate_footer(self, rule_url: str) -> str:
return "This ticket was automatically created by Sentry via [{}|{}]".format(
self.rule.label,
absolute_uri(rule_url),
)
def translate_integration(self, integration: RpcIntegration) -> str:
name = integration.metadata.get("domain_name", integration.name)
return name.replace(".atlassian.net", "")
def get_form_instance(self) -> JiraNotifyServiceForm:
return JiraNotifyServiceForm(self.data, integrations=self.get_integrations())
| JiraCreateTicketAction |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 12560,
"end": 13391
} | class ____(nn.Module):
def __init__(self, config: LongT5Config):
super().__init__()
self.wi_0 = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wi_1 = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
self.dropout = nn.Dropout(config.dropout_rate)
self.act = ACT2FN[config.dense_act_fn]
def forward(self, hidden_states):
hidden_gelu = self.act(self.wi_0(hidden_states))
hidden_linear = self.wi_1(hidden_states)
hidden_states = hidden_gelu * hidden_linear
hidden_states = self.dropout(hidden_states)
hidden_states = self.wo(hidden_states)
return hidden_states
# Copied from transformers.models.t5.modeling_t5.T5LayerFF with T5->LongT5
| LongT5DenseGatedActDense |
python | django-extensions__django-extensions | tests/test_management_command.py | {
"start": 1030,
"end": 1545
} | class ____(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwargs)
def emit(self, record):
self.messages[record.levelname.lower()].append(record.getMessage())
def reset(self):
self.messages = {
"debug": [],
"info": [],
"warning": [],
"error": [],
"critical": [],
}
| MockLoggingHandler |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 7599,
"end": 8131
} | class ____:
a: int = attr.ib()
b: int = attr.ib()
attr.asdict(FactoryTest())
attr.asdict(FactoryTest(), retain_collection_types=False)
def accessing_from_attr() -> None:
"""
Use a function to keep the ns clean.
"""
attr.converters.optional
attr.exceptions.FrozenError
attr.filters.include
attr.filters.exclude
attr.setters.frozen
attr.validators.and_
attr.cmp_using
foo = object
if attrs.has(foo) or attr.has(foo):
foo.__attrs_attrs__
@attrs.define(unsafe_hash=True)
| MatchArgs |
python | pytest-dev__pytest | src/_pytest/logging.py | {
"start": 5111,
"end": 11898
} | class ____(logging.PercentStyle):
"""A logging style with special support for multiline messages.
If the message of a record consists of multiple lines, this style
formats the message as if each line were logged separately.
"""
def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None:
super().__init__(fmt)
self._auto_indent = self._get_auto_indent(auto_indent)
@staticmethod
def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int:
"""Determine the current auto indentation setting.
Specify auto indent behavior (on/off/fixed) by passing in
extra={"auto_indent": [value]} to the call to logging.log() or
using a --log-auto-indent [value] command line or the
log_auto_indent [value] config option.
Default behavior is auto-indent off.
Using the string "True" or "on" or the boolean True as the value
turns auto indent on, using the string "False" or "off" or the
boolean False or the int 0 turns it off, and specifying a
positive integer fixes the indentation position to the value
specified.
Any other values for the option are invalid, and will silently be
converted to the default.
:param None|bool|int|str auto_indent_option:
User specified option for indentation from command line, config
or extra kwarg. Accepts int, bool or str. str option accepts the
same range of values as boolean config options, as well as
positive integers represented in str form.
:returns:
Indentation value, which can be
-1 (automatically determine indentation) or
0 (auto-indent turned off) or
>0 (explicitly set indentation position).
"""
if auto_indent_option is None:
return 0
elif isinstance(auto_indent_option, bool):
if auto_indent_option:
return -1
else:
return 0
elif isinstance(auto_indent_option, int):
return int(auto_indent_option)
elif isinstance(auto_indent_option, str):
try:
return int(auto_indent_option)
except ValueError:
pass
try:
if _strtobool(auto_indent_option):
return -1
except ValueError:
return 0
return 0
def format(self, record: logging.LogRecord) -> str:
if "\n" in record.message:
if hasattr(record, "auto_indent"):
# Passed in from the "extra={}" kwarg on the call to logging.log().
auto_indent = self._get_auto_indent(record.auto_indent)
else:
auto_indent = self._auto_indent
if auto_indent:
lines = record.message.splitlines()
formatted = self._fmt % {**record.__dict__, "message": lines[0]}
if auto_indent < 0:
indentation = _remove_ansi_escape_sequences(formatted).find(
lines[0]
)
else:
# Optimizes logging by allowing a fixed indentation.
indentation = auto_indent
lines[0] = formatted
return ("\n" + " " * indentation).join(lines)
return self._fmt % record.__dict__
def get_option_ini(config: Config, *names: str):
for name in names:
ret = config.getoption(name) # 'default' arg won't work as expected
if ret is None:
ret = config.getini(name)
if ret:
return ret
def pytest_addoption(parser: Parser) -> None:
"""Add options to control log capturing."""
group = parser.getgroup("logging")
def add_option_ini(option, dest, default=None, type=None, **kwargs):
parser.addini(
dest, default=default, type=type, help="Default value for " + option
)
group.addoption(option, dest=dest, **kwargs)
add_option_ini(
"--log-level",
dest="log_level",
default=None,
metavar="LEVEL",
help=(
"Level of messages to catch/display."
" Not set by default, so it depends on the root/parent log handler's"
' effective level, where it is "WARNING" by default.'
),
)
add_option_ini(
"--log-format",
dest="log_format",
default=DEFAULT_LOG_FORMAT,
help="Log format used by the logging module",
)
add_option_ini(
"--log-date-format",
dest="log_date_format",
default=DEFAULT_LOG_DATE_FORMAT,
help="Log date format used by the logging module",
)
parser.addini(
"log_cli",
default=False,
type="bool",
help='Enable log display during test run (also known as "live logging")',
)
add_option_ini(
"--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level"
)
add_option_ini(
"--log-cli-format",
dest="log_cli_format",
default=None,
help="Log format used by the logging module",
)
add_option_ini(
"--log-cli-date-format",
dest="log_cli_date_format",
default=None,
help="Log date format used by the logging module",
)
add_option_ini(
"--log-file",
dest="log_file",
default=None,
help="Path to a file when logging will be written to",
)
add_option_ini(
"--log-file-mode",
dest="log_file_mode",
default="w",
choices=["w", "a"],
help="Log file open mode",
)
add_option_ini(
"--log-file-level",
dest="log_file_level",
default=None,
help="Log file logging level",
)
add_option_ini(
"--log-file-format",
dest="log_file_format",
default=None,
help="Log format used by the logging module",
)
add_option_ini(
"--log-file-date-format",
dest="log_file_date_format",
default=None,
help="Log date format used by the logging module",
)
add_option_ini(
"--log-auto-indent",
dest="log_auto_indent",
default=None,
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.",
)
group.addoption(
"--log-disable",
action="append",
default=[],
dest="logger_disable",
help="Disable a logger by name. Can be passed multiple times.",
)
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler)
# Not using @contextmanager for performance reasons.
| PercentStyleMultiline |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 25688,
"end": 27472
} | class ____(FileHandler):
"""A file handler that will check if the file was moved while it was
open. This might happen on POSIX systems if an application like
logrotate moves the logfile over.
Because of different IO concepts on Windows, this handler will not
work on a windows system.
"""
def __init__(
self,
filename,
mode="a",
encoding="utf-8",
level=NOTSET,
format_string=None,
delay=False,
filter=None,
bubble=False,
):
FileHandler.__init__(
self, filename, mode, encoding, level, format_string, delay, filter, bubble
)
if os.name == "nt":
raise RuntimeError("MonitoringFileHandler does not support Windows")
self._query_fd()
def _query_fd(self):
if self.stream is None:
self._last_stat = None, None
else:
try:
st = os.stat(self._filename)
except OSError:
e = sys.exc_info()[1]
if e.errno != errno.ENOENT:
raise
self._last_stat = None, None
else:
self._last_stat = st[stat.ST_DEV], st[stat.ST_INO]
def emit(self, record):
msg = self.format(record)
self.lock.acquire()
try:
last_stat = self._last_stat
self._query_fd()
if last_stat != self._last_stat and self.stream is not None:
self.flush()
self.stream.close()
self.stream = None
self.ensure_stream_is_open()
self.write(self.encode(msg))
self.flush()
self._query_fd()
finally:
self.lock.release()
| MonitoringFileHandler |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 90111,
"end": 90270
} | class ____:
xlDoNotRepeatLabels = 1 # from enum XlPivotFieldRepeatLabels
xlRepeatLabels = 2 # from enum XlPivotFieldRepeatLabels
| PivotFieldRepeatLabels |
python | huggingface__transformers | src/transformers/models/swiftformer/modeling_swiftformer.py | {
"start": 10847,
"end": 11951
} | class ____(GradientCheckpointingLayer):
"""
A Swiftformer stage consisting of a series of `SwiftFormerConvEncoder` blocks and a final
`SwiftFormerEncoderBlock`.
Input: tensor in shape `[batch_size, channels, height, width]`
Output: tensor in shape `[batch_size, channels, height, width]`
"""
def __init__(self, config: SwiftFormerConfig, index: int) -> None:
super().__init__()
layer_depths = config.depths
dim = config.embed_dims[index]
depth = layer_depths[index]
blocks = []
for block_idx in range(depth):
block_dpr = config.drop_path_rate * (block_idx + sum(layer_depths[:index])) / (sum(layer_depths) - 1)
if depth - block_idx <= 1:
blocks.append(SwiftFormerEncoderBlock(config, dim=dim, drop_path=block_dpr))
else:
blocks.append(SwiftFormerConvEncoder(config, dim=dim))
self.blocks = nn.ModuleList(blocks)
def forward(self, input):
for block in self.blocks:
input = block(input)
return input
| SwiftFormerStage |
python | allegroai__clearml | clearml/backend_api/services/v2_23/models.py | {
"start": 117694,
"end": 117931
} | class ____(Response):
"""
Response of models.move endpoint.
"""
_service = "models"
_action = "move"
_version = "2.23"
_schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
| MoveResponse |
python | graphql-python__graphene | graphene/types/tests/test_definition.py | {
"start": 1106,
"end": 1147
} | class ____(Interface):
pass
| MyInterface |
python | tensorflow__tensorflow | tensorflow/compiler/tests/slice_ops_test.py | {
"start": 4579,
"end": 10403
} | class ____(xla_test.XLATestCase):
def test1D(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[10])
with self.test_scope():
o = array_ops.strided_slice(i, [2], [6], [2])
params = {
i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
}
result = o.eval(feed_dict=params)
self.assertAllEqual([2, 4], result)
def test1DDynamic(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[10])
begin = array_ops.placeholder(dtypes.int32, shape=[1])
with self.test_scope():
end = math_ops.add(begin, [1])
o = array_ops.strided_slice(i, begin, end, [1])
params = {
i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
begin: [0]
}
result = o.eval(feed_dict=params)
self.assertAllEqual([0], result)
def test1DNegativeStride(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[10])
with self.test_scope():
o = array_ops.strided_slice(i, [6], [2], [-2])
params = {
i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
}
result = o.eval(feed_dict=params)
self.assertAllEqual([6, 4], result)
def test2DDegenerate(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[2, 3])
with self.test_scope():
o = array_ops.strided_slice(i, [-1, 0], [0, 3])
params = {
i: [[0, 1, 2],
[3, 4, 5]]
}
result = o.eval(feed_dict=params)
self.assertEqual(tensor_shape.TensorShape((0, 3)), result.shape)
def test2DDegenerateNegativeStride(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[2, 3])
with self.test_scope():
o = array_ops.strided_slice(i, [0, 0], [-1, 3], [-1, 1])
params = {
i: [[0, 1, 2],
[3, 4, 5]]
}
result = o.eval(feed_dict=params)
self.assertEqual(tensor_shape.TensorShape((0, 3)), result.shape)
def test2DFullSlice(self):
for dtype in self.numeric_types:
with self.session():
with self.test_scope():
i = array_ops.placeholder(dtype, shape=[2, 4])
begin = array_ops.placeholder(dtypes.int32, shape=[2])
end = math_ops.add(begin, [1, 1])
o = array_ops.strided_slice(i, begin, end, [1, 1])
params = {
i: [[0, 1, 2, 3], [4, 5, 6, 7]],
begin: [1, 1]
}
result = o.eval(feed_dict=params)
self.assertAllEqual([[5]], result)
def test3D(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[3, 3, 10])
with self.test_scope():
o = array_ops.strided_slice(i, [0, 2, 2], [2, 3, 6], [1, 1, 2])
params = {
i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
[5, 3, 1, 7, 9, 2, 4, 6, 8, 0]],
[[5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[8, 7, 6, 5, 4, 3, 2, 1, 8, 7]],
[[7, 5, 7, 5, 7, 5, 7, 5, 7, 5],
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
[9, 8, 7, 9, 8, 7, 9, 8, 7, 9]]]
}
result = o.eval(feed_dict=params)
self.assertAllEqual([[[1, 9]], [[6, 4]]], result)
def test3DNegativeStride(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[3, 4, 10])
with self.test_scope():
o = array_ops.strided_slice(i, [2, 2, 6], [0, 0, 2], [-1, -1, -2])
params = {
i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0],
[5, 3, 1, 7, 9, 2, 4, 6, 8, 0],
[4, 5, 2, 4, 3, 7, 6, 8, 9, 4]],
[[5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
[4, 3, 4, 5, 7, 6, 5, 3, 4, 5],
[8, 7, 6, 5, 4, 3, 2, 1, 8, 7],
[7, 1, 7, 1, 8, 1, 8, 1, 3, 1]],
[[7, 5, 7, 5, 7, 5, 7, 5, 7, 5],
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2],
[9, 8, 7, 9, 8, 7, 9, 8, 7, 9],
[9, 9, 5, 5, 6, 6, 3, 3, 6, 6]]]
}
result = o.eval(feed_dict=params)
self.assertAllEqual([[[9, 8],
[1, 1]],
[[2, 4],
[5, 7]]], result)
# Test shrink_axis_mask. This `strided_slice` call is equivalent to `i[1,:]`.
def testShrinkAxisMask(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[2, 3])
with self.test_scope():
o = array_ops.strided_slice(i, [1, 0], [10, 3], shrink_axis_mask=1)
params = {
i: [[0, 1, 2], [3, 4, 5]],
}
result = o.eval(feed_dict=params)
self.assertAllEqual([3, 4, 5], result)
# Test shrink_axis_mask with the range for the second dimension implicit.
# This `strided_slice` call is equivalent to `i[1]`.
def testShrinkAxisMaskImplicitRange(self):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[2, 3])
with self.test_scope():
o = array_ops.strided_slice(i, [1], [10], shrink_axis_mask=1)
params = {
i: [[0, 1, 2], [3, 4, 5]],
}
result = o.eval(feed_dict=params)
self.assertAllEqual([3, 4, 5], result)
if __name__ == "__main__":
googletest.main()
| StridedSliceTest |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 38644,
"end": 38854
} | class ____(Pix2SkyProjection, QuadCube):
r"""
COBE quadrilateralized spherical cube projection - pixel to sky.
Corresponds to the ``CSC`` projection in FITS WCS.
"""
| Pix2Sky_COBEQuadSphericalCube |
python | huggingface__transformers | src/transformers/models/colqwen2/modeling_colqwen2.py | {
"start": 2812,
"end": 4739
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
The embeddings of the model.
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
"""
loss: Optional[torch.FloatTensor] = None
embeddings: Optional[torch.Tensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
@auto_docstring(
custom_intro="""
Following the ColPali approach, ColQwen2 leverages VLMs to construct efficient multi-vector embeddings directly
from document images (“screenshots”) for document retrieval. The model is trained to maximize the similarity
between these document embeddings and the corresponding query embeddings, using the late interaction method
introduced in ColBERT.
Using ColQwen2 removes the need for potentially complex and brittle layout recognition and OCR pipelines with
a single model that can take into account both the textual and visual content (layout, charts, ...) of a document.
ColQwen2 is part of the ColVision model family, which was introduced with ColPali in the following paper:
[*ColPali: Efficient Document Retrieval with Vision Language Models*](https://huggingface.co/papers/2407.01449).
"""
)
| ColQwen2ForRetrievalOutput |
python | doocs__leetcode | solution/0600-0699/0673.Number of Longest Increasing Subsequence/Solution2.py | {
"start": 0,
"end": 677
} | class ____:
__slots__ = ["n", "c", "d"]
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
self.d = [0] * (n + 1)
def update(self, x, v, cnt):
while x <= self.n:
if self.c[x] < v:
self.c[x] = v
self.d[x] = cnt
elif self.c[x] == v:
self.d[x] += cnt
x += x & -x
def query(self, x):
v = cnt = 0
while x:
if self.c[x] > v:
v = self.c[x]
cnt = self.d[x]
elif self.c[x] == v:
cnt += self.d[x]
x -= x & -x
return v, cnt
| BinaryIndexedTree |
python | bokeh__bokeh | src/bokeh/colors/groups.py | {
"start": 7246,
"end": 7767
} | class ____(ColorGroup):
''' CSS "Red" Color Group as defined by https://www.w3schools.com/colors/colors_groups.asp
.. bokeh-color:: lightsalmon
.. bokeh-color:: salmon
.. bokeh-color:: darksalmon
.. bokeh-color:: lightcoral
.. bokeh-color:: indianred
.. bokeh-color:: crimson
.. bokeh-color:: firebrick
.. bokeh-color:: darkred
.. bokeh-color:: red
'''
_colors = ('LightSalmon', 'Salmon', 'DarkSalmon', 'LightCoral', 'IndianRed', 'Crimson', 'FireBrick', 'DarkRed', 'Red')
| red |
python | getsentry__sentry | src/sentry/workflow_engine/buffer/batch_client.py | {
"start": 1761,
"end": 4508
} | class ____:
"""
Client for interacting with batch processing of delayed workflows.
This is used for managing the listing of projects that need to be processed
"""
_BUFFER_KEY = "workflow_engine_delayed_processing_buffer"
_BUFFER_SHARDS = 8
option = "delayed_workflow.rollout"
def __init__(
self, buf: RedisHashSortedSetBuffer | None = None, buffer_keys: list[str] | None = None
) -> None:
self._buffer = buf or buffer.get_backend()
self._buffer_keys = tuple(buffer_keys or self._get_buffer_keys())
def add_project_ids(self, project_ids: list[int]) -> None:
"""Add project IDs to a random shard for processing."""
sharded_key = random.choice(self._buffer_keys)
self._buffer.push_to_sorted_set(key=sharded_key, value=project_ids)
def get_project_ids(self, min: float, max: float) -> dict[int, list[float]]:
"""Get project IDs within the specified score range from all shards."""
return self._buffer.bulk_get_sorted_set(
self._buffer_keys,
min=min,
max=max,
)
def clear_project_ids(self, min: float, max: float) -> None:
"""Remove project IDs within the specified score range from all shards."""
self._buffer.delete_keys(
self._buffer_keys,
min=min,
max=max,
)
def mark_project_ids_as_processed(
self, project_id_max_timestamps: Mapping[int, float]
) -> list[int]:
"""
Mark project IDs as processed, removing any requests for them at the associated timestamp or earlier.
Returns a list of project IDs that were deleted.
"""
result = self._buffer.conditional_delete_from_sorted_sets(
self._buffer_keys,
list(project_id_max_timestamps.items()),
)
return list(set().union(*result.values()))
@classmethod
def _get_buffer_keys(cls) -> list[str]:
return [
f"{cls._BUFFER_KEY}:{shard}" if shard > 0 else cls._BUFFER_KEY
for shard in range(cls._BUFFER_SHARDS)
]
_COHORT_UPDATES_KEY = "WORKFLOW_ENGINE_COHORT_UPDATES"
def fetch_updates(self) -> CohortUpdates:
return self._buffer.get_parsed_key(
self._COHORT_UPDATES_KEY, CohortUpdates
) or CohortUpdates(values={})
def persist_updates(self, cohort_updates: CohortUpdates) -> None:
self._buffer.put_parsed_key(self._COHORT_UPDATES_KEY, cohort_updates)
def for_project(self, project_id: int) -> ProjectDelayedWorkflowClient:
"""Create a project-specific client for workflow operations."""
return ProjectDelayedWorkflowClient(project_id, self._buffer)
| DelayedWorkflowClient |
python | davidhalter__parso | parso/python/errors.py | {
"start": 23839,
"end": 24520
} | class ____(SyntaxRule):
message = "'return' with value in async generator"
message_async_yield = "'yield' inside async function"
def get_node(self, leaf):
return leaf.parent
def is_issue(self, leaf):
if self._normalizer.context.node.type != 'funcdef':
self.add_issue(self.get_node(leaf), message="'%s' outside function" % leaf.value)
elif self._normalizer.context.is_async_funcdef() \
and any(self._normalizer.context.node.iter_yield_exprs()):
if leaf.value == 'return' and leaf.parent.type == 'return_stmt':
return True
@ErrorFinder.register_rule(type='strings')
| _ReturnAndYieldChecks |
python | huggingface__transformers | src/transformers/models/paligemma/modeling_paligemma.py | {
"start": 1566,
"end": 2117
} | class ____(BaseModelOutputWithPast):
r"""
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
image_hidden_states: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for PaliGemma causal language model (or autoregressive) outputs.
"""
)
| PaligemmaModelOutputWithPast |
python | numba__numba | numba/tests/test_heapq.py | {
"start": 571,
"end": 14226
} | class ____(MemoryLeakMixin):
def setUp(self):
super(_TestHeapq, self).setUp()
self.rnd = np.random.RandomState(42)
def test_heapify_basic_sanity(self):
pyfunc = heapify
cfunc = jit(nopython=True)(pyfunc)
a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
b = self.listimpl(a)
pyfunc(a)
cfunc(b)
self.assertPreciseEqual(a, list(b))
# includes non-finite elements
element_pool = [3.142, -10.0, 5.5, np.nan, -np.inf, np.inf]
# list which may contain duplicate elements
for x in itertools.combinations_with_replacement(element_pool, 6):
a = list(x)
b = self.listimpl(a)
pyfunc(a)
cfunc(b)
self.assertPreciseEqual(a, list(b))
# single element list
for i in range(len(element_pool)):
a = [element_pool[i]]
b = self.listimpl(a)
pyfunc(a)
cfunc(b)
self.assertPreciseEqual(a, list(b))
# elements are tuples
a = [(3, 33), (1, 11), (2, 22)]
b = self.listimpl(a)
pyfunc(a)
cfunc(b)
self.assertPreciseEqual(a, list(b))
def check_invariant(self, heap):
for pos, item in enumerate(heap):
if pos:
parentpos = (pos - 1) >> 1
self.assertTrue(heap[parentpos] <= item)
def test_push_pop(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc_heappush = heappush
cfunc_heappush = jit(nopython=True)(pyfunc_heappush)
pyfunc_heappop = heappop
cfunc_heappop = jit(nopython=True)(pyfunc_heappop)
heap = self.listimpl([-1.0])
data = self.listimpl([-1.0])
self.check_invariant(heap)
for i in range(256):
item = self.rnd.randn(1).item(0)
data.append(item)
cfunc_heappush(heap, item)
self.check_invariant(heap)
results = []
while heap:
item = cfunc_heappop(heap)
self.check_invariant(heap)
results.append(item)
data_sorted = data[:]
data_sorted.sort()
self.assertPreciseEqual(list(data_sorted), results)
self.check_invariant(results)
def test_heapify(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc = heapify
cfunc = jit(nopython=True)(pyfunc)
for size in list(range(1, 30)) + [20000]:
heap = self.listimpl(self.rnd.random_sample(size))
cfunc(heap)
self.check_invariant(heap)
def test_heapify_exceptions(self):
pyfunc = heapify
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc((1, 5, 4))
msg = 'heap argument must be a list'
self.assertIn(msg, str(e.exception))
with self.assertTypingError() as e:
cfunc(self.listimpl([1 + 1j, 2 - 3j]))
msg = ("'<' not supported between instances "
"of 'complex' and 'complex'")
self.assertIn(msg, str(e.exception))
def test_heappop_basic_sanity(self):
pyfunc = heappop
cfunc = jit(nopython=True)(pyfunc)
def a_variations():
yield [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
yield [(3, 33), (1, 111), (2, 2222)]
yield np.full(5, fill_value=np.nan).tolist()
yield np.linspace(-10, -5, 100).tolist()
for a in a_variations():
heapify(a)
b = self.listimpl(a)
for i in range(len(a)):
val_py = pyfunc(a)
val_c = cfunc(b)
self.assertPreciseEqual(a, list(b))
self.assertPreciseEqual(val_py, val_c)
def test_heappop_exceptions(self):
pyfunc = heappop
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc((1, 5, 4))
msg = 'heap argument must be a list'
self.assertIn(msg, str(e.exception))
def iterables(self):
yield self.listimpl([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
a = np.linspace(-10, 2, 23)
yield self.listimpl(a)
yield self.listimpl(a[::-1])
self.rnd.shuffle(a)
yield self.listimpl(a)
def test_heappush_basic(self):
pyfunc_push = heappush
cfunc_push = jit(nopython=True)(pyfunc_push)
pyfunc_pop = heappop
cfunc_pop = jit(nopython=True)(pyfunc_pop)
for iterable in self.iterables():
expected = sorted(iterable)
heap = self.listimpl([iterable.pop(0)]) # must initialise heap
for value in iterable:
cfunc_push(heap, value)
got = [cfunc_pop(heap) for _ in range(len(heap))]
self.assertPreciseEqual(expected, got)
def test_heappush_exceptions(self):
pyfunc = heappush
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc((1, 5, 4), 6)
msg = 'heap argument must be a list'
self.assertIn(msg, str(e.exception))
with self.assertTypingError() as e:
cfunc(self.listimpl([1, 5, 4]), 6.0)
msg = 'heap type must be the same as item type'
self.assertIn(msg, str(e.exception))
def test_nsmallest_basic(self):
pyfunc = nsmallest
cfunc = jit(nopython=True)(pyfunc)
for iterable in self.iterables():
for n in range(-5, len(iterable) + 3):
expected = pyfunc(1, iterable)
got = cfunc(1, iterable)
self.assertPreciseEqual(expected, got)
# n is boolean
out = cfunc(False, self.listimpl([3, 2, 1]))
self.assertPreciseEqual(out, [])
out = cfunc(True, self.listimpl([3, 2, 1]))
self.assertPreciseEqual(out, [1])
# iterable is not a list
out = cfunc(2, (6, 5, 4, 3, 2, 1))
self.assertPreciseEqual(out, [1, 2])
out = cfunc(3, np.arange(6))
self.assertPreciseEqual(out, [0, 1, 2])
def test_nlargest_basic(self):
pyfunc = nlargest
cfunc = jit(nopython=True)(pyfunc)
for iterable in self.iterables():
for n in range(-5, len(iterable) + 3):
expected = pyfunc(1, iterable)
got = cfunc(1, iterable)
self.assertPreciseEqual(expected, got)
# n is boolean
out = cfunc(False, self.listimpl([3, 2, 1]))
self.assertPreciseEqual(out, [])
out = cfunc(True, self.listimpl([3, 2, 1]))
self.assertPreciseEqual(out, [3])
# iterable is not a list
out = cfunc(2, (6, 5, 4, 3, 2, 1))
self.assertPreciseEqual(out, [6, 5])
out = cfunc(3, np.arange(6))
self.assertPreciseEqual(out, [5, 4, 3])
def _assert_typing_error(self, cfunc):
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc(2.2, self.listimpl([3, 2, 1]))
msg = "First argument 'n' must be an integer"
self.assertIn(msg, str(e.exception))
with self.assertTypingError() as e:
cfunc(2, 100)
msg = "Second argument 'iterable' must be iterable"
self.assertIn(msg, str(e.exception))
def test_nsmallest_exceptions(self):
pyfunc = nsmallest
cfunc = jit(nopython=True)(pyfunc)
self._assert_typing_error(cfunc)
def test_nlargest_exceptions(self):
pyfunc = nlargest
cfunc = jit(nopython=True)(pyfunc)
self._assert_typing_error(cfunc)
def test_heapreplace_basic(self):
pyfunc = heapreplace
cfunc = jit(nopython=True)(pyfunc)
a = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(a)
b = self.listimpl(a)
for item in [-4, 4, 14]:
pyfunc(a, item)
cfunc(b, item)
self.assertPreciseEqual(a, list(b))
a = np.linspace(-3, 13, 20)
a[4] = np.nan
a[-1] = np.inf
a = a.tolist()
heapify(a)
b = self.listimpl(a)
for item in [-4.0, 3.142, -np.inf, np.inf]:
pyfunc(a, item)
cfunc(b, item)
self.assertPreciseEqual(a, list(b))
def test_heapreplace_exceptions(self):
pyfunc = heapreplace
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc((1, 5, 4), -1)
msg = 'heap argument must be a list'
self.assertIn(msg, str(e.exception))
with self.assertTypingError() as e:
cfunc(self.listimpl([1, 5, 4]), -1.0)
msg = 'heap type must be the same as item type'
self.assertIn(msg, str(e.exception))
def heapiter(self, heap):
try:
while 1:
yield heappop(heap)
except IndexError:
pass
def test_nbest(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
cfunc_heapify = jit(nopython=True)(heapify)
cfunc_heapreplace = jit(nopython=True)(heapreplace)
data = self.rnd.choice(range(2000), 1000).tolist()
heap = self.listimpl(data[:10])
cfunc_heapify(heap)
for item in data[10:]:
if item > heap[0]:
cfunc_heapreplace(heap, item)
self.assertPreciseEqual(list(self.heapiter(list(heap))),
sorted(data)[-10:])
def test_heapsort(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
cfunc_heapify = jit(nopython=True)(heapify)
cfunc_heappush = jit(nopython=True)(heappush)
cfunc_heappop = jit(nopython=True)(heappop)
for trial in range(100):
# Ensure consistency of typing, use float64 as it's double
# everywhere
values = np.arange(5, dtype=np.float64)
data = self.listimpl(self.rnd.choice(values, 10))
if trial & 1:
heap = data[:]
cfunc_heapify(heap)
else:
heap = self.listimpl([data[0]])
for item in data[1:]:
cfunc_heappush(heap, item)
heap_sorted = [cfunc_heappop(heap) for _ in range(10)]
self.assertPreciseEqual(heap_sorted, sorted(data))
def test_nsmallest(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc = nsmallest
cfunc = jit(nopython=True)(pyfunc)
data = self.listimpl(self.rnd.choice(range(2000), 1000))
for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
self.assertPreciseEqual(list(cfunc(n, data)), sorted(data)[:n])
def test_nlargest(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc = nlargest
cfunc = jit(nopython=True)(pyfunc)
data = self.listimpl(self.rnd.choice(range(2000), 1000))
for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
self.assertPreciseEqual(list(cfunc(n, data)),
sorted(data, reverse=True)[:n])
def test_nbest_with_pushpop(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc_heappushpop = heappushpop
cfunc_heappushpop = jit(nopython=True)(pyfunc_heappushpop)
pyfunc_heapify = heapify
cfunc_heapify = jit(nopython=True)(pyfunc_heapify)
# Ensure consistency of typing, use float64 as it's double everywhere
values = np.arange(2000, dtype=np.float64)
data = self.listimpl(self.rnd.choice(values, 1000))
heap = data[:10]
cfunc_heapify(heap)
for item in data[10:]:
cfunc_heappushpop(heap, item)
self.assertPreciseEqual(list(self.heapiter(list(heap))),
sorted(data)[-10:])
def test_heappushpop(self):
# inspired by
# https://github.com/python/cpython/blob/e42b7051/Lib/test/test_heapq.py
pyfunc = heappushpop
cfunc = jit(nopython=True)(pyfunc)
h = self.listimpl([1.0])
x = cfunc(h, 10.0)
self.assertPreciseEqual((list(h), x), ([10.0], 1.0))
self.assertPreciseEqual(type(h[0]), float)
self.assertPreciseEqual(type(x), float)
h = self.listimpl([10])
x = cfunc(h, 9)
self.assertPreciseEqual((list(h), x), ([10], 9))
h = self.listimpl([10])
x = cfunc(h, 11)
self.assertPreciseEqual((list(h), x), ([11], 10))
def test_heappushpop_exceptions(self):
pyfunc = heappushpop
cfunc = jit(nopython=True)(pyfunc)
# Exceptions leak references
self.disable_leak_check()
with self.assertTypingError() as e:
cfunc((1, 5, 4), -1)
msg = 'heap argument must be a list'
self.assertIn(msg, str(e.exception))
with self.assertTypingError() as e:
cfunc(self.listimpl([1, 5, 4]), False)
msg = 'heap type must be the same as item type'
self.assertIn(msg, str(e.exception))
| _TestHeapq |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 47198,
"end": 49825
} | class ____(List):
"""A vertical list of boxes."""
def __init__(self, elements: T.Sequence[Node], h: float = 0.0,
m: T.Literal['additional', 'exactly'] = 'additional'):
super().__init__(elements)
self.vpack(h=h, m=m)
def vpack(self, h: float = 0.0,
m: T.Literal['additional', 'exactly'] = 'additional',
l: float = np.inf) -> None:
"""
Compute the dimensions of the resulting boxes, and to adjust the glue
if one of those dimensions is pre-specified.
Parameters
----------
h : float, default: 0
A height.
m : {'exactly', 'additional'}, default: 'additional'
Whether to produce a box whose height is 'exactly' *h*; or a box
with the natural height of the contents, plus *h* ('additional').
l : float, default: np.inf
The maximum height.
Notes
-----
The defaults produce a box with the natural height of the contents.
"""
# I don't know why these get reset in TeX. Shift_amount is pretty
# much useless if we do.
# self.shift_amount = 0.
w = 0.
d = 0.
x = 0.
total_stretch = [0.] * 4
total_shrink = [0.] * 4
for p in self.children:
if isinstance(p, Box):
x += d + p.height
d = p.depth
if not np.isinf(p.width):
s = getattr(p, 'shift_amount', 0.)
w = max(w, p.width + s)
elif isinstance(p, Glue):
x += d
d = 0.
glue_spec = p.glue_spec
x += glue_spec.width
total_stretch[glue_spec.stretch_order] += glue_spec.stretch
total_shrink[glue_spec.shrink_order] += glue_spec.shrink
elif isinstance(p, Kern):
x += d + p.width
d = 0.
elif isinstance(p, Char):
raise RuntimeError(
"Internal mathtext error: Char node found in Vlist")
self.width = w
if d > l:
x += d - l
self.depth = l
else:
self.depth = d
if m == 'additional':
h += x
self.height = h
x = h - x
if x == 0:
self.glue_sign = 0
self.glue_order = 0
self.glue_ratio = 0.
return
if x > 0.:
self._set_glue(x, 1, total_stretch, "Overful")
else:
self._set_glue(x, -1, total_shrink, "Underful")
| Vlist |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar10.py | {
"start": 315,
"end": 1371
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "bar", "subtype": "percent_stacked"})
chart.axis_ids = [40274560, 40295040]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series({"values": "=Sheet1!$A$1:$A$5"})
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_datacatalog.py | {
"start": 21085,
"end": 22396
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.datacatalog.CloudDataCatalogHook")
def test_assert_valid_hook_call(self, mock_hook) -> None:
with pytest.warns(AirflowProviderDeprecationWarning):
task = CloudDataCatalogDeleteTagTemplateOperator(
task_id="task_id",
location=TEST_LOCATION,
tag_template=TEST_TAG_TEMPLATE_ID,
force=TEST_FORCE,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
task.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.delete_tag_template.assert_called_once_with(
location=TEST_LOCATION,
tag_template=TEST_TAG_TEMPLATE_ID,
force=TEST_FORCE,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestCloudDataCatalogDeleteTagTemplateOperator |
python | ray-project__ray | python/ray/_private/telemetry/open_telemetry_metric_recorder.py | {
"start": 472,
"end": 10305
} | class ____:
"""
A class to record OpenTelemetry metrics. This is the main entry point for exporting
all ray telemetries to Prometheus server.
It uses OpenTelemetry's Prometheus exporter to export metrics.
"""
_metrics_initialized = False
_metrics_initialized_lock = threading.Lock()
def __init__(self):
self._lock = threading.Lock()
self._registered_instruments = {}
self._observations_by_name = defaultdict(dict)
self._histogram_bucket_midpoints = defaultdict(list)
self._init_metrics()
self.meter = metrics.get_meter(__name__)
def _init_metrics(self):
# Initialize the global metrics provider and meter. We only do this once on
# the first initialization of the class, because re-setting the meter provider
# can result in loss of metrics.
with self._metrics_initialized_lock:
if self._metrics_initialized:
return
prometheus_reader = PrometheusMetricReader()
provider = MeterProvider(metric_readers=[prometheus_reader])
metrics.set_meter_provider(provider)
self._metrics_initialized = True
def register_gauge_metric(self, name: str, description: str) -> None:
with self._lock:
if name in self._registered_instruments:
# Gauge with the same name is already registered.
return
# Register ObservableGauge with a dynamic callback. Callbacks are special
# features in OpenTelemetry that allow you to provide a function that will
# compute the telemetry at collection time.
def callback(options):
# Take snapshot of current observations.
with self._lock:
observations = self._observations_by_name[name]
# Clear the observations to avoid emitting dead observations.
self._observations_by_name[name] = {}
# Drop high cardinality from tag_set and sum up the value for
# same tag set after dropping
aggregated_observations = defaultdict(float)
high_cardinality_labels = (
MetricCardinality.get_high_cardinality_labels_to_drop(name)
)
for tag_set, val in observations.items():
# Convert frozenset back to dict
tags_dict = dict(tag_set)
# Filter out high cardinality labels
filtered_tags = {
k: v
for k, v in tags_dict.items()
if k not in high_cardinality_labels
}
# Create a key for aggregation
filtered_key = frozenset(filtered_tags.items())
# Sum up values for the same filtered tag set
aggregated_observations[filtered_key] += val
return [
Observation(val, attributes=dict(tag_set))
for tag_set, val in aggregated_observations.items()
]
instrument = self.meter.create_observable_gauge(
name=f"{NAMESPACE}_{name}",
description=description,
unit="1",
callbacks=[callback],
)
self._registered_instruments[name] = instrument
self._observations_by_name[name] = {}
def register_counter_metric(self, name: str, description: str) -> None:
"""
Register a counter metric with the given name and description.
"""
with self._lock:
if name in self._registered_instruments:
# Counter with the same name is already registered. This is a common
# case when metrics are exported from multiple Ray components (e.g.,
# raylet, worker, etc.) running in the same node. Since each component
# may export metrics with the same name, the same metric might be
# registered multiple times.
return
instrument = self.meter.create_counter(
name=f"{NAMESPACE}_{name}",
description=description,
unit="1",
)
self._registered_instruments[name] = instrument
def register_sum_metric(self, name: str, description: str) -> None:
"""
Register a sum metric with the given name and description.
"""
with self._lock:
if name in self._registered_instruments:
# Sum with the same name is already registered. This is a common
# case when metrics are exported from multiple Ray components (e.g.,
# raylet, worker, etc.) running in the same node. Since each component
# may export metrics with the same name, the same metric might be
# registered multiple times.
return
instrument = self.meter.create_up_down_counter(
name=f"{NAMESPACE}_{name}",
description=description,
unit="1",
)
self._registered_instruments[name] = instrument
def register_histogram_metric(
self, name: str, description: str, buckets: List[float]
) -> None:
"""
Register a histogram metric with the given name and description.
"""
with self._lock:
if name in self._registered_instruments:
# Histogram with the same name is already registered. This is a common
# case when metrics are exported from multiple Ray components (e.g.,
# raylet, worker, etc.) running in the same node. Since each component
# may export metrics with the same name, the same metric might be
# registered multiple times.
return
instrument = self.meter.create_histogram(
name=f"{NAMESPACE}_{name}",
description=description,
unit="1",
explicit_bucket_boundaries_advisory=buckets,
)
self._registered_instruments[name] = instrument
# calculate the bucket midpoints; this is used for converting histogram
# internal representation to approximated histogram data points.
for i in range(len(buckets)):
if i == 0:
lower_bound = 0.0 if buckets[0] > 0 else buckets[0] * 2.0
self._histogram_bucket_midpoints[name].append(
(lower_bound + buckets[0]) / 2.0
)
else:
self._histogram_bucket_midpoints[name].append(
(buckets[i] + buckets[i - 1]) / 2.0
)
# Approximated mid point for Inf+ bucket. Inf+ bucket is an implicit bucket
# that is not part of buckets.
self._histogram_bucket_midpoints[name].append(
1.0 if buckets[-1] <= 0 else buckets[-1] * 2.0
)
def get_histogram_bucket_midpoints(self, name: str) -> List[float]:
"""
Get the bucket midpoints for a histogram metric with the given name.
"""
return self._histogram_bucket_midpoints[name]
def set_metric_value(self, name: str, tags: dict, value: float):
"""
Set the value of a metric with the given name and tags. If the metric is not
registered, it lazily records the value for observable metrics or is a no-op for
synchronous metrics.
"""
with self._lock:
if self._observations_by_name.get(name) is not None:
# Set the value of an observable metric with the given name and tags. It
# lazily records the metric value by storing it in a dictionary until
# the value actually gets exported by OpenTelemetry.
self._observations_by_name[name][frozenset(tags.items())] = value
else:
instrument = self._registered_instruments.get(name)
tags = {
k: v
for k, v in tags.items()
if k
not in MetricCardinality.get_high_cardinality_labels_to_drop(name)
}
if isinstance(instrument, metrics.Counter):
instrument.add(value, attributes=tags)
elif isinstance(instrument, metrics.UpDownCounter):
instrument.add(value, attributes=tags)
elif isinstance(instrument, metrics.Histogram):
instrument.record(value, attributes=tags)
else:
logger.warning(
f"Unsupported synchronous instrument type for metric: {name}."
)
def record_and_export(self, records: List[Record], global_tags=None):
"""
Record a list of telemetry records and export them to Prometheus.
"""
global_tags = global_tags or {}
for record in records:
gauge = record.gauge
value = record.value
tags = {**record.tags, **global_tags}
try:
self.register_gauge_metric(gauge.name, gauge.description or "")
self.set_metric_value(gauge.name, tags, value)
except Exception as e:
logger.error(
f"Failed to record metric {gauge.name} with value {value} with tags {tags!r} and global tags {global_tags!r} due to: {e!r}"
)
| OpenTelemetryMetricRecorder |
python | tensorflow__tensorflow | tensorflow/python/distribute/strategy_common_test.py | {
"start": 11237,
"end": 17105
} | class ____(test.TestCase, parameterized.TestCase):
def testDense(self, strategy, tf_function):
if (strategy_test_lib.is_tpu_strategy(strategy) and
tf_function is combinations.no_tf_function):
self.skipTest('Skip TPUStrategy + eager combination.')
@tf_function
def fn():
def replica_fn():
value = array_ops.identity(1.0)
reduced = strategy.extended._replica_ctx_all_reduce(
reduce_util.ReduceOp.SUM, value)
return reduced
return strategy.experimental_local_results(strategy.run(replica_fn))
got = fn()[0]
self.assertEqual(got, 1.0 * strategy.num_replicas_in_sync)
def testSparse(self, strategy, tf_function):
if tf_function is combinations.no_tf_function:
self.skipTest('Skip IndexedSlices + eager combination.')
@tf_function
def fn():
def replica_fn():
value = indexed_slices.IndexedSlices(
values=array_ops.identity([[1.0]]),
indices=array_ops.identity([0]),
dense_shape=array_ops.identity([5, 1]))
reduced = strategy.extended._replica_ctx_all_reduce(
reduce_util.ReduceOp.SUM, value)
return reduced
return strategy.experimental_local_results(strategy.run(replica_fn))
got = fn()[0]
expect = indexed_slices.IndexedSlices(
values=array_ops.identity([[1.0 * strategy.num_replicas_in_sync]]),
indices=array_ops.identity([0]),
dense_shape=array_ops.identity([5, 1]))
self.assertAllEqual(
ops.convert_to_tensor(got), ops.convert_to_tensor(expect))
def testNestedInput(self, strategy, tf_function):
if tf_function is combinations.no_tf_function:
self.skipTest('Skip IndexedSlices + eager combination.')
@tf_function
def fn():
def replica_fn():
value = (array_ops.identity(1.0),
indexed_slices.IndexedSlices(
values=array_ops.identity([[1.0]]),
indices=array_ops.identity([0]),
dense_shape=array_ops.identity([5, 1])),
array_ops.identity(2.0),
indexed_slices.IndexedSlices(
values=array_ops.identity([[2.0]]),
indices=array_ops.identity([1]),
dense_shape=array_ops.identity([5, 1])))
reduced = strategy.extended._replica_ctx_all_reduce(
reduce_util.ReduceOp.SUM, value)
return reduced
return strategy.experimental_local_results(strategy.run(replica_fn))
got = fn()[0]
expect = (1.0 * strategy.num_replicas_in_sync,
indexed_slices.IndexedSlices(
values=array_ops.identity(
[[1.0 * strategy.num_replicas_in_sync]]),
indices=array_ops.identity([0]),
dense_shape=array_ops.identity([5, 1])),
2.0 * strategy.num_replicas_in_sync,
indexed_slices.IndexedSlices(
values=array_ops.identity(
[[2.0 * strategy.num_replicas_in_sync]]),
indices=array_ops.identity([1]),
dense_shape=array_ops.identity([5, 1])))
self.assertAllClose(
nest.map_structure(ops.convert_to_tensor, got),
nest.map_structure(ops.convert_to_tensor, expect))
def testSyncOnReadVariableInput(self, strategy, tf_function):
if (not strategy_test_lib.is_mirrored_strategy(strategy) and
not strategy_test_lib.is_multi_worker_mirrored_strategy(strategy) and
not strategy_test_lib.is_tpu_strategy(strategy)):
self.skipTest('Skip strategies not using SyncOnReadVariables.')
if (strategy_test_lib.is_tpu_strategy(strategy) and
tf_function is combinations.no_tf_function):
self.skipTest('Skip TPUStrategy + eager combination.')
if (strategy_test_lib.is_multi_worker_mirrored_strategy(strategy) and
tf_function is combinations.tf_function):
self.skipTest('Skip MWMS + graph combination until b/228512201 is fixed.')
with strategy.scope():
var = variables.Variable(
0.0,
synchronization=variables.VariableSynchronization.ON_READ,
aggregation=variables.VariableAggregation.ONLY_FIRST_REPLICA)
@tf_function
def replica_fn():
replica_context = distribute_lib.get_replica_context()
replica_id = replica_context.replica_id_in_sync_group
var.assign(math_ops.cast(replica_id, dtype=float) * 3.0)
return replica_context.all_reduce(reduce_util.ReduceOp.SUM, var)
if strategy_test_lib.is_multi_worker_mirrored_strategy(strategy):
client_local_replica_num = strategy.extended._num_devices_per_worker
else:
client_local_replica_num = strategy.num_replicas_in_sync
workers_num = strategy.num_replicas_in_sync
expected_sum = sum(range(workers_num)) * 3.0
# Expand the values on each replica if multiple devices are used; otherwise
# simple read the value of the Tensor.
result = strategy.run(replica_fn)
if hasattr(result, 'values'):
result = result.values
result = nest.flatten(result)
# Iterate through all replicas and verify the reduce sum result.
for i in range(client_local_replica_num):
self.assertEqual(result[i].numpy(), expected_sum)
@combinations.generate(
combinations.combine(
strategy=[
strategy_combinations.multi_worker_mirrored_2x1_cpu,
strategy_combinations.multi_worker_mirrored_2x1_gpu,
strategy_combinations.multi_worker_mirrored_2x2_gpu,
strategy_combinations.multi_worker_mirrored_2x2_gpu_no_merge_call,
strategy_combinations.tpu_strategy,
] + strategy_combinations.strategies_minus_tpu,
tf_function=[combinations.tf_function, combinations.no_tf_function],
mode=['eager']))
| ReplicaCtxAllReduceTest |
python | joke2k__faker | faker/providers/currency/de/__init__.py | {
"start": 100,
"end": 6465
} | class ____(CurrencyProvider):
# source: https://www.laenderdaten.info/waehrungen/
currencies: ElementsType[Tuple[str, str]] = (
("AED", "Arabische Dirham"),
("AFN", "Afghani"),
("ALL", "Albanische Lek"),
("AMD", "Armenische Dram"),
("ANG", "Antillen Gulden"),
("AOA", "Angolanische Kwanza"),
("ARS", "Argentinische Peso"),
("AUD", "Australische Dollar"),
("AWG", "Aruba Florin"),
("AZN", "Aserbaidschanische Manat"),
("BAM", "Konvertible Mark"),
("BBD", "Barbados Dollar"),
("BDT", "Bangladeschische Taka"),
("BGN", "Bulgarische Lew"),
("BHD", "Bahrainische Dinar"),
("BIF", "Burundische Franc"),
("BMD", "Bermudische Dollar"),
("BND", "Brunei Dollar"),
("BOB", "Boliviano"),
("BRL", "Brasilianische Real"),
("BSD", "Bahamas Dollar"),
("BTN", "Bhutanisches Ngultrum"),
("BWP", "Botswanische Pula"),
("BYR", "Belarussische Rubel"),
("BZD", "Belize Dollar"),
("CAD", "Kanadische Dollar"),
("CDF", "Kongolesische Franc"),
("CHF", "Schweizer Franken"),
("CLP", "Chilenische Peso"),
("CNY", "Renminbi Yuán"),
("COP", "Kolumbische Peso"),
("CRC", "Costa-Rica Colón"),
("CUC", "Cuba Peso Convertible"),
("CUP", "Kubanische Peso"),
("CVE", "Cap Verdische Escudo"),
("CZK", "Tschechische Krone"),
("DJF", "Dschibuti Franc"),
("DKK", "Dänische Krone"),
("DOP", "Dominikanische Peso"),
("DZD", "Algerische Dinar"),
("EGP", "Ägyptische Pfund"),
("ERN", "Eritreische Nakfa"),
("ETB", "Äthiopische Birr"),
("EUR", "Euro"),
("FJD", "Fidschi Dollar"),
("FKP", "Falkländische Pfund"),
("GBP", "Sterling Pfund"),
("GEL", "Georgische Lari"),
("GGP", "Guernsey Pfund"),
("GHS", "Ghanaische Cedi"),
("GIP", "Gibraltar Pfund"),
("GMD", "Gambische Dalasi"),
("GNF", "Guinea Franc"),
("GTQ", "Guatemaltekischer Quetzal"),
("GYD", "Guyana Dollar"),
("HKD", "Hongkong Dollar"),
("HNL", "Honduranische Lempira"),
("HRK", "Kroatische Kuna"),
("HTG", "Haitianische Gourde"),
("HUF", "Ungarische Forint"),
("IDR", "Indonesische Rupiah"),
("ILS", "Israelische Schekel"),
("NIS", "Israelische Schekel"),
("IMP", "Isle-of-Man Pfund"),
("INR", "Indische Rupie"),
("IQD", "Irakische Dinar"),
("IRR", "Iranische Rial"),
("ISK", "Isländische Krone"),
("JEP", "Jersey Pfund"),
("JMD", "Jamaikanische Dollar"),
("JOD", "Jordanische Dinar"),
("JPY", "Japanische Yen"),
("KES", "Kenianische Schilling"),
("KGS", "Kirgisische Som"),
("KHR", "Kambodschanische Riel"),
("KMF", "Komorische Franc"),
("KPW", "Nordkoreanische Won"),
("KRW", "Südkoreanische Won"),
("KWD", "Kuwaitische Dinar"),
("KYD", "Cayman Dollar"),
("KZT", "Kasachische Tenge"),
("LAK", "Laotische Kip"),
("LBP", "Libanesische Pfund"),
("LKR", "Sri Lanka Rupie"),
("LRD", "Liberianische Dollar"),
("LSL", "Lesothische Loti"),
("LYD", "Libysche Dinar"),
("MAD", "Marokkanische Dirham"),
("MDL", "Moldauische Leu"),
("MGA", "Madagassische Ariary"),
("MKD", "Mazedonische Denar"),
("MMK", "Burmesische Kyat"),
("MNT", "Mongolische Tögrög"),
("MOP", "Macau Pataca"),
("MRO", "Mauretanische Ouguiya"),
("MUR", "Mauritius Rupie"),
("MVR", "Maledivische Rufiyaa"),
("MWK", "Malawische Kwacha"),
("MXN", "Mexikanische Peso"),
("MYR", "Malaysische Ringgit"),
("MZN", "Mosambikanische Metical"),
("NAD", "Namibische Dollar"),
("NGN", "Nigerianische Naira"),
("NIO", "Nicaraguanische Córdoba Oro"),
("NOK", "Norwegische Krone"),
("NPR", "Nepalesische Rupie"),
("NZD", "Neuseeländische Dollar"),
("OMR", "Omanische Rial"),
("PAB", "Panamaische Balboa"),
("PEN", "Peruanische Sol"),
("PGK", "Papua-neuguineische Kina"),
("PHP", "Philippinische Peso"),
("PKR", "Pakistanische Rupie"),
("PLN", "Polnische Złoty"),
("PYG", "Paraguayische Guaraní"),
("QAR", "Qatar Riyal"),
("RON", "Rumänische Leu"),
("RSD", "Serbische Dinar"),
("RUB", "Russische Rubel"),
("RWF", "Ruandische Franc"),
("SAR", "Saudische Riyal"),
("SBD", "Salomonische Dollar"),
("SCR", "Seychellen Rupie"),
("SDG", "Sudanesische Pfund"),
("SEK", "Schwedische Krone"),
("SGD", "Singapur Dollar"),
("SHP", "St.-Helena Pfund"),
("SLL", "Sierra-leonische Leone"),
("SOS", "Somalische Schilling"),
("SPL", "Seborga Luigini"),
("SRD", "Surinamische Dollar"),
("STD", "São-toméische Dobra"),
("SVC", "El-Salvador-Colón"),
("SYP", "Syrische Pfund"),
("SZL", "Swazi Lilangeni"),
("THB", "Thailändische Baht"),
("TJS", "Tadschikische Somoni"),
("TMT", "Turkmenische Manat"),
("TND", "Tunesische Dinar"),
("TOP", "Tongaische Pa'anga"),
("TRY", "Türkische Lira"),
("TTD", "Trinidad und Tobago Dollar"),
("TVD", "Tuvalu Dollar"),
("TWD", "Neu Taiwanesische Dollar"),
("TZS", "Tansanische Schilling"),
("UAH", "Ukrainische Hrywnja"),
("UGX", "Ugandische Schilling"),
("USD", "Amerikanische Dollar"),
("UYU", "Uruguayische Peso"),
("UZS", "Uzbekische So'm"),
("VEF", "Venezuelanische Bolívar"),
("VND", "Vietnamesischer Dong"),
("VUV", "Vanuatuische Vatu"),
("WST", "Samoanische Tala"),
("XAF", "Zentralafrikanische CFA-Franc"),
("XCD", "Ostkaribische Dollar"),
("XDR", "Sonderziehungsrecht"),
("XOF", "Westafrikanische CFA-Franc"),
("XPF", "Pazifische Franc"),
("YER", "Jemenitische Rial"),
("ZAR", "Südafrikanische Rand"),
("ZMW", "Sambische Kwacha"),
("ZWD", "Simbabwe Dollar"),
)
| Provider |
python | getsentry__sentry | src/sentry/tasks/assemble.py | {
"start": 2356,
"end": 10550
} | class ____(NamedTuple):
# File object stored in the database.
bundle: File
# Temporary in-memory object representing the file used for efficiency.
bundle_temp_file: IO
def delete_bundle(self):
self.bundle.delete()
self.bundle_temp_file.close()
@sentry_sdk.tracing.trace
def assemble_file(task, org_or_project, name, checksum, chunks, file_type) -> AssembleResult | None:
"""
Verifies and assembles a file model from chunks.
This downloads all chunks from blob store to verify their integrity and
associates them with a created file model. Additionally, it assembles the
full file in a temporary location and verifies the complete content hash.
Returns a tuple ``(File, TempFile)`` on success, or ``None`` on error.
"""
from sentry.models.files.fileblob import FileBlob
from sentry.models.files.utils import AssembleChecksumMismatch
if isinstance(org_or_project, Project):
organization = org_or_project.organization
else:
organization = org_or_project
# Load all FileBlobs from db since we can be sure here we already own all chunks need to build the file.
#
# To guarantee that the blobs are owned by the org which is building this file, we check the ownership when checking
# the blobs.
file_blobs = FileBlob.objects.filter(
checksum__in=chunks, fileblobowner__organization_id=organization.id
).values_list("id", "checksum", "size")
# Reject all files that exceed the maximum allowed size for this organization.
file_size = sum(size for _, _, size in file_blobs if size is not None)
if file_size > MAX_FILE_SIZE:
set_assemble_status(
task,
org_or_project.id,
checksum,
ChunkFileState.ERROR,
detail=f"File {name} exceeds maximum size ({file_size} > {MAX_FILE_SIZE})",
)
return None
# Sanity check. In case not all blobs exist at this point we have a race condition.
if {checksum for _, checksum, _ in file_blobs} != set(chunks):
# Most likely a previous check to `find_missing_chunks` or similar
# reported a chunk exists by its checksum, but now it does not
# exist anymore
logger.error(
"Not all chunks are available for assembly; they may have been removed or are not associated with the organization."
)
set_assemble_status(
task,
org_or_project.id,
checksum,
ChunkFileState.ERROR,
detail="Not all chunks available for assembling",
)
return None
# Ensure blobs are in the order and duplication in which they were
# transmitted. Otherwise, we would assemble the file in the wrong order.
ids_by_checksum = {chks: id for id, chks, _ in file_blobs}
file_blob_ids = [ids_by_checksum[c] for c in chunks]
file = File.objects.create(name=name, checksum=checksum, type=file_type)
try:
temp_file = file.assemble_from_file_blob_ids(file_blob_ids, checksum)
except AssembleChecksumMismatch:
file.delete()
set_assemble_status(
task,
org_or_project.id,
checksum,
ChunkFileState.ERROR,
detail="Reported checksum mismatch",
)
return None
return AssembleResult(bundle=file, bundle_temp_file=temp_file)
def _get_cache_key(task, scope, checksum):
"""Computes the cache key for assemble status.
``task`` must be one of the ``AssembleTask`` values. The scope can be the
identifier of any model, such as the organization or project that this task
is performed under.
``checksum`` should be the SHA1 hash of the main file that is being
assembled.
"""
return (
"assemble-status:%s"
% hashlib.sha1(
b"%s|%s|%s"
% (
str(scope).encode("ascii"),
checksum.encode("ascii"),
str(task).encode(),
)
).hexdigest()
)
def _get_redis_cluster_for_assemble() -> RedisCluster:
cluster_key = settings.SENTRY_ASSEMBLE_CLUSTER
return redis.redis_clusters.get(cluster_key) # type: ignore[return-value]
@sentry_sdk.tracing.trace
def get_assemble_status(task, scope, checksum):
"""
Checks the current status of an assembling task.
Returns a tuple in the form ``(status, details)``, where ``status`` is the
ChunkFileState, and ``details`` is either None or a string containing a
notice or error message.
"""
cache_key = _get_cache_key(task, scope, checksum)
client = _get_redis_cluster_for_assemble()
rv = client.get(cache_key)
if rv is None:
return None, None
# It is stored as bytes with [state, detail] on Redis.
return tuple(orjson.loads(rv))
@sentry_sdk.tracing.trace
def set_assemble_status(task, scope, checksum, state, detail=None):
"""
Updates the status of an assembling task. It is cached for 10 minutes.
"""
cache_key = _get_cache_key(task, scope, checksum)
redis_client = _get_redis_cluster_for_assemble()
redis_client.set(name=cache_key, value=orjson.dumps([state, detail]), ex=600)
@sentry_sdk.tracing.trace
def delete_assemble_status(task, scope, checksum):
"""
Deletes the status of an assembling task.
"""
cache_key = _get_cache_key(task, scope, checksum)
redis_client = _get_redis_cluster_for_assemble()
redis_client.delete(cache_key)
@instrumented_task(
name="sentry.tasks.assemble.assemble_dif",
namespace=attachments_tasks,
processing_deadline_duration=60 * 3,
silo_mode=SiloMode.REGION,
)
def assemble_dif(project_id, name, checksum, chunks, debug_id=None, **kwargs):
"""
Assembles uploaded chunks into a ``ProjectDebugFile``.
"""
from sentry.lang.native.sources import record_last_upload
from sentry.models.debugfile import BadDif, create_dif_from_id, detect_dif_from_path
from sentry.models.project import Project
sentry_sdk.get_isolation_scope().set_tag("project", project_id)
delete_file = False
try:
project = Project.objects.filter(id=project_id).get()
set_assemble_status(AssembleTask.DIF, project_id, checksum, ChunkFileState.ASSEMBLING)
# Assemble the chunks into a temporary file
rv = assemble_file(
AssembleTask.DIF, project, name, checksum, chunks, file_type="project.dif"
)
# If not file has been created this means that the file failed to
# assemble because of bad input data. In this case, assemble_file
# has set the assemble status already.
if rv is None:
return
file, temp_file = rv
delete_file = True
with temp_file:
# We only permit split difs to hit this endpoint.
# The client is required to split them up first or we error.
try:
result = detect_dif_from_path(temp_file.name, name=name, debug_id=debug_id)
except BadDif as e:
set_assemble_status(
AssembleTask.DIF, project_id, checksum, ChunkFileState.ERROR, detail=e.args[0]
)
return
if len(result) != 1:
detail = "Object contains %s architectures (1 expected)" % len(result)
set_assemble_status(
AssembleTask.DIF, project_id, checksum, ChunkFileState.ERROR, detail=detail
)
return
dif, created = create_dif_from_id(project, result[0], file=file)
delete_file = False
if created:
record_last_upload(project)
except Exception:
set_assemble_status(
AssembleTask.DIF,
project_id,
checksum,
ChunkFileState.ERROR,
detail="internal server error",
)
logger.exception("failed to assemble dif")
else:
set_assemble_status(
AssembleTask.DIF, project_id, checksum, ChunkFileState.OK, detail=serialize(dif)
)
finally:
if delete_file:
file.delete()
| AssembleResult |
python | aio-libs__aiohttp | aiohttp/http_writer.py | {
"start": 982,
"end": 1343
} | class ____(NamedTuple):
major: int
minor: int
HttpVersion10 = HttpVersion(1, 0)
HttpVersion11 = HttpVersion(1, 1)
_T_OnChunkSent = Optional[
Callable[
[Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]],
Awaitable[None],
]
]
_T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]]
| HttpVersion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.