language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | numpy__numpy | benchmarks/benchmarks/bench_reduce.py | {
"start": 1725,
"end": 2019
} | class ____(Benchmark):
params = [np.float32, np.float64]
param_names = ['dtype']
def setup(self, dtype):
self.d = np.ones(20000, dtype=dtype)
def time_min(self, dtype):
np.fmin.reduce(self.d)
def time_max(self, dtype):
np.fmax.reduce(self.d)
| FMinMax |
python | readthedocs__readthedocs.org | readthedocs/projects/querysets.py | {
"start": 6690,
"end": 8198
} | class ____(NoReprQuerySet, models.QuerySet):
"""
Useful for objects that relate to Project and its permissions.
Objects get the permissions from the project itself.
..note:: This shouldn't be used as a subclass.
"""
use_for_related_fields = True
project_field = "project"
def _add_from_user_projects(self, queryset, user):
if user and user.is_authenticated:
projects_pk = AdminPermission.projects(
user=user,
admin=True,
member=True,
).values_list("pk", flat=True)
kwargs = {f"{self.project_field}__in": projects_pk}
user_queryset = self.filter(**kwargs)
queryset = user_queryset | queryset
return queryset
def public(self, user=None, project=None):
kwargs = {f"{self.project_field}__privacy_level": constants.PUBLIC}
queryset = self.filter(**kwargs)
if user:
if user.is_superuser:
queryset = self.all()
else:
queryset = self._add_from_user_projects(queryset, user)
if project:
queryset = queryset.filter(project=project)
return queryset.distinct()
def api(self, user=None):
return self.public(user)
def api_v2(self, *args, **kwargs):
# API v2 is the same as API v3 for .org, but it's
# different for .com, this method is overridden there.
return self.api(*args, **kwargs)
| RelatedProjectQuerySet |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 12137,
"end": 12589
} | class ____(NamePathModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"PrependPath: {self.name}+{self.value}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories = [path_to_os_path(os.path.normpath(self.value)).pop()] + directories
env[self.name] = self.separator.join(directories)
| PrependPath |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_kronecker_test.py | {
"start": 3133,
"end": 11741
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enabled()
config.enable_tensor_float_32_execution(False)
# Increase from 1e-6 to 1e-4
self._atol[dtypes.float32] = 1e-4
self._atol[dtypes.complex64] = 1e-4
self._rtol[dtypes.float32] = 1e-4
self._rtol[dtypes.complex64] = 1e-4
@staticmethod
def operator_shapes_infos():
shape_info = linear_operator_test_util.OperatorShapesInfo
return [
shape_info((1, 1), factors=[(1, 1), (1, 1)]),
shape_info((8, 8), factors=[(2, 2), (2, 2), (2, 2)]),
shape_info((12, 12), factors=[(2, 2), (3, 3), (2, 2)]),
shape_info((1, 3, 3), factors=[(1, 1), (1, 3, 3)]),
shape_info((3, 6, 6), factors=[(3, 1, 1), (1, 2, 2), (1, 3, 3)]),
]
def operator_and_matrix(
self, build_info, dtype, use_placeholder,
ensure_self_adjoint_and_pd=False):
# Kronecker products constructed below will be from symmetric
# positive-definite matrices.
del ensure_self_adjoint_and_pd
shape = list(build_info.shape)
expected_factors = build_info.__dict__["factors"]
matrices = [
linear_operator_test_util.random_positive_definite_matrix(
block_shape, dtype, force_well_conditioned=True)
for block_shape in expected_factors
]
lin_op_matrices = matrices
if use_placeholder:
lin_op_matrices = [
array_ops.placeholder_with_default(m, shape=None) for m in matrices]
operator = kronecker.LinearOperatorKronecker(
[linalg.LinearOperatorFullMatrix(
l,
is_square=True,
is_self_adjoint=True,
is_positive_definite=True)
for l in lin_op_matrices])
matrices = linear_operator_util.broadcast_matrix_batch_dims(matrices)
kronecker_dense = _kronecker_dense(matrices)
if not use_placeholder:
kronecker_dense.set_shape(shape)
return operator, kronecker_dense
def test_is_x_flags(self):
# Matrix with two positive eigenvalues, 1, and 1.
# The matrix values do not effect auto-setting of the flags.
matrix = [[1., 0.], [1., 1.]]
operator = kronecker.LinearOperatorKronecker(
[linalg.LinearOperatorFullMatrix(matrix),
linalg.LinearOperatorFullMatrix(matrix)],
is_positive_definite=True,
is_non_singular=True,
is_self_adjoint=False)
self.assertTrue(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
self.assertFalse(operator.is_self_adjoint)
def test_is_non_singular_auto_set(self):
# Matrix with two positive eigenvalues, 11 and 8.
# The matrix values do not effect auto-setting of the flags.
matrix = [[11., 0.], [1., 8.]]
operator_1 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True)
operator_2 = linalg.LinearOperatorFullMatrix(matrix, is_non_singular=True)
operator = kronecker.LinearOperatorKronecker(
[operator_1, operator_2],
is_positive_definite=False, # No reason it HAS to be False...
is_non_singular=None)
self.assertFalse(operator.is_positive_definite)
self.assertTrue(operator.is_non_singular)
with self.assertRaisesRegex(ValueError, "always non-singular"):
kronecker.LinearOperatorKronecker(
[operator_1, operator_2], is_non_singular=False)
def test_name(self):
matrix = [[11., 0.], [1., 8.]]
operator_1 = linalg.LinearOperatorFullMatrix(matrix, name="left")
operator_2 = linalg.LinearOperatorFullMatrix(matrix, name="right")
operator = kronecker.LinearOperatorKronecker([operator_1, operator_2])
self.assertEqual("left_x_right", operator.name)
def test_different_dtypes_raises(self):
operators = [
linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3)),
linalg.LinearOperatorFullMatrix(rng.rand(2, 3, 3).astype(np.float32))
]
with self.assertRaisesRegex(TypeError, "same dtype"):
kronecker.LinearOperatorKronecker(operators)
def test_empty_or_one_operators_raises(self):
with self.assertRaisesRegex(ValueError, ">=1 operators"):
kronecker.LinearOperatorKronecker([])
def test_kronecker_adjoint_type(self):
matrix = [[1., 0.], [0., 1.]]
operator = kronecker.LinearOperatorKronecker(
[
linalg.LinearOperatorFullMatrix(
matrix, is_non_singular=True),
linalg.LinearOperatorFullMatrix(
matrix, is_non_singular=True),
],
is_non_singular=True,
)
adjoint = operator.adjoint()
self.assertIsInstance(
adjoint,
kronecker.LinearOperatorKronecker)
self.assertEqual(2, len(adjoint.operators))
def test_kronecker_cholesky_type(self):
matrix = [[1., 0.], [0., 1.]]
operator = kronecker.LinearOperatorKronecker(
[
linalg.LinearOperatorFullMatrix(
matrix,
is_positive_definite=True,
is_self_adjoint=True,
),
linalg.LinearOperatorFullMatrix(
matrix,
is_positive_definite=True,
is_self_adjoint=True,
),
],
is_positive_definite=True,
is_self_adjoint=True,
)
cholesky_factor = operator.cholesky()
self.assertIsInstance(
cholesky_factor,
kronecker.LinearOperatorKronecker)
self.assertEqual(2, len(cholesky_factor.operators))
self.assertIsInstance(
cholesky_factor.operators[0],
lower_triangular.LinearOperatorLowerTriangular)
self.assertIsInstance(
cholesky_factor.operators[1],
lower_triangular.LinearOperatorLowerTriangular)
def test_kronecker_inverse_type(self):
matrix = [[1., 0.], [0., 1.]]
operator = kronecker.LinearOperatorKronecker(
[
linalg.LinearOperatorFullMatrix(
matrix, is_non_singular=True),
linalg.LinearOperatorFullMatrix(
matrix, is_non_singular=True),
],
is_non_singular=True,
)
inverse = operator.inverse()
self.assertIsInstance(
inverse,
kronecker.LinearOperatorKronecker)
self.assertEqual(2, len(inverse.operators))
def test_tape_safe(self):
matrix_1 = variables_module.Variable([[1., 0.], [0., 1.]])
matrix_2 = variables_module.Variable([[2., 0.], [0., 2.]])
operator = kronecker.LinearOperatorKronecker(
[
linalg.LinearOperatorFullMatrix(
matrix_1, is_non_singular=True),
linalg.LinearOperatorFullMatrix(
matrix_2, is_non_singular=True),
],
is_non_singular=True,
)
self.check_tape_safe(operator)
def test_convert_variables_to_tensors(self):
matrix_1 = variables_module.Variable([[1., 0.], [0., 1.]])
matrix_2 = variables_module.Variable([[2., 0.], [0., 2.]])
operator = kronecker.LinearOperatorKronecker(
[
linalg.LinearOperatorFullMatrix(
matrix_1, is_non_singular=True),
linalg.LinearOperatorFullMatrix(
matrix_2, is_non_singular=True),
],
is_non_singular=True,
)
with self.cached_session() as sess:
sess.run([x.initializer for x in operator.variables])
self.check_convert_variables_to_tensors(operator)
def test_composite_gradients(self):
with backprop.GradientTape() as tape:
op1 = linalg.LinearOperatorFullMatrix(
[[1., 0.], [0., 1.]], is_non_singular=True)
op2 = linalg.LinearOperatorFullMatrix(
[[2., 0.], [0., 2.]], is_non_singular=True)
tape.watch([op1, op2])
operator = kronecker.LinearOperatorKronecker(
[op1, op2], is_non_singular=True)
x = self.make_x(op1, adjoint=False)
y = op1.matmul(x)
connected_grad, disconnected_grad, composite_grad = tape.gradient(
y, [op1, op2, operator])
disconnected_component_grad = composite_grad.operators[1].to_dense()
self.assertAllClose(connected_grad.to_dense(),
composite_grad.operators[0].to_dense())
self.assertAllClose(disconnected_component_grad,
array_ops.zeros_like(disconnected_component_grad))
self.assertIsNone(disconnected_grad)
if __name__ == "__main__":
linear_operator_test_util.add_tests(SquareLinearOperatorKroneckerTest)
test.main()
| SquareLinearOperatorKroneckerTest |
python | pytorch__pytorch | test/quantization/eager/test_model_numerics.py | {
"start": 304,
"end": 7618
} | class ____(QuantizationTestCase):
def test_float_quant_compare_per_tensor(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
torch.manual_seed(42)
my_model = ModelMultipleOps().to(torch.float32)
my_model.eval()
calib_data = torch.rand(1024, 3, 15, 15, dtype=torch.float32)
eval_data = torch.rand(1, 3, 15, 15, dtype=torch.float32)
out_ref = my_model(eval_data)
qModel = torch.ao.quantization.QuantWrapper(my_model)
qModel.eval()
qModel.qconfig = torch.ao.quantization.default_qconfig
torch.ao.quantization.fuse_modules(
qModel.module, [["conv1", "bn1", "relu1"]], inplace=True
)
torch.ao.quantization.prepare(qModel, inplace=True)
qModel(calib_data)
torch.ao.quantization.convert(qModel, inplace=True)
out_q = qModel(eval_data)
SQNRdB = 20 * torch.log10(
torch.norm(out_ref) / torch.norm(out_ref - out_q)
)
# Quantized model output should be close to floating point model output numerically
# Setting target SQNR to be 30 dB so that relative error is 1e-3 below the desired
# output
self.assertGreater(
SQNRdB,
30,
msg="Quantized model numerics diverge from float, expect SQNR > 30 dB",
)
def test_float_quant_compare_per_channel(self):
# Test for per-channel Quant
torch.manual_seed(67)
my_model = ModelMultipleOps().to(torch.float32)
my_model.eval()
calib_data = torch.rand(2048, 3, 15, 15, dtype=torch.float32)
eval_data = torch.rand(10, 3, 15, 15, dtype=torch.float32)
out_ref = my_model(eval_data)
q_model = torch.ao.quantization.QuantWrapper(my_model)
q_model.eval()
q_model.qconfig = torch.ao.quantization.default_per_channel_qconfig
torch.ao.quantization.fuse_modules(
q_model.module, [["conv1", "bn1", "relu1"]], inplace=True
)
torch.ao.quantization.prepare(q_model)
q_model(calib_data)
torch.ao.quantization.convert(q_model)
out_q = q_model(eval_data)
SQNRdB = 20 * torch.log10(torch.norm(out_ref) / torch.norm(out_ref - out_q))
# Quantized model output should be close to floating point model output numerically
# Setting target SQNR to be 35 dB
self.assertGreater(
SQNRdB,
35,
msg="Quantized model numerics diverge from float, expect SQNR > 35 dB",
)
def test_fake_quant_true_quant_compare(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
torch.manual_seed(67)
my_model = ModelMultipleOpsNoAvgPool().to(torch.float32)
calib_data = torch.rand(2048, 3, 15, 15, dtype=torch.float32)
eval_data = torch.rand(10, 3, 15, 15, dtype=torch.float32)
my_model.eval()
out_ref = my_model(eval_data)
fq_model = torch.ao.quantization.QuantWrapper(my_model)
fq_model.train()
fq_model.qconfig = torch.ao.quantization.default_qat_qconfig
torch.ao.quantization.fuse_modules_qat(
fq_model.module, [["conv1", "bn1", "relu1"]], inplace=True
)
torch.ao.quantization.prepare_qat(fq_model)
fq_model.eval()
fq_model.apply(torch.ao.quantization.disable_fake_quant)
fq_model.apply(torch.ao.nn.intrinsic.qat.freeze_bn_stats)
fq_model(calib_data)
fq_model.apply(torch.ao.quantization.enable_fake_quant)
fq_model.apply(torch.ao.quantization.disable_observer)
out_fq = fq_model(eval_data)
SQNRdB = 20 * torch.log10(
torch.norm(out_ref) / torch.norm(out_ref - out_fq)
)
# Quantized model output should be close to floating point model output numerically
# Setting target SQNR to be 35 dB
self.assertGreater(
SQNRdB,
35,
msg="Quantized model numerics diverge from float, expect SQNR > 35 dB",
)
torch.ao.quantization.convert(fq_model)
out_q = fq_model(eval_data)
SQNRdB = 20 * torch.log10(
torch.norm(out_fq) / (torch.norm(out_fq - out_q) + 1e-10)
)
self.assertGreater(
SQNRdB,
60,
msg="Fake quant and true quant numerics diverge, expect SQNR > 60 dB",
)
# Test to compare weight only quantized model numerics and
# activation only quantized model numerics with float
def test_weight_only_activation_only_fakequant(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
torch.manual_seed(67)
calib_data = torch.rand(2048, 3, 15, 15, dtype=torch.float32)
eval_data = torch.rand(10, 3, 15, 15, dtype=torch.float32)
qconfigset = {
torch.ao.quantization.default_weight_only_qconfig,
torch.ao.quantization.default_activation_only_qconfig,
}
SQNRTarget = [35, 45]
for idx, qconfig in enumerate(qconfigset):
my_model = ModelMultipleOpsNoAvgPool().to(torch.float32)
my_model.eval()
out_ref = my_model(eval_data)
fq_model = torch.ao.quantization.QuantWrapper(my_model)
fq_model.train()
fq_model.qconfig = qconfig
torch.ao.quantization.fuse_modules_qat(
fq_model.module, [["conv1", "bn1", "relu1"]], inplace=True
)
torch.ao.quantization.prepare_qat(fq_model)
fq_model.eval()
fq_model.apply(torch.ao.quantization.disable_fake_quant)
fq_model.apply(torch.ao.nn.intrinsic.qat.freeze_bn_stats)
fq_model(calib_data)
fq_model.apply(torch.ao.quantization.enable_fake_quant)
fq_model.apply(torch.ao.quantization.disable_observer)
out_fq = fq_model(eval_data)
SQNRdB = 20 * torch.log10(
torch.norm(out_ref) / torch.norm(out_ref - out_fq)
)
self.assertGreater(
SQNRdB,
SQNRTarget[idx],
msg="Quantized model numerics diverge from float",
)
if __name__ == "__main__":
raise RuntimeError(
"This test file is not meant to be run directly, use:\n\n"
"\tpython test/test_quantization.py TESTNAME\n\n"
"instead."
)
| TestModelNumericsEager |
python | ray-project__ray | python/ray/tests/spark/test_basic.py | {
"start": 1437,
"end": 9430
} | class ____(ABC):
spark = None
num_total_cpus = None
num_total_gpus = None
num_cpus_per_spark_task = None
num_gpus_per_spark_task = None
max_spark_tasks = None
@classmethod
def teardown_class(cls):
time.sleep(10) # Wait all background spark job canceled.
os.environ.pop("SPARK_WORKER_CORES", None)
cls.spark.stop()
@staticmethod
def get_ray_worker_resources_list():
wr_list = []
for node in ray.nodes():
# exclude dead node and head node (with 0 CPU resource)
if node["Alive"] and node["Resources"].get("CPU", 0) > 0:
wr_list.append(node["Resources"])
return wr_list
def test_cpu_allocation(self):
for max_worker_nodes, num_cpus_worker_node, max_worker_nodes_arg in [
(
self.max_spark_tasks // 2,
self.num_cpus_per_spark_task,
self.max_spark_tasks // 2,
),
(self.max_spark_tasks, self.num_cpus_per_spark_task, MAX_NUM_WORKER_NODES),
(
self.max_spark_tasks // 2,
self.num_cpus_per_spark_task * 2,
MAX_NUM_WORKER_NODES,
),
(
self.max_spark_tasks // 2,
self.num_cpus_per_spark_task * 2,
self.max_spark_tasks // 2 + 1,
), # Test case: requesting resources exceeding all cluster resources
]:
num_ray_task_slots = self.max_spark_tasks // (
num_cpus_worker_node // self.num_cpus_per_spark_task
)
(
mem_worker_node,
object_store_mem_worker_node,
_,
) = _calc_mem_per_ray_worker_node(
num_task_slots=num_ray_task_slots,
physical_mem_bytes=_RAY_ON_SPARK_WORKER_PHYSICAL_MEMORY_BYTES,
shared_mem_bytes=_RAY_ON_SPARK_WORKER_SHARED_MEMORY_BYTES,
configured_heap_memory_bytes=None,
configured_object_store_bytes=None,
)
with _setup_ray_cluster(
max_worker_nodes=max_worker_nodes_arg,
num_cpus_worker_node=num_cpus_worker_node,
num_gpus_worker_node=0,
head_node_options={"include_dashboard": False},
):
ray.init()
worker_res_list = self.get_ray_worker_resources_list()
assert len(worker_res_list) == max_worker_nodes
for worker_res in worker_res_list:
assert (
worker_res["CPU"] == num_cpus_worker_node
and worker_res["memory"] == mem_worker_node
and worker_res["object_store_memory"]
== object_store_mem_worker_node
)
def test_public_api(self):
try:
ray_temp_root_dir = tempfile.mkdtemp(dir="/tmp")
collect_log_to_path = tempfile.mkdtemp(dir="/tmp")
# Test the case that `collect_log_to_path` directory does not exist.
shutil.rmtree(collect_log_to_path, ignore_errors=True)
setup_ray_cluster(
max_worker_nodes=MAX_NUM_WORKER_NODES,
num_cpus_worker_node=1,
num_gpus_worker_node=0,
collect_log_to_path=collect_log_to_path,
ray_temp_root_dir=ray_temp_root_dir,
head_node_options={"include_dashboard": True},
)
assert (
os.environ["RAY_ADDRESS"]
== ray.util.spark.cluster_init._active_ray_cluster.address
)
ray.init()
@ray.remote
def f(x):
return x * x
futures = [f.remote(i) for i in range(32)]
results = ray.get(futures)
assert results == [i * i for i in range(32)]
shutdown_ray_cluster()
assert "RAY_ADDRESS" not in os.environ
time.sleep(7)
# assert temp dir is removed.
assert len(os.listdir(ray_temp_root_dir)) == 1 and os.listdir(
ray_temp_root_dir
)[0].endswith(".lock")
# assert logs are copied to specified path
listed_items = os.listdir(collect_log_to_path)
assert len(listed_items) == 1 and listed_items[0].startswith("ray-")
log_dest_dir = os.path.join(
collect_log_to_path, listed_items[0], socket.gethostname()
)
assert os.path.exists(log_dest_dir) and len(os.listdir(log_dest_dir)) > 0
finally:
if ray.util.spark.cluster_init._active_ray_cluster is not None:
# if the test raised error and does not destroy cluster,
# destroy it here.
ray.util.spark.cluster_init._active_ray_cluster.shutdown()
time.sleep(5)
shutil.rmtree(ray_temp_root_dir, ignore_errors=True)
shutil.rmtree(collect_log_to_path, ignore_errors=True)
def test_autoscaling(self):
for max_worker_nodes, num_cpus_worker_node, min_worker_nodes in [
(self.max_spark_tasks, self.num_cpus_per_spark_task, 0),
(self.max_spark_tasks // 2, self.num_cpus_per_spark_task * 2, 0),
(self.max_spark_tasks, self.num_cpus_per_spark_task, 1),
]:
num_ray_task_slots = self.max_spark_tasks // (
num_cpus_worker_node // self.num_cpus_per_spark_task
)
(
mem_worker_node,
object_store_mem_worker_node,
_,
) = _calc_mem_per_ray_worker_node(
num_task_slots=num_ray_task_slots,
physical_mem_bytes=_RAY_ON_SPARK_WORKER_PHYSICAL_MEMORY_BYTES,
shared_mem_bytes=_RAY_ON_SPARK_WORKER_SHARED_MEMORY_BYTES,
configured_heap_memory_bytes=None,
configured_object_store_bytes=None,
)
with _setup_ray_cluster(
max_worker_nodes=max_worker_nodes,
min_worker_nodes=min_worker_nodes,
num_cpus_worker_node=num_cpus_worker_node,
num_gpus_worker_node=0,
head_node_options={"include_dashboard": False},
autoscale_idle_timeout_minutes=0.1,
):
ray.init()
worker_res_list = self.get_ray_worker_resources_list()
assert len(worker_res_list) == min_worker_nodes
@ray.remote(num_cpus=num_cpus_worker_node)
def f(x):
import time
time.sleep(5)
return x * x
# Test scale up
futures = [f.remote(i) for i in range(8)]
results = ray.get(futures)
assert results == [i * i for i in range(8)]
worker_res_list = self.get_ray_worker_resources_list()
assert len(worker_res_list) == max_worker_nodes and all(
worker_res_list[i]["CPU"] == num_cpus_worker_node
and worker_res_list[i]["memory"] == mem_worker_node
and worker_res_list[i]["object_store_memory"]
== object_store_mem_worker_node
for i in range(max_worker_nodes)
)
# Test scale down
wait_for_condition(
lambda: len(self.get_ray_worker_resources_list())
== min_worker_nodes,
timeout=60,
retry_interval_ms=1000,
)
if min_worker_nodes > 0:
# Test scaling down keeps nodes number >= min_worker_nodes
time.sleep(30)
assert len(self.get_ray_worker_resources_list()) == min_worker_nodes
| RayOnSparkCPUClusterTestBase |
python | getsentry__sentry | tests/sentry/incidents/utils/test_metric_issue_base.py | {
"start": 947,
"end": 4356
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.detector_group_key = None
self.detector = self.create_detector(
project=self.project,
workflow_condition_group=self.create_data_condition_group(),
type=MetricIssue.slug,
created_by_id=self.user.id,
)
self.critical_detector_trigger = self.create_data_condition(
type=Condition.GREATER,
comparison=5,
condition_result=DetectorPriorityLevel.HIGH,
condition_group=self.detector.workflow_condition_group,
)
self.warning_detector_trigger = self.create_data_condition(
comparison=3,
type=Condition.GREATER,
condition_result=DetectorPriorityLevel.MEDIUM,
condition_group=self.detector.workflow_condition_group,
)
self.resolve_detector_trigger = self.create_data_condition(
type=Condition.LESS,
comparison=3,
condition_result=DetectorPriorityLevel.OK,
condition_group=self.detector.workflow_condition_group,
)
with self.tasks():
self.snuba_query = create_snuba_query(
query_type=SnubaQuery.Type.ERROR,
dataset=Dataset.Events,
query="hello",
aggregate="count()",
time_window=timedelta(minutes=1),
resolution=timedelta(minutes=1),
environment=self.environment,
event_types=[SnubaQueryEventType.EventType.ERROR],
)
self.query_subscription = create_snuba_subscription(
project=self.detector.project,
subscription_type=INCIDENTS_SNUBA_SUBSCRIPTION_TYPE,
snuba_query=self.snuba_query,
)
self.data_source = self.create_data_source(
organization=self.organization,
source_id=str(self.query_subscription.id),
type=DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION,
)
self.create_data_source_detector(self.data_source, self.detector)
self.alert_rule = self.create_alert_rule()
self.create_alert_rule_detector(alert_rule_id=self.alert_rule.id, detector=self.detector)
def create_subscription_packet(
self, value: int, time_jump: int = 0
) -> DataPacket[ProcessedSubscriptionUpdate]:
# XXX: the timestamp here is just used as a dedupe value, so we can avoid using freeze_time
# by providing a large timedelta
packet = ProcessedSubscriptionUpdate(
entity="entity",
subscription_id=str(self.query_subscription.id),
values={"value": value},
timestamp=datetime.now(UTC) + timedelta(minutes=time_jump),
)
return DataPacket[ProcessedSubscriptionUpdate](
source_id=str(self.query_subscription.id), packet=packet
)
def process_packet_and_return_result(
self, data_packet: DataPacket
) -> IssueOccurrence | StatusChangeMessage | None:
results = process_data_packet(data_packet, DATA_SOURCE_SNUBA_QUERY_SUBSCRIPTION)
if not results:
# alert did not trigger
return None
evaluation_result: DetectorEvaluationResult = results[0][1][self.detector_group_key]
return evaluation_result.result
| BaseMetricIssueTest |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-shopify/llama_index/tools/shopify/base.py | {
"start": 91,
"end": 1142
} | class ____(BaseToolSpec):
"""Shopify tool spec."""
spec_functions = ["run_graphql_query"]
def __init__(self, shop_url: str, api_version: str, admin_api_key: str):
# Currently only supports Admin API auth
# https://shopify.dev/docs/apps/auth/admin-app-access-tokens
from shopify import Session, ShopifyResource
session = Session(shop_url, api_version, admin_api_key)
ShopifyResource.activate_session(session)
def run_graphql_query(self, graphql_query: str):
"""
Run a GraphQL query against the Shopify Admin API.
Example graphql_query: {
products (first: 3) {
edges {
node {
id
title
handle
}
}
}
}
providing this query would return the id, title and handle of the first 3 products
"""
from shopify import GraphQL
return GraphQL().execute(graphql_query)
| ShopifyToolSpec |
python | fastai__fastai | nbs/examples/migrating_catalyst.py | {
"start": 698,
"end": 1319
} | class ____(dl.Runner):
def predict_batch(self, batch): return self.model(batch[0].to(self.device).view(batch[0].size(0), -1))
def _handle_batch(self, batch):
x, y = batch
y_hat = self.model(x.view(x.size(0), -1))
loss = F.cross_entropy(y_hat, y)
accuracy01, accuracy03 = metrics.accuracy(y_hat, y, topk=(1, 3))
self.batch_metrics.update(
{"loss": loss, "accuracy01": accuracy01, "accuracy03": accuracy03}
)
if self.is_train_loader:
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
| CustomRunner |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/cmdline.py | {
"start": 16607,
"end": 23655
} | class ____(argparse.HelpFormatter):
def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
if width is None:
try:
width = shutil.get_terminal_size().columns - 2
except Exception:
pass
argparse.HelpFormatter.__init__(self, prog, indent_increment,
max_help_position, width)
def main(args=sys.argv):
"""
Main command line entry point.
"""
desc = "Highlight an input file and write the result to an output file."
parser = argparse.ArgumentParser(description=desc, add_help=False,
formatter_class=HelpFormatter)
operation = parser.add_argument_group('Main operation')
lexersel = operation.add_mutually_exclusive_group()
lexersel.add_argument(
'-l', metavar='LEXER',
help='Specify the lexer to use. (Query names with -L.) If not '
'given and -g is not present, the lexer is guessed from the filename.')
lexersel.add_argument(
'-g', action='store_true',
help='Guess the lexer from the file contents, or pass through '
'as plain text if nothing can be guessed.')
operation.add_argument(
'-F', metavar='FILTER[:options]', action='append',
help='Add a filter to the token stream. (Query names with -L.) '
'Filter options are given after a colon if necessary.')
operation.add_argument(
'-f', metavar='FORMATTER',
help='Specify the formatter to use. (Query names with -L.) '
'If not given, the formatter is guessed from the output filename, '
'and defaults to the terminal formatter if the output is to the '
'terminal or an unknown file extension.')
operation.add_argument(
'-O', metavar='OPTION=value[,OPTION=value,...]', action='append',
help='Give options to the lexer and formatter as a comma-separated '
'list of key-value pairs. '
'Example: `-O bg=light,python=cool`.')
operation.add_argument(
'-P', metavar='OPTION=value', action='append',
help='Give a single option to the lexer and formatter - with this '
'you can pass options whose value contains commas and equal signs. '
'Example: `-P "heading=Pygments, the Python highlighter"`.')
operation.add_argument(
'-o', metavar='OUTPUTFILE',
help='Where to write the output. Defaults to standard output.')
operation.add_argument(
'INPUTFILE', nargs='?',
help='Where to read the input. Defaults to standard input.')
flags = parser.add_argument_group('Operation flags')
flags.add_argument(
'-v', action='store_true',
help='Print a detailed traceback on unhandled exceptions, which '
'is useful for debugging and bug reports.')
flags.add_argument(
'-s', action='store_true',
help='Process lines one at a time until EOF, rather than waiting to '
'process the entire file. This only works for stdin, only for lexers '
'with no line-spanning constructs, and is intended for streaming '
'input such as you get from `tail -f`. '
'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')
flags.add_argument(
'-x', action='store_true',
help='Allow custom lexers and formatters to be loaded from a .py file '
'relative to the current working directory. For example, '
'`-l ./customlexer.py -x`. By default, this option expects a file '
'with a class named CustomLexer or CustomFormatter; you can also '
'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '
'Users should be very careful not to use this option with untrusted '
'files, because it will import and run them.')
flags.add_argument('--json', help='Output as JSON. This can '
'be only used in conjunction with -L.',
default=False,
action='store_true')
special_modes_group = parser.add_argument_group(
'Special modes - do not do any highlighting')
special_modes = special_modes_group.add_mutually_exclusive_group()
special_modes.add_argument(
'-S', metavar='STYLE -f formatter',
help='Print style definitions for STYLE for a formatter '
'given with -f. The argument given by -a is formatter '
'dependent.')
special_modes.add_argument(
'-L', nargs='*', metavar='WHAT',
help='List lexers, formatters, styles or filters -- '
'give additional arguments for the thing(s) you want to list '
'(e.g. "styles"), or omit them to list everything.')
special_modes.add_argument(
'-N', metavar='FILENAME',
help='Guess and print out a lexer name based solely on the given '
'filename. Does not take input or highlight anything. If no specific '
'lexer can be determined, "text" is printed.')
special_modes.add_argument(
'-C', action='store_true',
help='Like -N, but print out a lexer name based solely on '
'a given content from standard input.')
special_modes.add_argument(
'-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),
help='Print detailed help for the object <name> of type <type>, '
'where <type> is one of "lexer", "formatter" or "filter".')
special_modes.add_argument(
'-V', action='store_true',
help='Print the package version.')
special_modes.add_argument(
'-h', '--help', action='store_true',
help='Print this help.')
special_modes_group.add_argument(
'-a', metavar='ARG',
help='Formatter-specific additional argument for the -S (print '
'style sheet) mode.')
argns = parser.parse_args(args[1:])
try:
return main_inner(parser, argns)
except BrokenPipeError:
# someone closed our stdout, e.g. by quitting a pager.
return 0
except Exception:
if argns.v:
print(file=sys.stderr)
print('*' * 65, file=sys.stderr)
print('An unhandled exception occurred while highlighting.',
file=sys.stderr)
print('Please report the whole traceback to the issue tracker at',
file=sys.stderr)
print('<https://github.com/pygments/pygments/issues>.',
file=sys.stderr)
print('*' * 65, file=sys.stderr)
print(file=sys.stderr)
raise
import traceback
info = traceback.format_exception(*sys.exc_info())
msg = info[-1].strip()
if len(info) >= 3:
# extract relevant file and position info
msg += '\n (f{})'.format(info[-2].split('\n')[0].strip()[1:])
print(file=sys.stderr)
print('*** Error while highlighting:', file=sys.stderr)
print(msg, file=sys.stderr)
print('*** If this is a bug you want to report, please rerun with -v.',
file=sys.stderr)
return 1
| HelpFormatter |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 9187,
"end": 10506
} | class ____(Importation):
"""
A binding created by a submodule import statement.
A submodule import is a special case where the root module is implicitly
imported, without an 'as' clause, and the submodule is also imported.
Python does not restrict which attributes of the root module may be used.
This class is only used when the submodule import is without an 'as' clause.
pyflakes handles this case by registering the root module name in the scope,
allowing any attribute of the root module to be accessed.
RedefinedWhileUnused is suppressed in `redefines` unless the submodule
name is also the same, to avoid false positives.
"""
def __init__(self, name, source):
# A dot should only appear in the name when it is a submodule import
assert '.' in name and (not source or isinstance(source, ast.Import))
package_name = name.split('.')[0]
super().__init__(package_name, source)
self.fullName = name
def redefines(self, other):
if isinstance(other, Importation):
return self.fullName == other.fullName
return super().redefines(other)
def __str__(self):
return self.fullName
@property
def source_statement(self):
return 'import ' + self.fullName
| SubmoduleImportation |
python | python__mypy | mypyc/codegen/emit.py | {
"start": 1608,
"end": 2719
} | class ____:
"""A representation of a declaration in C.
This is used to generate declarations in header files and
(optionally) definitions in source files.
Attributes:
decl: C source code for the declaration.
defn: Optionally, C source code for a definition.
dependencies: The names of any objects that must be declared prior.
is_type: Whether the declaration is of a C type. (C types will be declared in
external header files and not marked 'extern'.)
needs_export: Whether the declared object needs to be exported to
other modules in the linking table.
"""
def __init__(
self,
decl: str | list[str],
defn: list[str] | None = None,
*,
dependencies: set[str] | None = None,
is_type: bool = False,
needs_export: bool = False,
) -> None:
self.decl = [decl] if isinstance(decl, str) else decl
self.defn = defn
self.dependencies = dependencies or set()
self.is_type = is_type
self.needs_export = needs_export
| HeaderDeclaration |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/transfers/s3_to_teradata.py | {
"start": 1359,
"end": 5546
} | class ____(BaseOperator):
"""
Loads CSV, JSON and Parquet format data from Amazon S3 to Teradata.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3ToTeradataOperator`
:param s3_source_key: The URI format specifying the location of the S3 bucket.(templated)
The URI format is /s3/YOUR-BUCKET.s3.amazonaws.com/YOUR-BUCKET-NAME.
Refer to
https://docs.teradata.com/search/documents?query=native+object+store&sort=last_update&virtual-field=title_only&content-lang=en-US
:param public_bucket: Specifies whether the provided S3 bucket is public. If the bucket is public,
it means that anyone can access the objects within it via a URL without requiring authentication.
If the bucket is private and authentication is not provided, the operator will throw an exception.
:param teradata_table: The name of the teradata table to which the data is transferred.(templated)
:param aws_conn_id: The Airflow AWS connection used for AWS credentials.
:param teradata_conn_id: The connection ID used to connect to Teradata
:ref:`Teradata connection <howto/connection:Teradata>`.
:param teradata_authorization_name: The name of Teradata Authorization Database Object,
is used to control who can access an S3 object store.
Refer to
https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/Teradata-VantageTM-Native-Object-Store-Getting-Started-Guide-17.20/Setting-Up-Access/Controlling-Foreign-Table-Access-with-an-AUTHORIZATION-Object
Note that ``s3_source_key`` and ``teradata_table`` are
templated, so you can use variables in them if you wish.
"""
template_fields: Sequence[str] = ("s3_source_key", "teradata_table")
ui_color = "#e07c24"
def __init__(
self,
*,
s3_source_key: str,
public_bucket: bool = False,
teradata_table: str,
aws_conn_id: str = "aws_default",
teradata_conn_id: str = "teradata_default",
teradata_authorization_name: str = "",
**kwargs,
) -> None:
super().__init__(**kwargs)
self.s3_source_key = s3_source_key
self.public_bucket = public_bucket
self.teradata_table = teradata_table
self.aws_conn_id = aws_conn_id
self.teradata_conn_id = teradata_conn_id
self.teradata_authorization_name = teradata_authorization_name
def execute(self, context: Context) -> None:
self.log.info(
"transferring data from %s to teradata table %s...", self.s3_source_key, self.teradata_table
)
s3_hook = S3Hook(aws_conn_id=self.aws_conn_id)
teradata_hook = TeradataHook(teradata_conn_id=self.teradata_conn_id)
credentials_part = "ACCESS_ID= '' ACCESS_KEY= ''"
if not self.public_bucket:
# Accessing data directly from the S3 bucket and creating permanent table inside the database
if self.teradata_authorization_name:
credentials_part = f"AUTHORIZATION={self.teradata_authorization_name}"
else:
credentials = s3_hook.get_credentials()
access_key = credentials.access_key
access_secret = credentials.secret_key
credentials_part = f"ACCESS_ID= '{access_key}' ACCESS_KEY= '{access_secret}'"
token = credentials.token
if token:
credentials_part = credentials_part + f" SESSION_TOKEN = '{token}'"
sql = dedent(f"""
CREATE MULTISET TABLE {self.teradata_table} AS
(
SELECT * FROM (
LOCATION = '{self.s3_source_key}'
{credentials_part}
) AS d
) WITH DATA
""").rstrip()
try:
teradata_hook.run(sql, True)
except Exception as ex:
self.log.error(str(ex))
raise
self.log.info("The transfer of data from S3 to Teradata was successful")
| S3ToTeradataOperator |
python | numba__numba | numba/tests/test_inlining.py | {
"start": 4000,
"end": 4251
} | class ____(compiler.CompilerBase):
"""compiler pipeline for testing inlining after optimization
"""
def define_pipelines(self):
pm = gen_pipeline(self.state, InlineTestPass)
pm.finalize()
return [pm]
| InlineTestPipeline |
python | RaRe-Technologies__gensim | gensim/models/ensemblelda.py | {
"start": 5163,
"end": 22779
} | class ____:
max_num_neighboring_labels: int # the max number of parent labels among each topic of a given cluster
neighboring_labels: List[Set[int]] # a concatenated list of the neighboring_labels sets of each topic
label: int # the unique identifier of the cluster
num_cores: int # how many topics in the cluster are cores
def _is_valid_core(topic):
"""Check if the topic is a valid core, i.e. no neighboring valid cluster is overlapping with it.
Parameters
----------
topic : :class:`Topic`
topic to validate
"""
return topic.is_core and (topic.valid_neighboring_labels == {topic.label})
def _remove_from_all_sets(label, clusters):
"""Remove a label from every set in "neighboring_labels" for each core in ``clusters``."""
for cluster in clusters:
for neighboring_labels_set in cluster.neighboring_labels:
if label in neighboring_labels_set:
neighboring_labels_set.remove(label)
def _contains_isolated_cores(label, cluster, min_cores):
"""Check if the cluster has at least ``min_cores`` of cores that belong to no other cluster."""
return sum([neighboring_labels == {label} for neighboring_labels in cluster.neighboring_labels]) >= min_cores
def _aggregate_topics(grouped_by_labels):
"""Aggregate the labeled topics to a list of clusters.
Parameters
----------
grouped_by_labels : dict of (int, list of :class:`Topic`)
The return value of _group_by_labels. A mapping of the label to a list of each topic which belongs to the
label.
Returns
-------
list of :class:`Cluster`
It is sorted by max_num_neighboring_labels in descending order. There is one single element for each cluster.
"""
clusters = []
for label, topics in grouped_by_labels.items():
max_num_neighboring_labels = 0
neighboring_labels = [] # will be a list of sets
for topic in topics:
max_num_neighboring_labels = max(topic.num_neighboring_labels, max_num_neighboring_labels)
neighboring_labels.append(topic.neighboring_labels)
neighboring_labels = [x for x in neighboring_labels if len(x) > 0]
clusters.append(Cluster(
max_num_neighboring_labels=max_num_neighboring_labels,
neighboring_labels=neighboring_labels,
label=label,
num_cores=len([topic for topic in topics if topic.is_core]),
))
logger.info("found %s clusters", len(clusters))
return clusters
def _group_by_labels(cbdbscan_topics):
"""Group all the learned cores by their label, which was assigned in the cluster_model.
Parameters
----------
cbdbscan_topics : list of :class:`Topic`
A list of topic data resulting from fitting a :class:`~CBDBSCAN` object.
After calling .fit on a CBDBSCAN model, the results can be retrieved from it by accessing the .results
member, which can be used as the argument to this function. It is a list of infos gathered during
the clustering step and each element in the list corresponds to a single topic.
Returns
-------
dict of (int, list of :class:`Topic`)
A mapping of the label to a list of topics that belong to that particular label. Also adds
a new member to each topic called num_neighboring_labels, which is the number of
neighboring_labels of that topic.
"""
grouped_by_labels = {}
for topic in cbdbscan_topics:
if topic.is_core:
topic.num_neighboring_labels = len(topic.neighboring_labels)
label = topic.label
if label not in grouped_by_labels:
grouped_by_labels[label] = []
grouped_by_labels[label].append(topic)
return grouped_by_labels
def _teardown(pipes, processes, i):
"""Close pipes and terminate processes.
Parameters
----------
pipes : {list of :class:`multiprocessing.Pipe`}
list of pipes that the processes use to communicate with the parent
processes : {list of :class:`multiprocessing.Process`}
list of worker processes
"""
for parent_conn, child_conn in pipes:
child_conn.close()
parent_conn.close()
for process in processes:
if process.is_alive():
process.terminate()
del process
def mass_masking(a, threshold=None):
"""Original masking method. Returns a new binary mask."""
if threshold is None:
threshold = 0.95
sorted_a = np.sort(a)[::-1]
largest_mass = sorted_a.cumsum() < threshold
smallest_valid = sorted_a[largest_mass][-1]
return a >= smallest_valid
def rank_masking(a, threshold=None):
"""Faster masking method. Returns a new binary mask."""
if threshold is None:
threshold = 0.11
return a > np.sort(a)[::-1][int(len(a) * threshold)]
def _validate_clusters(clusters, min_cores):
"""Check which clusters from the cbdbscan step are significant enough. is_valid is set accordingly."""
# Clusters with noisy invalid neighbors may have a harder time being marked as stable, so start with the
# easy ones and potentially already remove some noise by also sorting smaller clusters to the front.
# This clears up the clusters a bit before checking the ones with many neighbors.
def _cluster_sort_key(cluster):
return cluster.max_num_neighboring_labels, cluster.num_cores, cluster.label
sorted_clusters = sorted(clusters, key=_cluster_sort_key, reverse=False)
for cluster in sorted_clusters:
cluster.is_valid = None
if cluster.num_cores < min_cores:
cluster.is_valid = False
_remove_from_all_sets(cluster.label, sorted_clusters)
# now that invalid clusters are removed, check which clusters contain enough cores that don't belong to any
# other cluster.
for cluster in [cluster for cluster in sorted_clusters if cluster.is_valid is None]:
label = cluster.label
if _contains_isolated_cores(label, cluster, min_cores):
cluster.is_valid = True
else:
cluster.is_valid = False
_remove_from_all_sets(label, sorted_clusters)
return [cluster for cluster in sorted_clusters if cluster.is_valid]
def _generate_topic_models_multiproc(ensemble, num_models, ensemble_workers):
"""Generate the topic models to form the ensemble in a multiprocessed way.
Depending on the used topic model this can result in a speedup.
Parameters
----------
ensemble: EnsembleLda
the ensemble
num_models : int
how many models to train in the ensemble
ensemble_workers : int
into how many processes to split the models will be set to max(workers, num_models), to avoid workers that
are supposed to train 0 models.
to get maximum performance, set to the number of your cores, if non-parallelized models are being used in
the ensemble (LdaModel).
For LdaMulticore, the performance gain is small and gets larger for a significantly smaller corpus.
In that case, ensemble_workers=2 can be used.
"""
# the way random_states is handled needs to prevent getting different results when multiprocessing is on,
# or getting the same results in every lda children. so it is solved by generating a list of state seeds before
# multiprocessing is started.
random_states = [ensemble.random_state.randint(_MAX_RANDOM_STATE) for _ in range(num_models)]
# each worker has to work on at least one model.
# Don't spawn idle workers:
workers = min(ensemble_workers, num_models)
# create worker processes:
# from what I know this is basically forking with a jump to a target function in each child
# so modifying the ensemble object will not modify the one in the parent because of no shared memory
processes = []
pipes = []
num_models_unhandled = num_models # how many more models need to be trained by workers?
for i in range(workers):
parent_conn, child_conn = Pipe()
num_subprocess_models = 0
if i == workers - 1: # i is a index, hence -1
# is this the last worker that needs to be created?
# then task that worker with all the remaining models
num_subprocess_models = num_models_unhandled
else:
num_subprocess_models = int(num_models_unhandled / (workers - i))
# get the chunk from the random states that is meant to be for those models
random_states_for_worker = random_states[-num_models_unhandled:][:num_subprocess_models]
args = (ensemble, num_subprocess_models, random_states_for_worker, child_conn)
try:
process = Process(target=_generate_topic_models_worker, args=args)
processes.append(process)
pipes.append((parent_conn, child_conn))
process.start()
num_models_unhandled -= num_subprocess_models
except ProcessError:
logger.error(f"could not start process {i}")
_teardown(pipes, processes)
raise
# aggregate results
# will also block until workers are finished
for parent_conn, _ in pipes:
answer = parent_conn.recv()
parent_conn.close()
# this does basically the same as the _generate_topic_models function (concatenate all the ttdas):
if not ensemble.memory_friendly_ttda:
ensemble.tms += answer
ttda = np.concatenate([m.get_topics() for m in answer])
else:
ttda = answer
ensemble.ttda = np.concatenate([ensemble.ttda, ttda])
for process in processes:
process.terminate()
def _generate_topic_models(ensemble, num_models, random_states=None):
"""Train the topic models that form the ensemble.
Parameters
----------
ensemble: EnsembleLda
the ensemble
num_models : int
number of models to be generated
random_states : list
list of numbers or np.random.RandomState objects. Will be autogenerated based on the ensembles
RandomState if None (default).
"""
if random_states is None:
random_states = [ensemble.random_state.randint(_MAX_RANDOM_STATE) for _ in range(num_models)]
assert len(random_states) == num_models
kwargs = ensemble.gensim_kw_args.copy()
tm = None # remember one of the topic models from the following
# loop, in order to collect some properties from it afterwards.
for i in range(num_models):
kwargs["random_state"] = random_states[i]
tm = ensemble.get_topic_model_class()(**kwargs)
# adds the lambda (that is the unnormalized get_topics) to ttda, which is
# a list of all those lambdas
ensemble.ttda = np.concatenate([ensemble.ttda, tm.get_topics()])
# only saves the model if it is not "memory friendly"
if not ensemble.memory_friendly_ttda:
ensemble.tms += [tm]
# use one of the tms to get some info that will be needed later
ensemble.sstats_sum = tm.state.sstats.sum()
ensemble.eta = tm.eta
def _generate_topic_models_worker(ensemble, num_models, random_states, pipe):
"""Wrapper for _generate_topic_models to write the results into a pipe.
This is intended to be used inside a subprocess."""
#
# Same as _generate_topic_models, but runs in a separate subprocess, and
# sends the updated ensemble state to the parent subprocess via a pipe.
#
logger.info(f"spawned worker to generate {num_models} topic models")
_generate_topic_models(ensemble=ensemble, num_models=num_models, random_states=random_states)
# send the ttda that is in the child/workers version of the memory into the pipe
# available, after _generate_topic_models has been called in the worker
if ensemble.memory_friendly_ttda:
# remember that this code is inside the worker processes memory,
# so self.ttda is the ttda of only a chunk of models
pipe.send(ensemble.ttda)
else:
pipe.send(ensemble.tms)
pipe.close()
def _calculate_asymmetric_distance_matrix_chunk(
ttda1,
ttda2,
start_index,
masking_method,
masking_threshold,
):
"""Calculate an (asymmetric) distance from each topic in ``ttda1`` to each topic in ``ttda2``.
Parameters
----------
ttda1 and ttda2: 2D arrays of floats
Two ttda matrices that are going to be used for distance calculation. Each row in ttda corresponds to one
topic. Each cell in the resulting matrix corresponds to the distance between a topic pair.
start_index : int
this function might be used in multiprocessing, so start_index has to be set as ttda1 is a chunk of the
complete ttda in that case. start_index would be 0 if ``ttda1 == self.ttda``. When self.ttda is split into
two pieces, each 100 ttdas long, then start_index should be be 100. default is 0
masking_method: function
masking_threshold: float
Returns
-------
2D numpy.ndarray of floats
Asymmetric distance matrix of size ``len(ttda1)`` by ``len(ttda2)``.
"""
# initialize the distance matrix. ndarray is faster than zeros
distances = np.ndarray((len(ttda1), len(ttda2)))
if ttda1.shape[0] > 0 and ttda2.shape[0] > 0:
# the worker might not have received a ttda because it was chunked up too much
# some help to find a better threshold by useful log messages
avg_mask_size = 0
# now iterate over each topic
for ttd1_idx, ttd1 in enumerate(ttda1):
# create mask from ttd1 that removes noise from a and keeps the largest terms
mask = masking_method(ttd1, masking_threshold)
ttd1_masked = ttd1[mask]
avg_mask_size += mask.sum()
# now look at every possible pair for topic a:
for ttd2_idx, ttd2 in enumerate(ttda2):
# distance to itself is 0
if ttd1_idx + start_index == ttd2_idx:
distances[ttd1_idx][ttd2_idx] = 0
continue
# now mask b based on a, which will force the shape of a onto b
ttd2_masked = ttd2[mask]
# Smart distance calculation avoids calculating cosine distance for highly masked topic-term
# distributions that will have distance values near 1.
if ttd2_masked.sum() <= _COSINE_DISTANCE_CALCULATION_THRESHOLD:
distance = 1
else:
distance = cosine(ttd1_masked, ttd2_masked)
distances[ttd1_idx][ttd2_idx] = distance
percent = round(100 * avg_mask_size / ttda1.shape[0] / ttda1.shape[1], 1)
logger.info(f'the given threshold of {masking_threshold} covered on average {percent}% of tokens')
return distances
def _asymmetric_distance_matrix_worker(
worker_id,
entire_ttda,
ttdas_sent,
n_ttdas,
masking_method,
masking_threshold,
pipe,
):
"""Worker that computes the distance to all other nodes from a chunk of nodes."""
logger.info(f"spawned worker {worker_id} to generate {n_ttdas} rows of the asymmetric distance matrix")
# the chunk of ttda that's going to be calculated:
ttda1 = entire_ttda[ttdas_sent:ttdas_sent + n_ttdas]
distance_chunk = _calculate_asymmetric_distance_matrix_chunk(
ttda1=ttda1,
ttda2=entire_ttda,
start_index=ttdas_sent,
masking_method=masking_method,
masking_threshold=masking_threshold,
)
pipe.send((worker_id, distance_chunk)) # remember that this code is inside the workers memory
pipe.close()
def _calculate_assymetric_distance_matrix_multiproc(
workers,
entire_ttda,
masking_method,
masking_threshold,
):
processes = []
pipes = []
ttdas_sent = 0
for i in range(workers):
try:
parent_conn, child_conn = Pipe()
# Load Balancing, for example if there are 9 ttdas and 4 workers, the load will be balanced 2, 2, 2, 3.
n_ttdas = 0
if i == workers - 1: # i is a index, hence -1
# is this the last worker that needs to be created?
# then task that worker with all the remaining models
n_ttdas = len(entire_ttda) - ttdas_sent
else:
n_ttdas = int((len(entire_ttda) - ttdas_sent) / (workers - i))
args = (i, entire_ttda, ttdas_sent, n_ttdas, masking_method, masking_threshold, child_conn)
process = Process(target=_asymmetric_distance_matrix_worker, args=args)
ttdas_sent += n_ttdas
processes.append(process)
pipes.append((parent_conn, child_conn))
process.start()
except ProcessError:
logger.error(f"could not start process {i}")
_teardown(pipes, processes)
raise
distances = []
# note, that the following loop maintains order in how the ttda will be concatenated
# which is very important. Ordering in ttda has to be the same as when using only one process
for parent_conn, _ in pipes:
worker_id, distance_chunk = parent_conn.recv()
parent_conn.close() # child conn will be closed from inside the worker
# this does basically the same as the _generate_topic_models function (concatenate all the ttdas):
distances.append(distance_chunk)
for process in processes:
process.terminate()
return np.concatenate(distances)
| Cluster |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance18.py | {
"start": 267,
"end": 507
} | class ____(NamedTuple, Generic[T]):
pass
def func1(val: NT1[str] | tuple[int, int]):
if isinstance(val, NT1):
reveal_type(val, expected_text="NT1[str]")
else:
reveal_type(val, expected_text="tuple[int, int]")
| NT1 |
python | catalyst-team__catalyst | examples/catalyst_rl/ddpg.py | {
"start": 3407,
"end": 10878
} | class ____(dl.Runner):
def __init__(
self,
*,
gamma: float,
tau: float,
tau_period: int = 1,
actor_key: str = "actor",
critic_key: str = "critic",
target_actor_key: str = "target_actor",
target_critic_key: str = "target_critic",
actor_optimizer_key: str = "actor",
critic_optimizer_key: str = "critic",
**kwargs,
):
super().__init__(**kwargs)
self.gamma = gamma
self.tau = tau
self.tau_period = tau_period
self.actor_key: str = actor_key
self.critic_key: str = critic_key
self.target_actor_key: str = target_actor_key
self.target_critic_key: str = target_critic_key
self.actor_optimizer_key: str = actor_optimizer_key
self.critic_optimizer_key: str = critic_optimizer_key
self.actor: nn.Module = None
self.critic: nn.Module = None
self.target_actor: nn.Module = None
self.target_critic: nn.Module = None
self.actor_optimizer: nn.Module = None
self.critic_optimizer: nn.Module = None
def on_experiment_start(self, runner: dl.IRunner):
super().on_experiment_start(runner)
self.actor = self.model[self.actor_key]
self.critic = self.model[self.critic_key]
self.target_actor = self.model[self.target_actor_key]
self.target_critic = self.model[self.target_critic_key]
soft_update(self.target_actor, self.actor, 1.0)
soft_update(self.target_critic, self.critic, 1.0)
self.actor_optimizer = self.optimizer[self.actor_optimizer_key]
self.critic_optimizer = self.optimizer[self.critic_optimizer_key]
def on_loader_start(self, runner: dl.IRunner):
super().on_loader_start(runner)
self.meters = {
key: metrics.AdditiveMetric(compute_on_call=False)
for key in ["critic_loss", "actor_loss"]
}
def handle_batch(self, batch: Sequence[torch.Tensor]):
# model train/valid step
# states, actions, rewards, dones, next_states = batch
states, actions, rewards, next_states, dones = (
batch["state"].squeeze_(1).to(torch.float32),
batch["action"].to(torch.float32),
batch["reward"].to(torch.float32),
batch["next_state"].squeeze_(1).to(torch.float32),
batch["done"].to(torch.bool),
)
# get actions for the current state
pred_actions = self.actor(states)
# get q-values for the actions in current states
pred_critic_states = torch.cat([states, pred_actions], 1)
# use q-values to train the actor model
policy_loss = (-self.critic(pred_critic_states)).mean()
with torch.no_grad():
# get possible actions for the next states
next_state_actions = self.target_actor(next_states)
# get possible q-values for the next actions
next_critic_states = torch.cat([next_states, next_state_actions], 1)
next_state_values = self.target_critic(next_critic_states).detach().squeeze()
next_state_values[dones] = 0.0
# compute Bellman's equation value
target_state_values = next_state_values * self.gamma + rewards
# compute predicted values
critic_states = torch.cat([states, actions], 1)
state_values = self.critic(critic_states).squeeze()
# train the critic model
value_loss = self.criterion(state_values, target_state_values.detach())
self.batch_metrics.update({"critic_loss": value_loss, "actor_loss": policy_loss})
for key in ["critic_loss", "actor_loss"]:
self.meters[key].update(self.batch_metrics[key].item(), self.batch_size)
if self.is_train_loader:
self.actor.zero_grad()
self.actor_optimizer.zero_grad()
policy_self.engine.backward(loss)
self.actor_optimizer.step()
self.critic.zero_grad()
self.critic_optimizer.zero_grad()
value_self.engine.backward(loss)
self.critic_optimizer.step()
if self.batch_step % self.tau_period == 0:
soft_update(self.target_actor, self.actor, self.tau)
soft_update(self.target_critic, self.critic, self.tau)
def on_loader_end(self, runner: dl.IRunner):
for key in ["critic_loss", "actor_loss"]:
self.loader_metrics[key] = self.meters[key].compute()[0]
super().on_loader_end(runner)
if __name__ == "__main__":
# data
num_samplers = 2
batch_size = 256
epoch_size = int(1e2) * batch_size
buffer_size = int(1e5)
# runner settings, ~training
gamma = 0.99
tau = 0.01
tau_period = 1
# optimization
lr_actor = 1e-4
lr_critic = 1e-3
db_server = RedisDB()
# You can change game
# env_name = "LunarLanderContinuous-v2"
env_name = "Pendulum-v0"
env = NormalizedActions(gym.make(env_name))
replay_buffer = OffpolicyReplayBuffer(
observation_space=env.observation_space,
action_space=env.action_space,
epoch_len=epoch_size,
capacity=buffer_size,
n_step=1,
gamma=gamma,
history_len=1,
)
actor, target_actor = get_network_actor(env), get_network_actor(env)
critic, target_critic = get_network_critic(env), get_network_critic(env)
set_requires_grad(target_actor, requires_grad=False)
set_requires_grad(target_critic, requires_grad=False)
models = nn.ModuleDict(
{
"actor": actor,
"critic": critic,
"target_actor": target_actor,
"target_critic": target_critic,
}
)
criterion = torch.nn.MSELoss()
optimizer = {
"actor": torch.optim.Adam(actor.parameters(), lr_actor),
"critic": torch.optim.Adam(critic.parameters(), lr=lr_critic),
}
loaders = {"train_game": DataLoader(replay_buffer, batch_size=batch_size)}
runner = CustomRunner(gamma=gamma, tau=tau, tau_period=tau_period)
runner.train(
# for simplicity reasons, let's run everything on single gpu
engine=dl.GPUEngine(),
model=models,
criterion=criterion,
optimizer=optimizer,
loaders=loaders,
logdir="./logs_ddpg",
num_epochs=50,
verbose=True,
valid_loader="_epoch_",
valid_metric="reward",
minimize_valid_metric=False,
load_best_on_end=True,
callbacks=[
GameCallback(
sampler_fn=Sampler,
env=env,
replay_buffer=replay_buffer,
db_server=db_server,
actor_key="actor",
num_samplers=num_samplers,
min_transactions_num=epoch_size,
)
],
)
# env = gym.wrappers.Monitor(gym.make(env_name), directory="videos_ddpg", force=True)
# generate_sessions(env=env, network=runner.model["actor"], num_sessions=100)
# env.close()
# # show video
# from IPython.display import HTML
# import os
#
# video_names = list(filter(lambda s: s.endswith(".mp4"), os.listdir("./videos_ddpg/")))
#
# HTML("""
# <video width="640" height="480" controls>
# <source src="{}" type="video/mp4">
# </video>
# """.format("./videos/" + video_names[-1]))
# # this may or may not be _last_ video. Try other indices
| CustomRunner |
python | pytorch__pytorch | test/dynamo/test_fx_graph_runnable.py | {
"start": 3133,
"end": 13132
} | class ____(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
torch._logging.structured.INTERN_TABLE.clear()
self.old_level = trace_log.level
trace_log.setLevel(logging.DEBUG)
# Create a custom filter specifically for fx_graph_runnable entries
self.filter = FxGraphRunnableArtifactFilter()
# Create a separate buffer and handler for capturing fx_graph_runnable entries
self.buffer = io.StringIO()
self.handler = logging.StreamHandler(self.buffer)
self.handler.setFormatter(StructuredTracePayloadFormatter())
self.handler.addFilter(self.filter)
trace_log.addHandler(self.handler)
def tearDown(self):
trace_log.removeHandler(self.handler)
trace_log.setLevel(self.old_level)
def _exec_and_verify_payload(self):
# Write captured payload & run it in a fresh Python process
payload = self.buffer.getvalue().strip()
self.assertTrue(payload, "Expected fx_graph_runnable payload but got nothing")
self.assertIn("def forward", payload) # sanity-check for actual FX code
with WritableTempFile("w", suffix=".py") as tmp:
tmp.write(payload)
tmp.flush()
res = subprocess.run(
[sys.executable, tmp.name], capture_output=True, text=True, timeout=30
)
self.assertEqual(
res.returncode,
0,
f"Standalone fx_graph_runnable failed:\nSTDERR:\n{res.stderr}",
)
# basic tests
def test_basic_tensor_add(self):
def f(x):
return x + 1
torch.compile(f)(torch.randn(4))
self._exec_and_verify_payload()
@unittest.skipUnless(has_triton(), "Triton not available")
def test_user_defined_triton_kernel_autotune(self):
def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
output = torch.ones(x.shape, device=x.device, dtype=x.dtype)
n_elements = output.numel()
def grid(
meta,
):
return (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
add_kernel_autotune[grid](x, y, output, n_elements)
return output
x = torch.ones((4096,), device=GPU_TYPE, dtype=torch.float16)
y = torch.ones((4096,), device=GPU_TYPE, dtype=torch.float16)
torch.compile(add)(x, y)
self._exec_and_verify_payload()
@unittest.skipUnless(has_triton(), "Triton not available")
@requires_gpu
def test_user_defined_triton_kernel(self):
def add(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
output = torch.ones(x.shape, device=x.device, dtype=x.dtype)
n_elements = x.numel()
add_kernel[n_elements,](x, y, output, n_elements, BLOCK_SIZE=4)
return output
x = torch.ones((4096,), device=GPU_TYPE, dtype=torch.float16)
y = torch.ones((4096,), device=GPU_TYPE, dtype=torch.float16)
torch.compile(add)(x, y)
self._exec_and_verify_payload()
def test_two_inputs_matmul(self):
def f(a, b):
return (a @ b).relu()
a, b = torch.randn(2, 3), torch.randn(3, 4)
torch.compile(f)(a, b)
self._exec_and_verify_payload()
def test_scalar_multiply(self):
def f(x):
return x * 2
torch.compile(f)(torch.randn(5))
self._exec_and_verify_payload()
# testing dynamic shapes
def test_dynamic_shapes_run(self):
def f(x):
return (x @ x.transpose(0, 1)).relu()
a = torch.randn(10, 12)
torch._dynamo.mark_dynamic(a, 0)
torch._dynamo.mark_dynamic(a, 1)
torch.compile(f)(a)
self._exec_and_verify_payload()
def test_broadcast_add_dynamic(self):
def f(x, y):
return x + y * 2
x = torch.randn(5, 1)
y = torch.randn(1, 8)
torch._dynamo.mark_dynamic(x, 0)
torch._dynamo.mark_dynamic(y, 1)
torch.compile(f)(x, y)
self._exec_and_verify_payload()
def test_toy_model_basic(self):
model = ToyModel(input_size=8, hidden_size=16, output_size=4)
model.eval() # Set to eval mode to avoid dropout randomness
x = torch.randn(3, 8)
torch.compile(model)(x)
self._exec_and_verify_payload()
def test_toy_model_batch_processing(self):
model = ToyModel(input_size=12, hidden_size=24, output_size=6)
model.eval()
x = torch.randn(16, 12)
torch.compile(model)(x)
self._exec_and_verify_payload()
def test_toy_model_dynamic_batch(self):
model = ToyModel(input_size=10, hidden_size=20, output_size=5)
model.eval()
x = torch.randn(7, 10)
torch._dynamo.mark_dynamic(x, 0)
torch.compile(model)(x)
self._exec_and_verify_payload()
# Distributed collectives tests with FakeProcessGroup
@unittest.skipIf(
not torch.distributed.is_available(), "Torch distributed not available."
)
@unittest.skipIf(IS_FBCODE or IS_SANDCASTLE, "Skip in fbcode/sandcastle")
def test_all_reduce_collective(self):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
def f(x):
dist.all_reduce(x)
return x * 2
try:
x = torch.randn(4, 4)
torch.compile(f)(x)
finally:
dist.destroy_process_group()
self._exec_and_verify_payload()
@unittest.skipIf(
not torch.distributed.is_available(), "Torch distributed not available."
)
@unittest.skipIf(IS_FBCODE or IS_SANDCASTLE, "Skip in fbcode/sandcastle")
def test_all_gather_collective(self):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
def f(x):
output_tensors = [torch.empty_like(x) for _ in range(2)]
dist.all_gather(output_tensors, x)
return output_tensors[0] + output_tensors[1]
try:
x = torch.randn(3, 3)
torch.compile(f)(x)
finally:
dist.destroy_process_group()
self._exec_and_verify_payload()
@unittest.skipIf(
not torch.distributed.is_available(), "Torch distributed not available."
)
@unittest.skipIf(IS_FBCODE or IS_SANDCASTLE, "Skip in fbcode/sandcastle")
def test_broadcast_collective(self):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
def f(x):
dist.broadcast(x, src=0)
return x.sum()
try:
x = torch.randn(5, 5)
torch.compile(f)(x)
finally:
dist.destroy_process_group()
self._exec_and_verify_payload()
@unittest.skipIf(
not torch.distributed.is_available(), "Torch distributed not available."
)
@unittest.skipIf(IS_FBCODE or IS_SANDCASTLE, "Skip in fbcode/sandcastle")
def test_reduce_scatter_collective(self):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
def f(x):
input_list = [x, x.clone()]
output = torch.empty_like(x)
dist.reduce_scatter(output, input_list)
return output
try:
x = torch.randn(4, 4)
torch.compile(f)(x)
finally:
dist.destroy_process_group()
self._exec_and_verify_payload()
@unittest.skipIf(
not torch.distributed.is_available(), "Torch distributed not available"
)
@unittest.skipIf(IS_FBCODE or IS_SANDCASTLE, "Skip in fbcode/sandcastle")
def test_dtensor_compile_redistribute(self):
store = FakeStore()
dist.init_process_group(backend="fake", rank=0, world_size=2, store=store)
mesh = DeviceMesh("cpu", list(range(2)))
def f(x, y):
dt = DTensor.from_local(x.reshape(2, 4), mesh, [Shard(0)], run_check=False)
dt2 = DTensor.from_local(y.reshape(4, 2), mesh, [Shard(1)], run_check=False)
dt_out = torch.matmul(dt, dt2)
dt_out_redistribute = dt_out.redistribute(mesh, [Replicate()])
return dt_out_redistribute.to_local()
try:
x = torch.arange(8, dtype=torch.float32)
y = torch.arange(8, dtype=torch.float32)
torch.compile(f)(x, y)
finally:
dist.destroy_process_group()
self._exec_and_verify_payload()
def test_metrics_context(self):
"""
When TORCH_COMPILE_DEBUG is set, provenance_tracking_level is set to 1, and
the generated fx_graph_runnable crashed with,
RuntimeError: Cannot add inductor_provenance outside of a MetricsContext
"""
import torch._inductor.config as inductor_config
def f(x):
return x * 2 + 1
# Enable provenance tracking to trigger the code path that adds metrics
with inductor_config.patch(
{"trace.enabled": True, "trace.provenance_tracking_level": 1}
):
x = torch.randn(4, 4)
torch.compile(f)(x)
self._exec_and_verify_payload()
@torch._dynamo.config.patch(assume_static_by_default=False)
def test_dynamic_expression(self):
"""
Test not emitting something like "s27*s53**2 = 36"
"""
def f(x):
return torch.ops.aten._adaptive_avg_pool2d(
x, (6, 6)
), torch.ops.aten._adaptive_avg_pool2d(x + 1, (2, 5))
x = torch.randn(2, 4, 16, 16)
torch.compile(f)(x)
self._exec_and_verify_payload()
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
if not (IS_FBCODE or IS_SANDCASTLE):
# fbcode complains about not being able to find torch in subprocess
run_tests()
| FxGraphRunnableTest |
python | huggingface__transformers | tests/models/chinese_clip/test_processing_chinese_clip.py | {
"start": 968,
"end": 2485
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = ChineseCLIPProcessor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
vocab_tokens = [
"[UNK]",
"[CLS]",
"[SEP]",
"[PAD]",
"[MASK]",
"的",
"价",
"格",
"是",
"15",
"便",
"alex",
"##andra",
",",
"。",
"-",
"t",
"shirt",
]
vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
with open(vocab_file, "w", encoding="utf-8") as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
return tokenizer_class(vocab_file=vocab_file)
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
image_processor_map = {
"do_resize": True,
"size": {"height": 224, "width": 224},
"do_center_crop": True,
"crop_size": {"height": 18, "width": 18},
"do_normalize": True,
"image_mean": [0.48145466, 0.4578275, 0.40821073],
"image_std": [0.26862954, 0.26130258, 0.27577711],
"do_convert_rgb": True,
}
return image_processor_class(**image_processor_map)
| ChineseCLIPProcessorTest |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_collection.py | {
"start": 13275,
"end": 41068
} | class ____:
"""Tests centred around the ``update_dag_parsing_results_in_db`` function."""
@pytest.fixture
def clean_db(self, session):
yield
clear_db_serialized_dags()
clear_db_dags()
clear_db_import_errors()
@pytest.fixture(name="dag_import_error_listener")
def _dag_import_error_listener(self):
from unit.listeners import dag_import_error_listener
get_listener_manager().add_listener(dag_import_error_listener)
yield dag_import_error_listener
get_listener_manager().clear()
dag_import_error_listener.clear()
@mark_fab_auth_manager_test
@pytest.mark.usefixtures("clean_db") # sync_perms in fab has bad session commit hygiene
def test_sync_perms_syncs_dag_specific_perms_on_update(
self, monkeypatch, spy_agency: SpyAgency, session, time_machine, testing_dag_bundle
):
"""Test DAG-specific permissions are synced when a DAG is new or updated"""
from airflow import settings
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 0
monkeypatch.setattr(settings, "MIN_SERIALIZED_DAG_UPDATE_INTERVAL", 5)
time_machine.move_to(tz.datetime(2020, 1, 5, 0, 0, 0), tick=False)
dag = DAG(dag_id="test")
sync_perms_spy = spy_agency.spy_on(
airflow.dag_processing.collection._sync_dag_perms,
call_original=False,
)
def _sync_to_db():
sync_perms_spy.reset_calls()
time_machine.shift(20)
update_dag_parsing_results_in_db("testing", None, [dag], dict(), None, set(), session)
_sync_to_db()
spy_agency.assert_spy_called_with(sync_perms_spy, dag, session=session)
# DAG isn't updated
_sync_to_db()
# `_sync_dag_perms` should be called even the DAG isn't updated. Otherwise, any import error will not show up until DAG is updated.
spy_agency.assert_spy_called_with(sync_perms_spy, dag, session=session)
# DAG is updated
dag.tags = {"new_tag"}
_sync_to_db()
spy_agency.assert_spy_called_with(sync_perms_spy, dag, session=session)
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
@patch.object(SerializedDagModel, "write_dag")
@patch("airflow.serialization.serialized_objects.SerializedDAG.bulk_write_to_db")
def test_sync_to_db_is_retried(
self, mock_bulk_write_to_db, mock_s10n_write_dag, testing_dag_bundle, session
):
"""Test that important DB operations in db sync are retried on OperationalError"""
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 0
mock_dag = mock.MagicMock()
dags = [mock_dag]
op_error = OperationalError(statement=mock.ANY, params=mock.ANY, orig=mock.ANY)
# Mock error for the first 2 tries and a successful third try
side_effect = [op_error, op_error, mock.ANY]
mock_bulk_write_to_db.side_effect = side_effect
mock_session = mock.MagicMock()
update_dag_parsing_results_in_db(
"testing",
None,
dags=dags,
import_errors={},
parse_duration=None,
warnings=set(),
session=mock_session,
)
# Test that 3 attempts were made to run 'DAG.bulk_write_to_db' successfully
mock_bulk_write_to_db.assert_has_calls(
[
mock.call("testing", None, mock.ANY, None, session=mock.ANY),
mock.call("testing", None, mock.ANY, None, session=mock.ANY),
mock.call("testing", None, mock.ANY, None, session=mock.ANY),
]
)
# Assert that rollback is called twice (i.e. whenever OperationalError occurs)
mock_session.rollback.assert_has_calls([mock.call(), mock.call()])
# Check that 'SerializedDagModel.write_dag' is also called
# Only called once since the other two times the 'DAG.bulk_write_to_db' error'd
# and the session was roll-backed before even reaching 'SerializedDagModel.write_dag'
mock_s10n_write_dag.assert_has_calls(
[
mock.call(
mock_dag,
bundle_name="testing",
bundle_version=None,
min_update_interval=mock.ANY,
session=mock_session,
),
]
)
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 0
def test_serialized_dags_are_written_to_db_on_sync(self, testing_dag_bundle, session):
"""Test DAGs are Serialized and written to DB when parsing result is updated"""
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 0
dag = DAG(dag_id="test")
update_dag_parsing_results_in_db(
bundle_name="testing",
bundle_version=None,
dags=[LazyDeserializedDAG.from_dag(dag)],
import_errors={},
parse_duration=None,
warnings=set(),
session=session,
)
new_serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert new_serialized_dags_count == 1
def test_parse_time_written_to_db_on_sync(self, testing_dag_bundle, session):
"""Test that the parse time is correctly written to the DB after parsing"""
parse_duration = 1.25
dag = DAG(dag_id="test")
update_dag_parsing_results_in_db("testing", None, [dag], dict(), parse_duration, set(), session)
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
assert dag_model.last_parse_duration == parse_duration
@patch.object(ParseImportError, "full_file_path")
@patch.object(SerializedDagModel, "write_dag")
@pytest.mark.usefixtures("clean_db")
def test_serialized_dag_errors_are_import_errors(
self, mock_serialize, mock_full_path, caplog, session, dag_import_error_listener, testing_dag_bundle
):
"""
Test that errors serializing a DAG are recorded as import_errors in the DB
"""
mock_serialize.side_effect = SerializationError
caplog.set_level(logging.ERROR)
dag = DAG(dag_id="test")
dag.fileloc = "abc.py"
dag.relative_fileloc = "abc.py"
mock_full_path.return_value = "abc.py"
import_errors = {}
update_dag_parsing_results_in_db(
"testing", None, [dag], import_errors, None, set(), session, files_parsed={("testing", "abc.py")}
)
assert "SerializationError" in caplog.text
# Should have been edited in place
err = import_errors.get(("testing", dag.relative_fileloc))
assert "SerializationError" in err
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
assert dag_model.has_import_errors is True
import_errors = session.query(ParseImportError).all()
assert len(import_errors) == 1
import_error = import_errors[0]
assert import_error.filename == dag.relative_fileloc
assert "SerializationError" in import_error.stacktrace
# Ensure the listener was notified
assert len(dag_import_error_listener.new) == 1
assert len(dag_import_error_listener.existing) == 0
assert dag_import_error_listener.new["abc.py"] == import_error.stacktrace
@patch.object(ParseImportError, "full_file_path")
@mark_fab_auth_manager_test
@pytest.mark.usefixtures("clean_db")
def test_import_error_persist_for_invalid_access_control_role(
self,
mock_full_path,
monkeypatch,
dag_maker,
session,
time_machine,
dag_import_error_listener,
testing_dag_bundle,
):
"""
Test that import errors related to invalid access control role are tracked in the DB until being fixed.
"""
from airflow import settings
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 0
monkeypatch.setattr(settings, "MIN_SERIALIZED_DAG_UPDATE_INTERVAL", 5)
time_machine.move_to(tz.datetime(2020, 1, 5, 0, 0, 0), tick=False)
# create a DAG and assign it a non-exist role.
with dag_maker(
dag_id="test_nonexist_access_control",
access_control={
"non_existing_role": {"can_edit", "can_read", "can_delete"},
},
) as dag:
pass
dag.fileloc = "test_nonexist_access_control.py"
dag.relative_fileloc = "test_nonexist_access_control.py"
mock_full_path.return_value = "test_nonexist_access_control.py"
# the DAG processor should raise an import error when processing the DAG above.
import_errors = {}
# run the DAG parsing.
update_dag_parsing_results_in_db("testing", None, [dag], import_errors, None, set(), session)
# expect to get an error with "role does not exist" message.
err = import_errors.get(("testing", dag.relative_fileloc))
assert "AirflowException" in err
assert "role does not exist" in err
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
# the DAG should contain an import error.
assert dag_model.has_import_errors is True
prev_import_errors = session.query(ParseImportError).all()
# the import error message should match.
assert len(prev_import_errors) == 1
prev_import_error = prev_import_errors[0]
assert prev_import_error.filename == dag.relative_fileloc
assert "AirflowException" in prev_import_error.stacktrace
assert "role does not exist" in prev_import_error.stacktrace
# this is a new import error.
assert len(dag_import_error_listener.new) == 1
assert len(dag_import_error_listener.existing) == 0
assert (
dag_import_error_listener.new["test_nonexist_access_control.py"] == prev_import_error.stacktrace
)
# the DAG is serialized into the DB.
serialized_dags_count = session.query(func.count(SerializedDagModel.dag_id)).scalar()
assert serialized_dags_count == 1
# run the update again. Even though the DAG is not updated, the processor should raise import error since the access control is not fixed.
time_machine.move_to(tz.datetime(2020, 1, 5, 0, 0, 5), tick=False)
update_dag_parsing_results_in_db("testing", None, [dag], dict(), None, set(), session)
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
# the DAG should contain an import error.
assert dag_model.has_import_errors is True
import_errors = session.query(ParseImportError).all()
# the import error should still in the DB.
assert len(import_errors) == 1
import_error = import_errors[0]
assert import_error.filename == dag.relative_fileloc
assert "AirflowException" in import_error.stacktrace
assert "role does not exist" in import_error.stacktrace
# the new import error should be the same as the previous one
assert len(import_errors) == len(prev_import_errors)
assert import_error.filename == prev_import_error.filename
assert import_error.filename == dag.relative_fileloc
assert import_error.stacktrace == prev_import_error.stacktrace
# there is a new error and an existing error.
assert len(dag_import_error_listener.new) == 1
assert len(dag_import_error_listener.existing) == 1
assert (
dag_import_error_listener.new["test_nonexist_access_control.py"] == prev_import_error.stacktrace
)
# run the update again, but the incorrect access control configuration is removed.
time_machine.move_to(tz.datetime(2020, 1, 5, 0, 0, 10), tick=False)
dag.access_control = None
update_dag_parsing_results_in_db("testing", None, [dag], dict(), None, set(), session)
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
# the import error should be cleared.
assert dag_model.has_import_errors is False
import_errors = session.query(ParseImportError).all()
# the import error should be cleared.
assert len(import_errors) == 0
# no import error should be introduced.
assert len(dag_import_error_listener.new) == 1
assert len(dag_import_error_listener.existing) == 1
@patch.object(ParseImportError, "full_file_path")
@pytest.mark.usefixtures("clean_db")
def test_new_import_error_replaces_old(
self, mock_full_file_path, session, dag_import_error_listener, testing_dag_bundle
):
"""
Test that existing import error is updated and new record not created
for a dag with the same filename
"""
bundle_name = "testing"
filename = "abc.py"
mock_full_file_path.return_value = filename
prev_error = ParseImportError(
filename=filename,
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
session.add(prev_error)
session.flush()
prev_error_id = prev_error.id
update_dag_parsing_results_in_db(
bundle_name=bundle_name,
bundle_version=None,
dags=[],
import_errors={("testing", "abc.py"): "New error"},
parse_duration=None,
warnings=set(),
session=session,
files_parsed={("testing", "abc.py")},
)
import_error = (
session.query(ParseImportError)
.filter(ParseImportError.filename == filename, ParseImportError.bundle_name == bundle_name)
.one()
)
# assert that the ID of the import error did not change
assert import_error.id == prev_error_id
assert import_error.stacktrace == "New error"
# Ensure the listener was notified
assert len(dag_import_error_listener.new) == 0
assert len(dag_import_error_listener.existing) == 1
assert dag_import_error_listener.existing["abc.py"] == prev_error.stacktrace
@pytest.mark.usefixtures("clean_db")
def test_remove_error_clears_import_error(self, testing_dag_bundle, session):
# Pre-condition: there is an import error for the dag file
bundle_name = "testing"
filename = "abc.py"
prev_error = ParseImportError(
filename=filename,
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
session.add(prev_error)
# And one for another file we haven't been given results for -- this shouldn't be deleted
session.add(
ParseImportError(
filename="def.py",
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
)
session.flush()
# Sanity check of pre-condition
import_errors = set(session.execute(select(ParseImportError.filename, ParseImportError.bundle_name)))
assert import_errors == {("abc.py", bundle_name), ("def.py", bundle_name)}
dag = DAG(dag_id="test")
dag.fileloc = filename
dag.relative_fileloc = filename
import_errors = {}
update_dag_parsing_results_in_db(
bundle_name,
bundle_version=None,
dags=[LazyDeserializedDAG.from_dag(dag)],
import_errors=dict.fromkeys(import_errors),
parse_duration=None,
warnings=set(),
session=session,
files_parsed={(bundle_name, "abc.py")},
)
dag_model: DagModel = session.get(DagModel, (dag.dag_id,))
assert dag_model.has_import_errors is False
import_errors = set(session.execute(select(ParseImportError.filename, ParseImportError.bundle_name)))
assert import_errors == {("def.py", bundle_name)}
@pytest.mark.usefixtures("clean_db")
def test_remove_error_updates_loaded_dag_model(self, testing_dag_bundle, session):
bundle_name = "testing"
filename = "abc.py"
session.add(
ParseImportError(
filename=filename,
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
)
session.add(
ParseImportError(
filename="def.py",
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
)
session.flush()
dag = DAG(dag_id="test")
dag.fileloc = filename
dag.relative_fileloc = filename
lazy_deserialized_dags = [LazyDeserializedDAG.from_dag(dag)]
import_errors = {(bundle_name, filename): "Some error"}
update_dag_parsing_results_in_db(
bundle_name,
bundle_version=None,
dags=lazy_deserialized_dags,
import_errors=import_errors,
parse_duration=None,
warnings=set(),
session=session,
files_parsed={(bundle_name, "abc.py")},
)
dag_model = session.get(DagModel, (dag.dag_id,))
assert dag_model.has_import_errors is True
import_errors = {}
update_dag_parsing_results_in_db(
bundle_name,
bundle_version=None,
dags=lazy_deserialized_dags,
import_errors=import_errors,
parse_duration=None,
warnings=set(),
session=session,
)
assert dag_model.has_import_errors is False
@pytest.mark.usefixtures("clean_db")
def test_clear_import_error_for_file_without_dags(self, testing_dag_bundle, session):
"""
Test that import errors are cleared for files that were parsed but no longer contain DAGs.
"""
bundle_name = "testing"
filename = "no_dags.py"
prev_error = ParseImportError(
filename=filename,
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Previous import error",
)
session.add(prev_error)
# And import error for another file we haven't parsed (this shouldn't be deleted)
other_file_error = ParseImportError(
filename="other.py",
bundle_name=bundle_name,
timestamp=tz.utcnow(),
stacktrace="Some error",
)
session.add(other_file_error)
session.flush()
import_errors = set(session.execute(select(ParseImportError.filename, ParseImportError.bundle_name)))
assert import_errors == {("no_dags.py", bundle_name), ("other.py", bundle_name)}
# Simulate parsing the file: it was parsed successfully (no import errors),
# but it no longer contains any DAGs. By passing files_parsed, we ensure
# the import error is cleared even though there are no DAGs.
files_parsed = {(bundle_name, filename)}
update_dag_parsing_results_in_db(
bundle_name=bundle_name,
bundle_version=None,
dags=[], # No DAGs in this file
import_errors={}, # No import errors
parse_duration=None,
warnings=set(),
session=session,
files_parsed=files_parsed,
)
import_errors = set(session.execute(select(ParseImportError.filename, ParseImportError.bundle_name)))
assert import_errors == {("other.py", bundle_name)}, "Import error for parsed file should be cleared"
@pytest.mark.need_serialized_dag(False)
@pytest.mark.parametrize(
("attrs", "expected"),
[
pytest.param(
{
"_tasks_": [
EmptyOperator(task_id="task", owner="owner1"),
EmptyOperator(task_id="task2", owner="owner2"),
EmptyOperator(task_id="task3"),
EmptyOperator(task_id="task4", owner="owner2"),
]
},
{"owners": ["owner1", "owner2"]},
id="tasks-multiple-owners",
),
pytest.param(
{"is_paused_upon_creation": True},
{"is_paused": True},
id="is_paused_upon_creation",
),
pytest.param(
{},
{"owners": ["airflow"]},
id="default-owner",
),
pytest.param(
{},
{"fail_fast": False},
id="default-fail-fast",
),
pytest.param(
{"fail_fast": True},
{"fail_fast": True},
id="fail-fast-true",
),
pytest.param(
{
"_tasks_": [
EmptyOperator(task_id="task", owner="owner1"),
EmptyOperator(task_id="task2", owner="owner2"),
EmptyOperator(task_id="task3"),
EmptyOperator(task_id="task4", owner="owner2"),
],
"schedule": "0 0 * * *",
"catchup": False,
},
{
"owners": ["owner1", "owner2"],
"next_dagrun": tz.datetime(2020, 1, 5, 0, 0, 0),
"next_dagrun_data_interval_start": tz.datetime(2020, 1, 5, 0, 0, 0),
"next_dagrun_data_interval_end": tz.datetime(2020, 1, 6, 0, 0, 0),
"next_dagrun_create_after": tz.datetime(2020, 1, 6, 0, 0, 0),
},
id="with-scheduled-dagruns",
),
],
)
@pytest.mark.usefixtures("clean_db")
def test_dagmodel_properties(self, attrs, expected, session, time_machine, testing_dag_bundle, dag_maker):
"""Test that properties on the dag model are correctly set when dealing with a LazySerializedDag"""
dt = tz.datetime(2020, 1, 6, 0, 0, 0)
time_machine.move_to(dt, tick=False)
tasks = attrs.pop("_tasks_", None)
with dag_maker("dag", **attrs) as dag:
...
if tasks:
dag.add_tasks(tasks)
if attrs.pop("schedule", None):
dr_kwargs = {
"dag_id": "dag",
"run_type": "scheduled",
"data_interval": (dt, dt + timedelta(minutes=5)),
}
dr1 = DagRun(logical_date=dt, run_id="test_run_id_1", **dr_kwargs, start_date=dt)
session.add(dr1)
update_dag_parsing_results_in_db(
bundle_name="testing",
bundle_version=None,
dags=[LazyDeserializedDAG.from_dag(dag)],
import_errors={},
parse_duration=None,
warnings=set(),
session=session,
)
orm_dag = session.get(DagModel, ("dag",))
for attrname, expected_value in expected.items():
if attrname == "owners":
assert sorted(orm_dag.owners.split(", ")) == expected_value
else:
assert getattr(orm_dag, attrname) == expected_value
assert orm_dag.last_parsed_time == dt
def test_existing_dag_is_paused_upon_creation(self, testing_dag_bundle, session, dag_maker):
with dag_maker("dag_paused", schedule=None) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, ("dag_paused",))
assert orm_dag.is_paused is False
with dag_maker("dag_paused", schedule=None, is_paused_upon_creation=True) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
# Since the dag existed before, it should not follow the pause flag upon creation
orm_dag = session.get(DagModel, ("dag_paused",))
assert orm_dag.is_paused is False
def test_bundle_name_and_version_are_stored(self, testing_dag_bundle, session, dag_maker):
with dag_maker("mydag", schedule=None) as dag:
...
update_dag_parsing_results_in_db("testing", "1.0", [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "mydag")
assert orm_dag.bundle_name == "testing"
assert orm_dag.bundle_version == "1.0"
def test_max_active_tasks_explicit_value_is_used(self, testing_dag_bundle, session, dag_maker):
with dag_maker("dag_max_tasks", schedule=None, max_active_tasks=5) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_tasks")
assert orm_dag.max_active_tasks == 5
def test_max_active_tasks_defaults_from_conf_when_none(self, testing_dag_bundle, session, dag_maker):
# Override config so that when DAG.max_active_tasks is None, DagModel gets the configured default
with conf_vars({("core", "max_active_tasks_per_dag"): "7"}):
with dag_maker("dag_max_tasks_default", schedule=None) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_tasks_default")
assert orm_dag.max_active_tasks == 7
def test_max_active_runs_explicit_value_is_used(self, testing_dag_bundle, session, dag_maker):
with dag_maker("dag_max_runs", schedule=None, max_active_runs=3) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_runs")
assert orm_dag.max_active_runs == 3
def test_max_active_runs_defaults_from_conf_when_none(self, testing_dag_bundle, session, dag_maker):
with conf_vars({("core", "max_active_runs_per_dag"): "4"}):
with dag_maker("dag_max_runs_default", schedule=None) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_runs_default")
assert orm_dag.max_active_runs == 4
def test_max_consecutive_failed_dag_runs_explicit_value_is_used(
self, testing_dag_bundle, session, dag_maker
):
with dag_maker("dag_max_failed_runs", schedule=None, max_consecutive_failed_dag_runs=2) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_failed_runs")
assert orm_dag.max_consecutive_failed_dag_runs == 2
def test_max_consecutive_failed_dag_runs_defaults_from_conf_when_none(
self, testing_dag_bundle, session, dag_maker
):
with conf_vars({("core", "max_consecutive_failed_dag_runs_per_dag"): "6"}):
with dag_maker("dag_max_failed_runs_default", schedule=None) as dag:
...
update_dag_parsing_results_in_db("testing", None, [dag], {}, 0.1, set(), session)
orm_dag = session.get(DagModel, "dag_max_failed_runs_default")
assert orm_dag.max_consecutive_failed_dag_runs == 6
@pytest.mark.db_test
| TestUpdateDagParsingResults |
python | pypa__pip | src/pip/_internal/req/req_file.py | {
"start": 9974,
"end": 14756
} | class ____:
def __init__(
self,
session: PipSession,
line_parser: LineParser,
) -> None:
self._session = session
self._line_parser = line_parser
def parse(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
"""Parse a given file, yielding parsed lines."""
yield from self._parse_and_recurse(
filename, constraint, [{os.path.abspath(filename): None}]
)
def _parse_and_recurse(
self,
filename: str,
constraint: bool,
parsed_files_stack: list[dict[str, str | None]],
) -> Generator[ParsedLine, None, None]:
for line in self._parse_file(filename, constraint):
if line.requirement is None and (
line.opts.requirements or line.opts.constraints
):
# parse a nested requirements file
if line.opts.requirements:
req_path = line.opts.requirements[0]
nested_constraint = False
else:
req_path = line.opts.constraints[0]
nested_constraint = True
# original file is over http
if SCHEME_RE.search(filename):
# do a url join so relative paths work
req_path = urllib.parse.urljoin(filename, req_path)
# original file and nested file are paths
elif not SCHEME_RE.search(req_path):
# do a join so relative paths work
# and then abspath so that we can identify recursive references
req_path = os.path.abspath(
os.path.join(
os.path.dirname(filename),
req_path,
)
)
parsed_files = parsed_files_stack[0]
if req_path in parsed_files:
initial_file = parsed_files[req_path]
tail = (
f" and again in {initial_file}"
if initial_file is not None
else ""
)
raise RequirementsFileParseError(
f"{req_path} recursively references itself in {filename}{tail}"
)
# Keeping a track where was each file first included in
new_parsed_files = parsed_files.copy()
new_parsed_files[req_path] = filename
yield from self._parse_and_recurse(
req_path, nested_constraint, [new_parsed_files, *parsed_files_stack]
)
else:
yield line
def _parse_file(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
_, content = get_file_content(filename, self._session)
lines_enum = preprocess(content)
for line_number, line in lines_enum:
try:
args_str, opts = self._line_parser(line)
except OptionParsingError as e:
# add offending line
msg = f"Invalid requirement: {line}\n{e.msg}"
raise RequirementsFileParseError(msg)
yield ParsedLine(
filename,
line_number,
args_str,
opts,
constraint,
)
def get_line_parser(finder: PackageFinder | None) -> LineParser:
def parse_line(line: str) -> tuple[str, Values]:
# Build new parser for each line since it accumulates appendable
# options.
parser = build_parser()
defaults = parser.get_default_values()
defaults.index_url = None
if finder:
defaults.format_control = finder.format_control
args_str, options_str = break_args_options(line)
try:
options = shlex.split(options_str)
except ValueError as e:
raise OptionParsingError(f"Could not split options: {options_str}") from e
opts, _ = parser.parse_args(options, defaults)
return args_str, opts
return parse_line
def break_args_options(line: str) -> tuple[str, str]:
"""Break up the line into an args and options string. We only want to shlex
(and then optparse) the options, not the args. args can contain markers
which are corrupted by shlex.
"""
tokens = line.split(" ")
args = []
options = tokens[:]
for token in tokens:
if token.startswith(("-", "--")):
break
else:
args.append(token)
options.pop(0)
return " ".join(args), " ".join(options)
| RequirementsFileParser |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 576,
"end": 636
} | class ____(str, Enum):
OIDC = "oidc"
@dataclass
| GroupTypes |
python | ray-project__ray | python/ray/tests/test_runtime_env_packaging.py | {
"start": 10860,
"end": 11436
} | class ____:
def test_get_top_level_valid(self, random_zip_file_with_top_level_dir):
top_level_dir_name = get_top_level_dir_from_compressed_package(
str(random_zip_file_with_top_level_dir)
)
assert top_level_dir_name == TOP_LEVEL_DIR_NAME
def test_get_top_level_invalid(self, random_zip_file_without_top_level_dir):
top_level_dir_name = get_top_level_dir_from_compressed_package(
str(random_zip_file_without_top_level_dir)
)
assert top_level_dir_name is None
| TestGetTopLevelDirFromCompressedPackage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/log.py | {
"start": 7469,
"end": 8498
} | class ____:
__doc__ = """\
When ``True``, enable log output for this element.
This has the effect of setting the Python logging level for the namespace
of this element's class and object reference. A value of boolean ``True``
indicates that the loglevel ``logging.INFO`` will be set for the logger,
whereas the string value ``debug`` will set the loglevel to
``logging.DEBUG``.
"""
@overload
def __get__(
self, instance: Literal[None], owner: Type[Identified]
) -> echo_property: ...
@overload
def __get__(
self, instance: Identified, owner: Type[Identified]
) -> _EchoFlagType: ...
def __get__(
self, instance: Optional[Identified], owner: Type[Identified]
) -> Union[echo_property, _EchoFlagType]:
if instance is None:
return self
else:
return instance._echo
def __set__(self, instance: Identified, value: _EchoFlagType) -> None:
instance_logger(instance, echoflag=value)
| echo_property |
python | getsentry__sentry | tests/sentry/core/endpoints/scim/test_scim_schema.py | {
"start": 50,
"end": 254
} | class ____(SCIMTestCase):
endpoint = "sentry-api-0-organization-scim-schema-index"
def test_schema_200s(self) -> None:
self.get_success_response(self.organization.slug)
| SCIMSchemaEndpointTest |
python | sqlalchemy__sqlalchemy | test/orm/_fixtures.py | {
"start": 11074,
"end": 17584
} | class ____:
"""Built on demand, instances use mappers in effect at time of call."""
def __init__(self, test):
self.test = test
@property
def user_result(self):
User = self.test.classes.User
return [User(id=7), User(id=8), User(id=9), User(id=10)]
@property
def user_address_result(self):
User, Address = self.test.classes.User, self.test.classes.Address
return [
User(id=7, addresses=[Address(id=1)]),
User(
id=8,
addresses=[
Address(id=2, email_address="ed@wood.com"),
Address(id=3, email_address="ed@bettyboop.com"),
Address(id=4, email_address="ed@lala.com"),
],
),
User(id=9, addresses=[Address(id=5)]),
User(id=10, addresses=[]),
]
@property
def address_user_result(self):
User, Address = self.test.classes.User, self.test.classes.Address
u7 = User(id=7)
u8 = User(id=8)
u9 = User(id=9)
return [
Address(id=1, email_address="jack@bean.com", user=u7),
Address(id=2, email_address="ed@wood.com", user=u8),
Address(id=3, email_address="ed@bettyboop.com", user=u8),
Address(id=4, email_address="ed@lala.com", user=u8),
Address(id=5, user=u9),
]
@property
def user_all_result(self):
User, Address, Order, Item = (
self.test.classes.User,
self.test.classes.Address,
self.test.classes.Order,
self.test.classes.Item,
)
return [
User(
id=7,
addresses=[Address(id=1)],
orders=[
Order(
description="order 1",
items=[
Item(description="item 1"),
Item(description="item 2"),
Item(description="item 3"),
],
),
Order(description="order 3"),
Order(description="order 5"),
],
),
User(
id=8, addresses=[Address(id=2), Address(id=3), Address(id=4)]
),
User(
id=9,
addresses=[Address(id=5)],
orders=[
Order(
description="order 2",
items=[
Item(description="item 1"),
Item(description="item 2"),
Item(description="item 3"),
],
),
Order(
description="order 4",
items=[
Item(description="item 1"),
Item(description="item 5"),
],
),
],
),
User(id=10, addresses=[]),
]
@property
def user_order_result(self):
User, Order, Item = (
self.test.classes.User,
self.test.classes.Order,
self.test.classes.Item,
)
return [
User(
id=7,
orders=[
Order(id=1, items=[Item(id=1), Item(id=2), Item(id=3)]),
Order(id=3, items=[Item(id=3), Item(id=4), Item(id=5)]),
Order(id=5, items=[Item(id=5)]),
],
),
User(id=8, orders=[]),
User(
id=9,
orders=[
Order(id=2, items=[Item(id=1), Item(id=2), Item(id=3)]),
Order(id=4, items=[Item(id=1), Item(id=5)]),
],
),
User(id=10),
]
@property
def item_keyword_result(self):
Item, Keyword = self.test.classes.Item, self.test.classes.Keyword
return [
Item(
id=1,
keywords=[
Keyword(name="red"),
Keyword(name="big"),
Keyword(name="round"),
],
),
Item(
id=2,
keywords=[
Keyword(name="red"),
Keyword(name="small"),
Keyword(name="square"),
],
),
Item(
id=3,
keywords=[
Keyword(name="green"),
Keyword(name="big"),
Keyword(name="round"),
],
),
Item(id=4, keywords=[]),
Item(id=5, keywords=[]),
]
@property
def user_item_keyword_result(self):
Item, Keyword = self.test.classes.Item, self.test.classes.Keyword
User, Order = self.test.classes.User, self.test.classes.Order
item1, item2, item3, item4, item5 = (
Item(
id=1,
keywords=[
Keyword(name="red"),
Keyword(name="big"),
Keyword(name="round"),
],
),
Item(
id=2,
keywords=[
Keyword(name="red"),
Keyword(name="small"),
Keyword(name="square"),
],
),
Item(
id=3,
keywords=[
Keyword(name="green"),
Keyword(name="big"),
Keyword(name="round"),
],
),
Item(id=4, keywords=[]),
Item(id=5, keywords=[]),
)
user_result = [
User(
id=7,
orders=[
Order(id=1, items=[item1, item2, item3]),
Order(id=3, items=[item3, item4, item5]),
Order(id=5, items=[item5]),
],
),
User(id=8, orders=[]),
User(
id=9,
orders=[
Order(id=2, items=[item1, item2, item3]),
Order(id=4, items=[item1, item5]),
],
),
User(id=10, orders=[]),
]
return user_result
| CannedResults |
python | jina-ai__jina | tests/unit/orchestrate/pods/test_pod.py | {
"start": 2284,
"end": 4502
} | class ____(BaseExecutor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
raise RuntimeError('intentional error')
def test_failing_executor():
args = _generate_pod_args(
[
'--uses',
'RaisingExecutor',
]
)
with pytest.raises(RuntimeFailToStart):
with Pod(args):
pass
@pytest.mark.parametrize(
'protocol, expected',
[
('grpc', 'GRPCGateway'),
('websocket', 'WebSocketGateway'),
('http', 'HTTPGateway'),
],
)
def test_failing_gateway_runtimes(protocol, expected):
args = set_gateway_parser().parse_args(
[
'--graph-description',
'{"start-gateway": ["pod0"], "pod0": ["end-gateway"]}',
'--deployments-addresses',
'{_INVALIDJSONINTENTIONALLY_pod0": ["0.0.0.0:1234"]}',
'--protocol',
protocol,
]
)
with pytest.raises(RuntimeFailToStart):
with Pod(args):
pass
@pytest.mark.timeout(4)
def test_close_before_start(monkeypatch):
class SlowFakeRuntime:
def __init__(self, *args, **kwargs):
time.sleep(5.0)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def run_forever(self):
pass
monkeypatch.setattr(
runtime_asyncio,
'AsyncNewLoopRuntime',
SlowFakeRuntime,
)
pod = Pod(_generate_pod_args(['--noblock-on-start']))
pod.start()
pod.is_signal_handlers_installed.set()
pod.close()
@pytest.mark.timeout(4)
def test_close_before_start_slow_enter(monkeypatch):
class SlowFakeRuntime:
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
time.sleep(5.0)
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def run_forever(self):
pass
monkeypatch.setattr(
runtime_asyncio,
'AsyncNewLoopRuntime',
SlowFakeRuntime,
)
pod = Pod(_generate_pod_args(['--noblock-on-start']))
pod.start()
pod.is_signal_handlers_installed.set()
pod.close()
| RaisingExecutor |
python | pytorch__pytorch | torch/distributed/elastic/utils/api.py | {
"start": 1202,
"end": 1705
} | class ____:
"""
Defines simple macros for caffe2.distributed.launch cmd args substitution
"""
local_rank = "${local_rank}"
@staticmethod
def substitute(args: list[Any], local_rank: str) -> list[str]:
args_sub = []
for arg in args:
if isinstance(arg, str):
sub = Template(arg).safe_substitute(local_rank=local_rank)
args_sub.append(sub)
else:
args_sub.append(arg)
return args_sub
| macros |
python | pytorch__pytorch | test/jit/test_custom_operators.py | {
"start": 456,
"end": 4865
} | class ____(JitTestCase):
def test_dynamic_op_registry(self):
from torch._ops import _OpNamespace
self.assertTrue(hasattr(torch, "ops"))
if "_test" in torch.ops.__dict__:
torch.ops.__dict__.pop("_test")
# Don't use `hasattr()` because it will call `__getattr__`.
self.assertNotIn("_test", torch.ops.__dict__)
torch.ops._test
self.assertIn("_test", torch.ops.__dict__)
self.assertEqual(type(torch.ops._test), _OpNamespace)
self.assertNotIn("leaky_relu", torch.ops._test.__dict__)
op = torch.ops._test.leaky_relu
self.assertTrue(callable(op))
self.assertIn("leaky_relu", torch.ops._test.__dict__)
op2 = torch.ops._test.leaky_relu
self.assertEqual(op, op2)
def test_getting_invalid_attr(self):
for attr in ["__origin__", "__self__"]:
with self.assertRaisesRegexWithHighlight(
AttributeError,
f"Invalid attribute '{attr}' for '_OpNamespace' '_test'",
"",
):
getattr(torch.ops._test, attr)
def test_simply_calling_an_operator(self):
input = torch.randn(100)
output = torch.ops.aten.relu(input)
self.assertEqual(output, input.relu())
def test_default_arguments_are_used(self):
output = torch.ops._test.leaky_relu(torch.tensor([-1.0, 1.0]))
self.assertEqual(output, torch.tensor([-0.01, 1]))
def test_passing_too_many_args(self):
with self.assertRaisesRegexWithHighlight(
RuntimeError,
r"aten::relu\(\) expected at most 1 argument\(s\) but received 2 argument\(s\)",
"",
):
torch.ops.aten.relu(1, 2)
def test_passing_too_few_args(self):
with self.assertRaisesRegexWithHighlight(
RuntimeError, r"aten::relu\(\) is missing value for argument 'self'.", ""
):
torch.ops.aten.relu()
def test_passing_one_positional_but_not_the_second(self):
with self.assertRaisesRegexWithHighlight(
RuntimeError,
r"aten::type_as\(\) is missing value for argument 'other'.",
"",
):
torch.ops.aten.type_as(torch.ones(5, 5))
def test_passing_unknown_kwargs(self):
with self.assertRaisesRegexWithHighlight(
RuntimeError,
"Unknown keyword argument 'foo' for operator '_test::leaky_relu'",
"",
):
torch.ops._test.leaky_relu(torch.ones(5), foo=torch.ones(5))
def test_passing_and_returning_lists(self):
# Replace with actual test once we support lists.
a, b = torch.rand(5), torch.rand(5)
output = torch.ops._test.cat([a, b])
output_ref = torch.cat([a, b])
self.assertEqual(output, output_ref)
def test_calling_scripted_custom_op(self):
@torch.jit.script
def func(x):
return torch.ops.aten.relu(x)
input = torch.ones(5, 5)
self.assertEqual(func(input), input.relu())
def test_calling_traced_custom_op(self):
input = torch.ones(5, 5)
func = torch.jit.trace(torch.ops.aten.relu, [input])
self.assertEqual(func(input), input.relu())
@unittest.skip(
"Need to figure out default dtype differences between fbcode and oss"
)
def test_script_graph_for_custom_ops_matches_traced_graph(self):
input = torch.ones(5, 5)
trace = torch.jit.trace(torch.ops.aten.relu, [input])
self.assertExpectedInline(
canonical(trace.graph),
"""\
graph(%0 : Float(5, 5)):
%1 : Float(5, 5) = aten::relu(%0)
return (%1)
""",
)
def test_script_graph_contains_custom_op(self):
@torch.jit.script
def func(x):
return torch.ops.aten.relu(x)
self.assertExpectedInline(
canonical(func.graph),
"""\
graph(%x.1 : Tensor):
%1 : Tensor = aten::relu(%x.1)
return (%1)
""",
)
def test_generic_list(self):
self.assertEqual(torch.ops._test.get_first([["hello"]]), "hello")
# https://github.com/pytorch/pytorch/issues/80508
def test_where_no_scalar(self):
x = torch.rand(1, 3, 224, 224)
torch.ops.aten.where(x > 0.5, -1.5, 1.5) # does not raise
if __name__ == "__main__":
raise_on_run_directly("test/test_jit.py")
| TestCustomOperators |
python | doocs__leetcode | solution/3100-3199/3114.Latest Time You Can Obtain After Replacing Characters/Solution.py | {
"start": 0,
"end": 271
} | class ____:
def findLatestTime(self, s: str) -> str:
for h in range(11, -1, -1):
for m in range(59, -1, -1):
t = f"{h:02d}:{m:02d}"
if all(a == b for a, b in zip(s, t) if a != "?"):
return t
| Solution |
python | getsentry__sentry | src/sentry/onboarding_tasks/backends/organization_onboarding_task.py | {
"start": 775,
"end": 5864
} | class ____(OnboardingTaskBackend[OrganizationOnboardingTask]):
Model = OrganizationOnboardingTask
def fetch_onboarding_tasks(self, organization, user):
return self.Model.objects.filter(
organization=organization,
task__in=OnboardingTask.values(), # we exclude any tasks that might no longer be in the onboarding flow but still linger around in the database
status__in=OnboardingTaskStatus.values(), # same here but for status
)
def create_or_update_onboarding_task(self, organization, user, task, values):
return self.Model.objects.create_or_update(
organization=organization,
task=task,
values=values,
defaults={"user_id": user.id},
)
def complete_onboarding_task(
self,
organization: Organization,
task: int,
date_completed: datetime | None = None,
**task_kwargs,
) -> bool:
# Mark the task as complete
created = self.Model.objects.record(
organization_id=organization.id,
task=task,
status=OnboardingTaskStatus.COMPLETE,
date_completed=date_completed or timezone.now(),
**task_kwargs,
)
# Check if all required tasks are complete to see if we can mark onboarding as complete
if created:
self.try_mark_onboarding_complete(organization.id)
return created
def has_completed_onboarding_task(self, organization: Organization, task: int) -> bool:
return OrganizationOnboardingTask.objects.filter(
organization_id=organization.id, task=task
).exists()
def try_mark_onboarding_complete(self, organization_id: int):
if OrganizationOption.objects.filter(
organization_id=organization_id, key="onboarding:complete"
).exists():
return
completed = set(
OrganizationOnboardingTask.objects.filter(
Q(organization_id=organization_id)
& (Q(status=OnboardingTaskStatus.COMPLETE) | Q(status=OnboardingTaskStatus.SKIPPED))
& Q(
completion_seen__isnull=False
) # For a task to be considered complete, it must have been marked as seen.
).values_list("task", flat=True)
)
organization = Organization.objects.get_from_cache(id=organization_id)
has_project_with_source_maps = Project.objects.filter(
organization=organization, platform__in=SOURCE_MAPS
).exists()
# If a project supports source maps, we require them to complete the quick start.
# It's possible that the first project doesn't have source maps,
# but the second project (which users are guided to create in the "Add Sentry to other parts of the app" step) may have source maps.
required_tasks = (
OrganizationOnboardingTask.REQUIRED_ONBOARDING_TASKS_WITH_SOURCE_MAPS
if has_project_with_source_maps
else OrganizationOnboardingTask.REQUIRED_ONBOARDING_TASKS
)
if completed >= required_tasks:
try:
with transaction.atomic(router.db_for_write(OrganizationOption)):
OrganizationOption.objects.create(
organization_id=organization_id,
key="onboarding:complete",
value={"updated": json.datetime_to_str(timezone.now())},
)
try:
analytics.record(
OnboardingCompleteEvent(
user_id=organization.default_owner_id,
organization_id=organization_id,
referrer="onboarding_tasks",
)
)
except Exception as e:
sentry_sdk.capture_exception(e)
except IntegrityError:
pass
def transfer_onboarding_tasks(
self,
from_organization_id: int,
to_organization_id: int,
project: Project | None = None,
):
# get a list of task IDs that already exist in the new organization
existing_tasks_in_new_org = OrganizationOnboardingTask.objects.filter(
organization_id=to_organization_id
).values_list("task", flat=True)
# get a list of tasks to transfer from the old organization
tasks_to_transfer = OrganizationOnboardingTask.objects.filter(
organization=from_organization_id,
task__in=OrganizationOnboardingTask.TRANSFERABLE_TASKS,
).exclude(task__in=existing_tasks_in_new_org)
for task_to_transfer in tasks_to_transfer:
task_dict = model_to_dict(task_to_transfer, exclude=["id", "organization", "project"])
new_task = OrganizationOnboardingTask(
**task_dict, organization_id=to_organization_id, project=project
)
new_task.save()
| OrganizationOnboardingTaskBackend |
python | lepture__authlib | authlib/oauth2/rfc7591/errors.py | {
"start": 638,
"end": 847
} | class ____(OAuth2Error):
"""The software statement presented is invalid.
https://tools.ietf.org/html/rfc7591#section-3.2.2.
"""
error = "invalid_software_statement"
| InvalidSoftwareStatementError |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py | {
"start": 926,
"end": 1137
} | class ____(Exception):
"""Will be raised on missing hooks (if a fallback can't be used)."""
def __init__(self, hook_name):
super().__init__(hook_name)
self.hook_name = hook_name
| HookMissing |
python | cython__cython | Cython/Shadow.py | {
"start": 16473,
"end": 16982
} | class ____:
"""
The cython.parallel module.
"""
__all__ = ['parallel', 'prange', 'threadid']
def parallel(self, num_threads=None):
return nogil
def prange(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None):
if stop is None:
stop = start
start = 0
return range(start, stop, step)
def threadid(self):
return 0
# def threadsavailable(self):
# return 1
| CythonDotParallel |
python | sanic-org__sanic | sanic/touchup/schemes/ode.py | {
"start": 141,
"end": 1564
} | class ____(BaseScheme):
ident = "ODE"
SYNC_SIGNAL_NAMESPACES = "http."
def __init__(self, app) -> None:
super().__init__(app)
self._sync_events()
self._registered_events = [
signal.name for signal in app.signal_router.routes
]
def visitors(self) -> list[NodeTransformer]:
return [RemoveDispatch(self._registered_events)]
def _sync_events(self):
all_events = set()
app_events = {}
for app in self.app.__class__._app_registry.values():
if app.state.server_info:
app_events[app] = {
signal.name for signal in app.signal_router.routes
}
all_events.update(app_events[app])
for app, events in app_events.items():
missing = {
x
for x in all_events.difference(events)
if any(x.startswith(y) for y in self.SYNC_SIGNAL_NAMESPACES)
}
if missing:
was_finalized = app.signal_router.finalized
if was_finalized: # no cov
app.signal_router.reset()
for event in missing:
app.signal(event)(self.noop)
if was_finalized: # no cov
app.signal_router.finalize()
@staticmethod
async def noop(**_): # no cov
...
| OptionalDispatchEvent |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 35342,
"end": 35546
} | class ____(BoringModel):
def on_validation_start(self):
if not self.trainer.sanity_checking and self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnValidationStart |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 83210,
"end": 84575
} | class ____(nn.Module):
def __init__(
self,
d_model,
dim_feedforward=2048,
dropout=0.0,
activation="relu",
normalize_before=False,
layer_norm_eps=1e-05,
):
super().__init__()
# Implementation of Feedforward model
self.linear1 = nn.Linear(d_model, dim_feedforward)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(dim_feedforward, d_model)
self.norm = nn.LayerNorm(d_model, eps=layer_norm_eps)
self.activation = ACT2FN[activation]
self.normalize_before = normalize_before
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, output):
output2 = self.linear2(self.dropout(self.activation(self.linear1(output))))
output = output + self.dropout(output2)
output = self.norm(output)
return output
def forward_pre(self, output):
output2 = self.norm(output)
output2 = self.linear2(self.dropout(self.activation(self.linear1(output2))))
output = output + self.dropout(output2)
return output
def forward(self, output):
if self.normalize_before:
return self.forward_pre(output)
return self.forward_post(output)
| OneFormerTransformerDecoderFFNLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 575946,
"end": 576583
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DisablePullRequestAutoMerge"""
__schema__ = github_schema
__field_names__ = ("actor", "client_mutation_id", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
pull_request = sgqlc.types.Field("PullRequest", graphql_name="pullRequest")
"""The pull request auto merge was disabled on."""
| DisablePullRequestAutoMergePayload |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py | {
"start": 300,
"end": 4532
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
team: Team | None = Relationship(back_populates="heroes")
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():
with Session(engine) as session:
team_preventers = Team(name="Preventers", headquarters="Sharp Tower")
team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar")
hero_deadpond = Hero(
name="Deadpond", secret_name="Dive Wilson", team=team_z_force
)
hero_rusty_man = Hero(
name="Rusty-Man", secret_name="Tommy Sharp", age=48, team=team_preventers
)
hero_spider_boy = Hero(name="Spider-Boy", secret_name="Pedro Parqueador")
session.add(hero_deadpond)
session.add(hero_rusty_man)
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_deadpond)
session.refresh(hero_rusty_man)
session.refresh(hero_spider_boy)
print("Created hero:", hero_deadpond)
print("Created hero:", hero_rusty_man)
print("Created hero:", hero_spider_boy)
hero_spider_boy.team = team_preventers
session.add(hero_spider_boy)
session.commit()
session.refresh(hero_spider_boy)
print("Updated hero:", hero_spider_boy)
hero_black_lion = Hero(name="Black Lion", secret_name="Trevor Challa", age=35)
hero_sure_e = Hero(name="Princess Sure-E", secret_name="Sure-E")
team_wakaland = Team(
name="Wakaland",
headquarters="Wakaland Capital City",
heroes=[hero_black_lion, hero_sure_e],
)
session.add(team_wakaland)
session.commit()
session.refresh(team_wakaland)
print("Team Wakaland:", team_wakaland)
hero_tarantula = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32)
hero_dr_weird = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36)
hero_cap = Hero(
name="Captain North America", secret_name="Esteban Rogelios", age=93
)
team_preventers.heroes.append(hero_tarantula)
team_preventers.heroes.append(hero_dr_weird)
team_preventers.heroes.append(hero_cap)
session.add(team_preventers)
session.commit()
session.refresh(hero_tarantula)
session.refresh(hero_dr_weird)
session.refresh(hero_cap)
print("Preventers new hero:", hero_tarantula)
print("Preventers new hero:", hero_dr_weird)
print("Preventers new hero:", hero_cap)
def select_heroes():
with Session(engine) as session:
statement = select(Team).where(Team.name == "Preventers")
result = session.exec(statement)
team_preventers = result.one()
print("Preventers heroes:", team_preventers.heroes)
def update_heroes():
with Session(engine) as session:
hero_spider_boy = session.exec(
select(Hero).where(Hero.name == "Spider-Boy")
).one()
preventers_team = session.exec(
select(Team).where(Team.name == "Preventers")
).one()
print("Hero Spider-Boy:", hero_spider_boy)
print("Preventers Team:", preventers_team)
print("Preventers Team Heroes:", preventers_team.heroes)
hero_spider_boy.team = None
print("Spider-Boy without team:", hero_spider_boy)
print("Preventers Team Heroes again:", preventers_team.heroes)
session.add(hero_spider_boy)
session.commit()
print("After committing")
session.refresh(hero_spider_boy)
print("Spider-Boy after commit:", hero_spider_boy)
print("Preventers Team Heroes after commit:", preventers_team.heroes)
def main():
create_db_and_tables()
create_heroes()
select_heroes()
update_heroes()
if __name__ == "__main__":
main()
| Hero |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 307478,
"end": 307658
} | class ____(VegaLiteSchema):
"""Element schema wrapper."""
_schema = {"$ref": "#/definitions/Element"}
def __init__(self, *args):
super().__init__(*args)
| Element |
python | django__django | tests/serializers/models/base.py | {
"start": 2928,
"end": 3573
} | class ____(models.CharField):
def __init__(self):
super().__init__(max_length=100)
def get_db_prep_save(self, value, connection):
return str(value.title)
def to_python(self, value):
if isinstance(value, Team):
return value
return Team(value)
def from_db_value(self, value, expression, connection):
return Team(value)
def value_to_string(self, obj):
return self.value_from_object(obj).to_string()
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs["max_length"]
return name, path, args, kwargs
| TeamField |
python | milvus-io__pymilvus | pymilvus/orm/future.py | {
"start": 1777,
"end": 1929
} | class ____(BaseFuture):
"""SearchFuture of async already returns SearchResult, add BaseFuture
functions into async.SearchFuture
"""
| SearchFuture |
python | skorch-dev__skorch | examples/word_language_model/net.py | {
"start": 121,
"end": 3546
} | class ____(skorch.NeuralNet):
def __init__(
self,
criterion=torch.nn.CrossEntropyLoss,
clip=0.25,
lr=20,
ntokens=10000,
*args,
**kwargs
):
self.clip = clip
self.ntokens = ntokens
super(Net, self).__init__(criterion=criterion, lr=lr, *args, **kwargs)
def repackage_hidden(self, h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if isinstance(h, Variable):
return torch.tensor(h.data, device=h.device)
else:
return tuple(self.repackage_hidden(v) for v in h)
def on_epoch_begin(self, *args, **kwargs):
super().on_epoch_begin(*args, **kwargs)
# As an optimization to save tensor allocation for each
# batch we initialize the hidden state only once per epoch.
# This optimization was taken from the original example.
self.hidden = self.module_.init_hidden(self.batch_size)
def train_step(self, X, y):
self.module_.train()
# Repackage shared hidden state so that the previous batch
# does not influence the current one.
self.hidden = self.repackage_hidden(self.hidden)
self.module_.zero_grad()
output, self.hidden = self.module_(X, self.hidden)
y_pred = output.view(-1, self.ntokens)
loss = self.get_loss(y_pred, y)
loss.backward()
torch.nn.utils.clip_grad_norm_(self.module_.parameters(), self.clip)
for p in self.module_.parameters():
p.data.add_(-self.lr, p.grad.data)
return {'loss': loss, 'y_pred': y_pred}
def validation_step(self, X, y):
self.module_.eval()
hidden = self.module_.init_hidden(self.batch_size)
output, _ = self.module_(X, hidden)
output_flat = output.view(-1, self.ntokens)
return {'loss': self.get_loss(output_flat, y), 'y_pred': output_flat}
def evaluation_step(self, X, **kwargs):
self.module_.eval()
X = skorch.utils.to_tensor(X, device=self.device)
hidden = self.module_.init_hidden(self.batch_size)
output, _ = self.module_(X, hidden)
return output.view(-1, self.ntokens)
def predict(self, X):
return np.argmax(super().predict(X), -1)
def sample(self, input, temperature=1., hidden=None):
hidden = self.module_.init_hidden(1) if hidden is None else hidden
output, hidden = self.module_(input, hidden)
probas = output.squeeze().data.div(temperature).exp()
sample = torch.multinomial(probas, 1)[-1]
if probas.dim() > 1:
sample = sample[0]
return sample, self.repackage_hidden(hidden)
def sample_n(self, num_words, input, temperature=1., hidden=None):
preds = [None] * num_words
for i in range(num_words):
preds[i], hidden = self.sample(input, hidden=hidden)
input = skorch.utils.to_tensor(torch.LongTensor([[preds[i]]]),
device=self.device)
return preds, hidden
def score(self, X, y=None):
ds = self.get_dataset(X)
target_iterator = self.get_iterator(ds, training=False)
y_true = np.concatenate([skorch.utils.to_numpy(y) for _, y in target_iterator])
y_pred = self.predict(X)
return f1_score(y_true, y_pred, average='micro')
| Net |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 63514,
"end": 63755
} | class ____(BaseModel, extra="forbid"):
"""
Select points with empty payload for a specified field
"""
is_empty: "PayloadField" = Field(..., description="Select points with empty payload for a specified field")
| IsEmptyCondition |
python | django-guardian__django-guardian | example_project_custom_group/articles/models.py | {
"start": 1404,
"end": 1774
} | class ____(GroupObjectPermissionAbstract):
group = models.ForeignKey(CustomGroup, on_delete=models.CASCADE)
class Meta(GroupObjectPermissionAbstract.Meta):
abstract = False
indexes = [
*GroupObjectPermissionAbstract.Meta.indexes,
models.Index(fields=["content_type", "object_pk", "group"]),
]
| BigGroupObjectPermission |
python | doocs__leetcode | solution/1400-1499/1424.Diagonal Traverse II/Solution.py | {
"start": 0,
"end": 277
} | class ____:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
arr = []
for i, row in enumerate(nums):
for j, v in enumerate(row):
arr.append((i + j, j, v))
arr.sort()
return [v[2] for v in arr]
| Solution |
python | apache__airflow | providers/oracle/tests/unit/oracle/transfers/test_oracle_to_oracle.py | {
"start": 975,
"end": 2911
} | class ____:
def test_execute(self):
oracle_destination_conn_id = "oracle_destination_conn_id"
destination_table = "destination_table"
oracle_source_conn_id = "oracle_source_conn_id"
source_sql = "select sysdate from dual where trunc(sysdate) = :p_data"
source_sql_params = {":p_data": "2018-01-01"}
rows_chunk = 5000
cursor_description = [
("id", "<class 'oracledb.NUMBER'>", 39, None, 38, 0, 0),
("description", "<class 'oracledb.STRING'>", 60, 240, None, None, 1),
]
cursor_rows = [[1, "description 1"], [2, "description 2"]]
mock_dest_hook = MagicMock()
mock_src_hook = MagicMock()
mock_src_conn = mock_src_hook.get_conn.return_value.__enter__.return_value
mock_cursor = mock_src_conn.cursor.return_value
mock_cursor.description.__iter__.return_value = cursor_description
mock_cursor.fetchmany.side_effect = [cursor_rows, []]
op = OracleToOracleOperator(
task_id="copy_data",
oracle_destination_conn_id=oracle_destination_conn_id,
destination_table=destination_table,
oracle_source_conn_id=oracle_source_conn_id,
source_sql=source_sql,
source_sql_params=source_sql_params,
rows_chunk=rows_chunk,
)
op._execute(mock_src_hook, mock_dest_hook, None)
assert mock_src_hook.get_conn.called
assert mock_src_conn.cursor.called
mock_cursor.execute.assert_called_once_with(source_sql, source_sql_params)
calls = [
mock.call(rows_chunk),
mock.call(rows_chunk),
]
mock_cursor.fetchmany.assert_has_calls(calls)
mock_dest_hook.bulk_insert_rows.assert_called_once_with(
destination_table, cursor_rows, commit_every=rows_chunk, target_fields=["id", "description"]
)
| TestOracleToOracleTransfer |
python | boto__boto3 | tests/unit/docs/test_subresource.py | {
"start": 662,
"end": 1978
} | class ____(BaseDocsTest):
def test_document_sub_resources(self):
sub_resource_documentor = SubResourceDocumenter(
self.resource, self.root_services_path
)
sub_resource_documentor.document_sub_resources(self.doc_structure)
self.assert_contains_lines_in_order(
[
'-------------\nSub-resources\n-------------',
'Sub-resources are methods that create a new instance of a',
' child resource. This resource\'s identifiers get passed',
' along to the child.',
'For more information about sub-resources refer to the ',
]
)
self.assert_contains_lines_in_order(
[
'Sample',
'.. py:method:: MyService.ServiceResource.Sample(name)',
' Creates a Sample resource.::',
" sample = myservice.Sample('name')",
' :type name: string',
" :param name: The Sample's name identifier.",
' :rtype: :py:class:`MyService.Sample`',
' :returns: A Sample resource',
],
self.get_nested_service_contents(
'myservice', 'service-resource', 'Sample'
),
)
| TestSubResourceDocumenter |
python | gevent__gevent | src/gevent/tests/test__greenness.py | {
"start": 1948,
"end": 2295
} | class ____(HTTPServer, object):
messages = ()
requests_handled = 0
def __init__(self):
HTTPServer.__init__(self,
params.DEFAULT_BIND_ADDR_TUPLE,
QuietHandler)
def handle_request(self):
HTTPServer.handle_request(self)
self.requests_handled += 1
| Server |
python | pytorch__pytorch | .github/scripts/test_trymerge.py | {
"start": 36148,
"end": 38686
} | class ____(TestCase):
def test_get_classifications(self, *args: Any) -> None:
pr = GitHubPR("pytorch", "pytorch", 111467)
checks = pr.get_checkrun_conclusions()
checks = get_classifications(
pr.pr_num,
pr.project,
checks,
[],
)
pending, failed, ignorable = categorize_checks(checks, list(checks.keys()))
self.assertTrue(len(pending) == 0)
self.assertTrue(len(failed) == 0)
self.assertTrue(len(ignorable["FLAKY"]) == 1)
self.assertTrue(len(ignorable["BROKEN_TRUNK"]) == 1)
def test_get_classifications_drci_checkrun_not_found(self, *args: Any) -> None:
pr = GitHubPR("pytorch", "pytorch", 111467)
# No summary
checks = pr.get_checkrun_conclusions()
checks[DRCI_CHECKRUN_NAME] = JobCheckState(
DRCI_CHECKRUN_NAME,
"",
"NEUTRAL",
None,
1,
"",
None,
)
checks = get_classifications(
pr.pr_num,
pr.project,
checks,
[],
)
pending, failed, ignorable = categorize_checks(checks, list(checks.keys()))
self.assertTrue(len(pending) == 0)
self.assertTrue(len(failed) == 2)
# Empty summary
checks = pr.get_checkrun_conclusions()
checks[DRCI_CHECKRUN_NAME] = JobCheckState(
DRCI_CHECKRUN_NAME,
"",
"NEUTRAL",
None,
1,
"",
"",
)
checks = get_classifications(
pr.pr_num,
pr.project,
checks,
[],
)
pending, failed, ignorable = categorize_checks(checks, list(checks.keys()))
self.assertTrue(len(pending) == 0)
self.assertTrue(len(failed) == 2)
# No Dr.CI checkrun
checks = pr.get_checkrun_conclusions()
del checks[DRCI_CHECKRUN_NAME]
checks = get_classifications(
pr.pr_num,
pr.project,
checks,
[],
)
pending, failed, ignorable = categorize_checks(checks, list(checks.keys()))
self.assertTrue(len(pending) == 0)
self.assertTrue(len(failed) == 2)
@mock.patch("trymerge.gh_graphql", side_effect=mocked_gh_graphql)
@mock.patch("trymerge.gh_fetch_merge_base", return_value="")
@mock.patch(
"trymerge.get_drci_classifications", side_effect=mocked_drci_classifications
)
| TestBypassFailuresOnSandCastle |
python | pydata__xarray | xarray/core/variable.py | {
"start": 12116,
"end": 101430
} | class ____(NamedArray, AbstractArray, VariableArithmetic):
"""A netcdf-like variable consisting of dimensions, data and attributes
which describe a single Array. A single Variable object is not fully
described outside the context of its parent Dataset (if you want such a
fully described object, use a DataArray instead).
The main functional difference between Variables and numpy arrays is that
numerical operations on Variables implement array broadcasting by dimension
name. For example, adding an Variable with dimensions `('time',)` to
another Variable with dimensions `('space',)` results in a new Variable
with dimensions `('time', 'space')`. Furthermore, numpy reduce operations
like ``mean`` or ``sum`` are overwritten to take a "dimension" argument
instead of an "axis".
Variables are light-weight objects used as the building block for datasets.
They are more primitive objects, so operations with them provide marginally
higher performance than using DataArrays. However, manipulating data in the
form of a Dataset or DataArray should almost always be preferred, because
they can use more complete metadata in context of coordinate labels.
"""
__slots__ = ("_attrs", "_data", "_dims", "_encoding")
def __init__(
self,
dims,
data: T_DuckArray | ArrayLike,
attrs=None,
encoding=None,
fastpath=False,
):
"""
Parameters
----------
dims : str or sequence of str
Name(s) of the the data dimension(s). Must be either a string (only
for 1D data) or a sequence of strings with length equal to the
number of dimensions.
data : array_like
Data array which supports numpy-like data access.
attrs : dict_like or None, optional
Attributes to assign to the new variable. If None (default), an
empty attribute dictionary is initialized.
(see FAQ, :ref:`approach to metadata`)
encoding : dict_like or None, optional
Dictionary specifying how to encode this array's data into a
serialized format like netCDF4. Currently used keys (for netCDF)
include '_FillValue', 'scale_factor', 'add_offset' and 'dtype'.
Well-behaved code to serialize a Variable should ignore
unrecognized encoding items.
"""
super().__init__(
dims=dims, data=as_compatible_data(data, fastpath=fastpath), attrs=attrs
)
self._encoding: dict[Any, Any] | None = None
if encoding is not None:
self.encoding = encoding
def _new(
self,
dims=_default,
data=_default,
attrs=_default,
):
dims_ = copy.copy(self._dims) if dims is _default else dims
if attrs is _default:
attrs_ = None if self._attrs is None else self._attrs.copy()
else:
attrs_ = attrs
if data is _default:
return type(self)(dims_, copy.copy(self._data), attrs_)
else:
cls_ = type(self)
return cls_(dims_, data, attrs_)
@property
def _in_memory(self) -> bool:
if isinstance(
self._data, PandasIndexingAdapter | CoordinateTransformIndexingAdapter
):
return self._data._in_memory
return isinstance(
self._data,
np.ndarray | np.number | PandasExtensionArray,
) or (
isinstance(self._data, indexing.MemoryCachedArray)
and isinstance(self._data.array, indexing.NumpyIndexingAdapter)
)
@property
def data(self):
"""
The Variable's data as an array. The underlying array type
(e.g. dask, sparse, pint) is preserved.
See Also
--------
Variable.to_numpy
Variable.as_numpy
Variable.values
"""
if isinstance(self._data, PandasExtensionArray):
duck_array = self._data.array
elif isinstance(self._data, indexing.ExplicitlyIndexed):
duck_array = self._data.get_duck_array()
elif is_duck_array(self._data):
duck_array = self._data
else:
duck_array = self.values
if isinstance(duck_array, PandasExtensionArray):
# even though PandasExtensionArray is a duck array,
# we should not return the PandasExtensionArray wrapper,
# and instead return the underlying data.
return duck_array.array
return duck_array
@data.setter # type: ignore[override,unused-ignore]
def data(self, data: T_DuckArray | ArrayLike) -> None:
data = as_compatible_data(data)
self._check_shape(data)
self._data = data
def astype(
self,
dtype,
*,
order=None,
casting=None,
subok=None,
copy=None,
keep_attrs=True,
) -> Self:
"""
Copy of the Variable object, with data cast to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to which the array is cast.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout order of the result. ‘C’ means C order,
‘F’ means Fortran order, ‘A’ means ‘F’ order if all the arrays are
Fortran contiguous, ‘C’ order otherwise, and ‘K’ means as close to
the order the array elements appear in memory as possible.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
Controls what kind of data casting may occur.
* 'no' means the data types should not be cast at all.
* 'equiv' means only byte-order changes are allowed.
* 'safe' means only casts which can preserve values are allowed.
* 'same_kind' means only safe casts or casts within a kind,
like float64 to float32, are allowed.
* 'unsafe' means any data conversions may be done.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise the
returned array will be forced to be a base-class array.
copy : bool, optional
By default, astype always returns a newly allocated array. If this
is set to False and the `dtype` requirement is satisfied, the input
array is returned instead of a copy.
keep_attrs : bool, optional
By default, astype keeps attributes. Set to False to remove
attributes in the returned object.
Returns
-------
out : same as object
New object with data cast to the specified type.
Notes
-----
The ``order``, ``casting``, ``subok`` and ``copy`` arguments are only passed
through to the ``astype`` method of the underlying array when a value
different than ``None`` is supplied.
Make sure to only supply these arguments if the underlying array class
supports them.
See Also
--------
numpy.ndarray.astype
dask.array.Array.astype
sparse.COO.astype
"""
from xarray.computation.apply_ufunc import apply_ufunc
kwargs = dict(order=order, casting=casting, subok=subok, copy=copy)
kwargs = {k: v for k, v in kwargs.items() if v is not None}
return apply_ufunc(
duck_array_ops.astype,
self,
dtype,
kwargs=kwargs,
keep_attrs=keep_attrs,
dask="allowed",
)
def _dask_finalize(self, results, array_func, *args, **kwargs):
data = array_func(results, *args, **kwargs)
return Variable(self._dims, data, attrs=self._attrs, encoding=self._encoding)
@property
def values(self) -> np.ndarray:
"""The variable's data as a numpy.ndarray"""
return _as_array_or_item(self._data)
@values.setter
def values(self, values):
self.data = values
def to_base_variable(self) -> Variable:
"""Return this variable as a base xarray.Variable"""
return Variable(
self._dims, self._data, self._attrs, encoding=self._encoding, fastpath=True
)
to_variable = utils.alias(to_base_variable, "to_variable")
def to_index_variable(self) -> IndexVariable:
"""Return this variable as an xarray.IndexVariable"""
return IndexVariable(
self._dims, self._data, self._attrs, encoding=self._encoding, fastpath=True
)
to_coord = utils.alias(to_index_variable, "to_coord")
def _to_index(self) -> pd.Index:
return self.to_index_variable()._to_index()
def to_index(self) -> pd.Index:
"""Convert this variable to a pandas.Index"""
return self.to_index_variable().to_index()
def to_dict(
self, data: bool | str = "list", encoding: bool = False
) -> dict[str, Any]:
"""Dictionary representation of variable."""
item: dict[str, Any] = {
"dims": self.dims,
"attrs": decode_numpy_dict_values(self.attrs),
}
if data is not False:
if data in [True, "list"]:
item["data"] = ensure_us_time_resolution(self.to_numpy()).tolist()
elif data == "array":
item["data"] = ensure_us_time_resolution(self.data)
else:
msg = 'data argument must be bool, "list", or "array"'
raise ValueError(msg)
else:
item.update({"dtype": str(self.dtype), "shape": self.shape})
if encoding:
item["encoding"] = dict(self.encoding)
return item
def _item_key_to_tuple(self, key):
if is_dict_like(key):
return tuple(key.get(dim, slice(None)) for dim in self.dims)
else:
return key
def _broadcast_indexes(self, key):
"""Prepare an indexing key for an indexing operation.
Parameters
----------
key : int, slice, array-like, dict or tuple of integer, slice and array-like
Any valid input for indexing.
Returns
-------
dims : tuple
Dimension of the resultant variable.
indexers : IndexingTuple subclass
Tuple of integer, array-like, or slices to use when indexing
self._data. The type of this argument indicates the type of
indexing to perform, either basic, outer or vectorized.
new_order : Optional[Sequence[int]]
Optional reordering to do on the result of indexing. If not None,
the first len(new_order) indexing should be moved to these
positions.
"""
key = self._item_key_to_tuple(key) # key is a tuple
# key is a tuple of full size
key = indexing.expanded_indexer(key, self.ndim)
# Convert a scalar Variable to a 0d-array
key = tuple(
k.data if isinstance(k, Variable) and k.ndim == 0 else k for k in key
)
# Convert a 0d numpy arrays to an integer
# dask 0d arrays are passed through
key = tuple(
k.item() if isinstance(k, np.ndarray) and k.ndim == 0 else k for k in key
)
if all(
(isinstance(k, BASIC_INDEXING_TYPES) and not isinstance(k, bool))
for k in key
):
return self._broadcast_indexes_basic(key)
self._validate_indexers(key)
# Detect it can be mapped as an outer indexer
# If all key is unlabeled, or
# key can be mapped as an OuterIndexer.
if all(not isinstance(k, Variable) for k in key):
return self._broadcast_indexes_outer(key)
# If all key is 1-dimensional and there are no duplicate labels,
# key can be mapped as an OuterIndexer.
dims = []
for k, d in zip(key, self.dims, strict=True):
if isinstance(k, Variable):
if len(k.dims) > 1:
return self._broadcast_indexes_vectorized(key)
dims.append(k.dims[0])
elif not isinstance(k, integer_types):
dims.append(d)
if len(set(dims)) == len(dims):
return self._broadcast_indexes_outer(key)
return self._broadcast_indexes_vectorized(key)
def _broadcast_indexes_basic(self, key):
dims = tuple(
dim
for k, dim in zip(key, self.dims, strict=True)
if not isinstance(k, integer_types)
)
return dims, BasicIndexer(key), None
def _validate_indexers(self, key):
"""Make sanity checks"""
for dim, k in zip(self.dims, key, strict=True):
if not isinstance(k, BASIC_INDEXING_TYPES):
if not isinstance(k, Variable):
if not is_duck_array(k):
k = np.asarray(k)
if k.ndim > 1:
raise IndexError(
"Unlabeled multi-dimensional array cannot be "
f"used for indexing: {k}"
)
if k.dtype.kind == "b":
if self.shape[self.get_axis_num(dim)] != len(k):
raise IndexError(
f"Boolean array size {len(k):d} is used to index array "
f"with shape {self.shape}."
)
if k.ndim > 1:
raise IndexError(
f"{k.ndim}-dimensional boolean indexing is not supported. "
)
if is_duck_dask_array(k.data):
raise KeyError(
"Indexing with a boolean dask array is not allowed. "
"This will result in a dask array of unknown shape. "
"Such arrays are unsupported by Xarray."
"Please compute the indexer first using .compute()"
)
if getattr(k, "dims", (dim,)) != (dim,):
raise IndexError(
"Boolean indexer should be unlabeled or on the "
"same dimension to the indexed array. Indexer is "
f"on {k.dims} but the target dimension is {dim}."
)
def _broadcast_indexes_outer(self, key):
# drop dim if k is integer or if k is a 0d dask array
dims = tuple(
k.dims[0] if isinstance(k, Variable) else dim
for k, dim in zip(key, self.dims, strict=True)
if (not isinstance(k, integer_types) and not is_0d_dask_array(k))
)
new_key = []
for k in key:
if isinstance(k, Variable):
k = k.data
if not isinstance(k, BASIC_INDEXING_TYPES):
if not is_duck_array(k):
k = np.asarray(k)
if k.size == 0:
# Slice by empty list; numpy could not infer the dtype
k = k.astype(int)
elif k.dtype.kind == "b":
(k,) = np.nonzero(k)
new_key.append(k)
return dims, OuterIndexer(tuple(new_key)), None
def _broadcast_indexes_vectorized(self, key):
variables = []
out_dims_set = OrderedSet()
for dim, value in zip(self.dims, key, strict=True):
if isinstance(value, slice):
out_dims_set.add(dim)
else:
variable = (
value
if isinstance(value, Variable)
else as_variable(value, name=dim, auto_convert=False)
)
if variable.dims == (dim,):
variable = variable.to_index_variable()
if variable.dtype.kind == "b": # boolean indexing case
(variable,) = variable._nonzero()
variables.append(variable)
out_dims_set.update(variable.dims)
variable_dims = set()
for variable in variables:
variable_dims.update(variable.dims)
slices = []
for i, (dim, value) in enumerate(zip(self.dims, key, strict=True)):
if isinstance(value, slice):
if dim in variable_dims:
# We only convert slice objects to variables if they share
# a dimension with at least one other variable. Otherwise,
# we can equivalently leave them as slices aknd transpose
# the result. This is significantly faster/more efficient
# for most array backends.
values = np.arange(*value.indices(self.sizes[dim]))
variables.insert(i - len(slices), Variable((dim,), values))
else:
slices.append((i, value))
try:
variables = _broadcast_compat_variables(*variables)
except ValueError as err:
raise IndexError(f"Dimensions of indexers mismatch: {key}") from err
out_key = [variable.data for variable in variables]
out_dims = tuple(out_dims_set)
slice_positions = set()
for i, value in slices:
out_key.insert(i, value)
new_position = out_dims.index(self.dims[i])
slice_positions.add(new_position)
if slice_positions:
new_order = [i for i in range(len(out_dims)) if i not in slice_positions]
else:
new_order = None
return out_dims, VectorizedIndexer(tuple(out_key)), new_order
def __getitem__(self, key) -> Self:
"""Return a new Variable object whose contents are consistent with
getting the provided key from the underlying data.
NB. __getitem__ and __setitem__ implement xarray-style indexing,
where if keys are unlabeled arrays, we index the array orthogonally
with them. If keys are labeled array (such as Variables), they are
broadcasted with our usual scheme and then the array is indexed with
the broadcasted key, like numpy's fancy indexing.
If you really want to do indexing like `x[x > 0]`, manipulate the numpy
array `x.values` directly.
"""
dims, indexer, new_order = self._broadcast_indexes(key)
indexable = as_indexable(self._data)
data = indexing.apply_indexer(indexable, indexer)
if new_order:
data = duck_array_ops.moveaxis(data, range(len(new_order)), new_order)
return self._finalize_indexing_result(dims, data)
def _finalize_indexing_result(self, dims, data) -> Self:
"""Used by IndexVariable to return IndexVariable objects when possible."""
return self._replace(dims=dims, data=data)
def _getitem_with_mask(self, key, fill_value=dtypes.NA):
"""Index this Variable with -1 remapped to fill_value."""
# TODO(shoyer): expose this method in public API somewhere (isel?) and
# use it for reindex.
# TODO(shoyer): add a sanity check that all other integers are
# non-negative
# TODO(shoyer): add an optimization, remapping -1 to an adjacent value
# that is actually indexed rather than mapping it to the last value
# along each axis.
if fill_value is dtypes.NA:
fill_value = dtypes.get_fill_value(self.dtype)
dims, indexer, new_order = self._broadcast_indexes(key)
if self.size:
if is_duck_dask_array(self._data):
# dask's indexing is faster this way; also vindex does not
# support negative indices yet:
# https://github.com/dask/dask/pull/2967
actual_indexer = indexing.posify_mask_indexer(indexer)
else:
actual_indexer = indexer
indexable = as_indexable(self._data)
data = indexing.apply_indexer(indexable, actual_indexer)
mask = indexing.create_mask(indexer, self.shape, data)
# we need to invert the mask in order to pass data first. This helps
# pint to choose the correct unit
# TODO: revert after https://github.com/hgrecco/pint/issues/1019 is fixed
mask = to_like_array(mask, data)
data = duck_array_ops.where(
duck_array_ops.logical_not(mask), data, fill_value
)
else:
# array cannot be indexed along dimensions of size 0, so just
# build the mask directly instead.
mask = indexing.create_mask(indexer, self.shape)
data = duck_array_ops.broadcast_to(fill_value, getattr(mask, "shape", ()))
if new_order:
data = duck_array_ops.moveaxis(data, range(len(new_order)), new_order)
return self._finalize_indexing_result(dims, data)
def __setitem__(self, key, value):
"""__setitem__ is overloaded to access the underlying numpy values with
orthogonal indexing.
See __getitem__ for more details.
"""
dims, index_tuple, new_order = self._broadcast_indexes(key)
if not isinstance(value, Variable):
value = as_compatible_data(value)
if value.ndim > len(dims):
raise ValueError(
f"shape mismatch: value array of shape {value.shape} could not be "
f"broadcast to indexing result with {len(dims)} dimensions"
)
if value.ndim == 0:
value = Variable((), value)
else:
value = Variable(dims[-value.ndim :], value)
# broadcast to become assignable
value = value.set_dims(dims).data
if new_order:
value = duck_array_ops.asarray(value)
value = value[(len(dims) - value.ndim) * (np.newaxis,) + (Ellipsis,)]
value = duck_array_ops.moveaxis(value, new_order, range(len(new_order)))
indexable = as_indexable(self._data)
indexing.set_with_indexer(indexable, index_tuple, value)
@property
def encoding(self) -> dict[Any, Any]:
"""Dictionary of encodings on this variable."""
if self._encoding is None:
encoding: dict[Any, Any] = {}
self._encoding = encoding
return self._encoding
@encoding.setter
def encoding(self, value):
try:
self._encoding = dict(value)
except ValueError as err:
raise ValueError("encoding must be castable to a dictionary") from err
def reset_encoding(self) -> Self:
warnings.warn(
"reset_encoding is deprecated since 2023.11, use `drop_encoding` instead",
stacklevel=2,
)
return self.drop_encoding()
def drop_encoding(self) -> Self:
"""Return a new Variable without encoding."""
return self._replace(encoding={})
def _copy(
self,
deep: bool = True,
data: T_DuckArray | ArrayLike | None = None,
memo: dict[int, Any] | None = None,
) -> Self:
if data is None:
data_old = self._data
if not isinstance(data_old, indexing.MemoryCachedArray):
ndata = data_old
else:
# don't share caching between copies
# TODO: MemoryCachedArray doesn't match the array api:
ndata = indexing.MemoryCachedArray(data_old.array) # type: ignore[assignment]
if deep:
ndata = copy.deepcopy(ndata, memo)
else:
ndata = as_compatible_data(data)
if self.shape != ndata.shape:
raise ValueError(
f"Data shape {ndata.shape} must match shape of object {self.shape}"
)
attrs = copy.deepcopy(self._attrs, memo) if deep else copy.copy(self._attrs)
encoding = (
copy.deepcopy(self._encoding, memo) if deep else copy.copy(self._encoding)
)
# note: dims is already an immutable tuple
return self._replace(data=ndata, attrs=attrs, encoding=encoding)
def _replace(
self,
dims=_default,
data=_default,
attrs=_default,
encoding=_default,
) -> Self:
if dims is _default:
dims = copy.copy(self._dims)
if data is _default:
data = copy.copy(self.data)
if attrs is _default:
attrs = copy.copy(self._attrs)
if encoding is _default:
encoding = copy.copy(self._encoding)
return type(self)(dims, data, attrs, encoding, fastpath=True)
def load(self, **kwargs) -> Self:
"""Trigger loading data into memory and return this variable.
Data will be computed and/or loaded from disk or a remote source.
Unlike ``.compute``, the original variable is modified and returned.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.array.compute``.
Returns
-------
object : Variable
Same object but with lazy data as an in-memory array.
See Also
--------
dask.array.compute
Variable.compute
Variable.load_async
DataArray.load
Dataset.load
"""
self._data = to_duck_array(self._data, **kwargs)
return self
async def load_async(self, **kwargs) -> Self:
"""Trigger and await asynchronous loading of data into memory and return this variable.
Data will be computed and/or loaded from disk or a remote source.
Unlike ``.compute``, the original variable is modified and returned.
Only works when opening data lazily from IO storage backends which support lazy asynchronous loading.
Otherwise will raise a NotImplementedError.
Note users are expected to limit concurrency themselves - xarray does not internally limit concurrency in any way.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.array.compute``.
Returns
-------
object : Variable
Same object but with lazy data as an in-memory array.
See Also
--------
dask.array.compute
Variable.load
Variable.compute
DataArray.load_async
Dataset.load_async
"""
self._data = await async_to_duck_array(self._data, **kwargs)
return self
def compute(self, **kwargs) -> Self:
"""Trigger loading data into memory and return a new variable.
Data will be computed and/or loaded from disk or a remote source.
The original variable is left unaltered.
Normally, it should not be necessary to call this method in user code,
because all xarray functions should either work on deferred data or
load data automatically.
Parameters
----------
**kwargs : dict
Additional keyword arguments passed on to ``dask.array.compute``.
Returns
-------
object : Variable
New object with the data as an in-memory array.
See Also
--------
dask.array.compute
Variable.load
Variable.load_async
DataArray.compute
Dataset.compute
"""
new = self.copy(deep=False)
return new.load(**kwargs)
def _shuffle(
self, indices: list[list[int]], dim: Hashable, chunks: T_Chunks
) -> Self:
# TODO (dcherian): consider making this public API
array = self._data
if is_chunked_array(array):
chunkmanager = get_chunked_array_type(array)
return self._replace(
data=chunkmanager.shuffle(
array,
indexer=indices,
axis=self.get_axis_num(dim),
chunks=chunks,
)
)
else:
return self.isel({dim: np.concatenate(indices)})
def isel(
self,
indexers: Mapping[Any, Any] | None = None,
missing_dims: ErrorOptionsWithWarn = "raise",
**indexers_kwargs: Any,
) -> Self:
"""Return a new array indexed along the specified dimension(s).
Parameters
----------
**indexers : {dim: indexer, ...}
Keyword arguments with names matching dimensions and values given
by integers, slice objects or arrays.
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
DataArray:
- "raise": raise an exception
- "warn": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
Returns
-------
obj : Array object
A new Array with the selected data and dimensions. In general,
the new variable's data will be a view of this variable's data,
unless numpy fancy indexing was triggered by using an array
indexer, in which case the data will be a copy.
"""
indexers = either_dict_or_kwargs(indexers, indexers_kwargs, "isel")
indexers = drop_dims_from_indexers(indexers, self.dims, missing_dims)
key = tuple(indexers.get(dim, slice(None)) for dim in self.dims)
return self[key]
def squeeze(self, dim=None):
"""Return a new object with squeezed data.
Parameters
----------
dim : None or str or tuple of str, optional
Selects a subset of the length one dimensions. If a dimension is
selected with length greater than one, an error is raised. If
None, all length one dimensions are squeezed.
Returns
-------
squeezed : same type as caller
This object, but with with all or a subset of the dimensions of
length 1 removed.
See Also
--------
numpy.squeeze
"""
dims = common.get_squeeze_dims(self, dim)
return self.isel(dict.fromkeys(dims, 0))
def _shift_one_dim(self, dim, count, fill_value=dtypes.NA):
axis = self.get_axis_num(dim)
if count > 0:
keep = slice(None, -count)
elif count < 0:
keep = slice(-count, None)
else:
keep = slice(None)
trimmed_data = self[(slice(None),) * axis + (keep,)].data
if fill_value is dtypes.NA:
dtype, fill_value = dtypes.maybe_promote(self.dtype)
else:
dtype = self.dtype
width = min(abs(count), self.shape[axis])
dim_pad = (width, 0) if count >= 0 else (0, width)
pads = [(0, 0) if d != dim else dim_pad for d in self.dims]
data = duck_array_ops.pad(
duck_array_ops.astype(trimmed_data, dtype),
pads,
mode="constant",
constant_values=fill_value,
)
if is_duck_dask_array(data):
# chunked data should come out with the same chunks; this makes
# it feasible to combine shifted and unshifted data
# TODO: remove this once dask.array automatically aligns chunks
data = data.rechunk(self.data.chunks)
return self._replace(data=data)
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs):
"""
Return a new Variable with shifted data.
Parameters
----------
shifts : mapping of the form {dim: offset}
Integer offset to shift along each of the given dimensions.
Positive offsets shift to the right; negative offsets shift to the
left.
fill_value : scalar, optional
Value to use for newly missing values
**shifts_kwargs
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
shifted : Variable
Variable with the same dimensions and attributes but shifted data.
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "shift")
result = self
for dim, count in shifts.items():
result = result._shift_one_dim(dim, count, fill_value=fill_value)
return result
def _pad_options_dim_to_index(
self,
pad_option: Mapping[Any, int | float | tuple[int, int] | tuple[float, float]],
fill_with_shape=False,
):
# change number values to a tuple of two of those values
for k, v in pad_option.items():
if isinstance(v, numbers.Number):
pad_option[k] = (v, v)
if fill_with_shape:
return [
pad_option.get(d, (n, n))
for d, n in zip(self.dims, self.data.shape, strict=True)
]
return [pad_option.get(d, (0, 0)) for d in self.dims]
def pad(
self,
pad_width: Mapping[Any, int | tuple[int, int]] | None = None,
mode: PadModeOptions = "constant",
stat_length: (
int | tuple[int, int] | Mapping[Any, tuple[int, int]] | None
) = None,
constant_values: T_VarPadConstantValues | None = None,
end_values: int | tuple[int, int] | Mapping[Any, tuple[int, int]] | None = None,
reflect_type: PadReflectOptions = None,
keep_attrs: bool | None = None,
**pad_width_kwargs: Any,
):
"""
Return a new Variable with padded data.
Parameters
----------
pad_width : mapping of hashable to tuple of int
Mapping with the form of {dim: (pad_before, pad_after)}
describing the number of values padded along each dimension.
{dim: pad} is a shortcut for pad_before = pad_after = pad
mode : str, default: "constant"
See numpy / Dask docs
stat_length : int, tuple or mapping of hashable to tuple
Used in 'maximum', 'mean', 'median', and 'minimum'. Number of
values at edge of each axis used to calculate the statistic value.
constant_values : scalar, tuple or mapping of hashable to scalar or tuple
Used in 'constant'. The values to set the padded values for each
axis.
end_values : scalar, tuple or mapping of hashable to tuple
Used in 'linear_ramp'. The values used for the ending value of the
linear_ramp and that will form the edge of the padded array.
reflect_type : {"even", "odd"}, optional
Used in "reflect", and "symmetric". The "even" style is the
default with an unaltered reflection around the edge value. For
the "odd" style, the extended part of the array is created by
subtracting the reflected values from two times the edge value.
keep_attrs : bool, optional
If True, the variable's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
**pad_width_kwargs
One of pad_width or pad_width_kwargs must be provided.
Returns
-------
padded : Variable
Variable with the same dimensions and attributes but padded data.
"""
pad_width = either_dict_or_kwargs(pad_width, pad_width_kwargs, "pad")
# change default behaviour of pad with mode constant
if mode == "constant" and (
constant_values is None or constant_values is dtypes.NA
):
dtype, constant_values = dtypes.maybe_promote(self.dtype)
else:
dtype = self.dtype
# create pad_options_kwargs, numpy requires only relevant kwargs to be nonempty
if isinstance(stat_length, dict):
stat_length = self._pad_options_dim_to_index(
stat_length, fill_with_shape=True
)
if isinstance(constant_values, dict):
constant_values = self._pad_options_dim_to_index(constant_values)
if isinstance(end_values, dict):
end_values = self._pad_options_dim_to_index(end_values)
# workaround for bug in Dask's default value of stat_length https://github.com/dask/dask/issues/5303
if stat_length is None and mode in ["maximum", "mean", "median", "minimum"]:
stat_length = [(n, n) for n in self.data.shape] # type: ignore[assignment]
pad_width_by_index = self._pad_options_dim_to_index(pad_width)
# create pad_options_kwargs, numpy/dask requires only relevant kwargs to be nonempty
pad_option_kwargs: dict[str, Any] = {}
if stat_length is not None:
pad_option_kwargs["stat_length"] = stat_length
if constant_values is not None:
pad_option_kwargs["constant_values"] = constant_values
if end_values is not None:
pad_option_kwargs["end_values"] = end_values
if reflect_type is not None:
pad_option_kwargs["reflect_type"] = reflect_type
array = duck_array_ops.pad(
duck_array_ops.astype(self.data, dtype, copy=False),
pad_width_by_index,
mode=mode,
**pad_option_kwargs,
)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
attrs = self._attrs if keep_attrs else None
return type(self)(self.dims, array, attrs=attrs)
def _roll_one_dim(self, dim, count):
axis = self.get_axis_num(dim)
count %= self.shape[axis]
if count != 0:
indices = [slice(-count, None), slice(None, -count)]
else:
indices = [slice(None)]
arrays = [self[(slice(None),) * axis + (idx,)].data for idx in indices]
data = duck_array_ops.concatenate(arrays, axis)
if is_duck_dask_array(data):
# chunked data should come out with the same chunks; this makes
# it feasible to combine shifted and unshifted data
# TODO: remove this once dask.array automatically aligns chunks
data = data.rechunk(self.data.chunks)
return self._replace(data=data)
def roll(self, shifts=None, **shifts_kwargs):
"""
Return a new Variable with rolld data.
Parameters
----------
shifts : mapping of hashable to int
Integer offset to roll along each of the given dimensions.
Positive offsets roll to the right; negative offsets roll to the
left.
**shifts_kwargs
The keyword arguments form of ``shifts``.
One of shifts or shifts_kwargs must be provided.
Returns
-------
shifted : Variable
Variable with the same dimensions and attributes but rolled data.
"""
shifts = either_dict_or_kwargs(shifts, shifts_kwargs, "roll")
result = self
for dim, count in shifts.items():
result = result._roll_one_dim(dim, count)
return result
@deprecate_dims
def transpose(
self,
*dim: Hashable | EllipsisType,
missing_dims: ErrorOptionsWithWarn = "raise",
) -> Self:
"""Return a new Variable object with transposed dimensions.
Parameters
----------
*dim : Hashable, optional
By default, reverse the dimensions. Otherwise, reorder the
dimensions to this order.
missing_dims : {"raise", "warn", "ignore"}, default: "raise"
What to do if dimensions that should be selected from are not present in the
Variable:
- "raise": raise an exception
- "warn": raise a warning, and ignore the missing dimensions
- "ignore": ignore the missing dimensions
Returns
-------
transposed : Variable
The returned object has transposed data and dimensions with the
same attributes as the original.
Notes
-----
This operation returns a view of this variable's data. It is
lazy for dask-backed Variables but not for numpy-backed Variables.
See Also
--------
numpy.transpose
"""
if len(dim) == 0:
dim = self.dims[::-1]
else:
dim = tuple(infix_dims(dim, self.dims, missing_dims))
if len(dim) < 2 or dim == self.dims:
# no need to transpose if only one dimension
# or dims are in same order
return self.copy(deep=False)
axes = self.get_axis_num(dim)
data = as_indexable(self._data).transpose(axes)
return self._replace(dims=dim, data=data)
@property
def T(self) -> Self:
return self.transpose()
@deprecate_dims
def set_dims(self, dim, shape=None):
"""Return a new variable with given set of dimensions.
This method might be used to attach new dimension(s) to variable.
When possible, this operation does not copy this variable's data.
Parameters
----------
dim : str or sequence of str or dict
Dimensions to include on the new variable. If a dict, values are
used to provide the sizes of new dimensions; otherwise, new
dimensions are inserted with length 1.
Returns
-------
Variable
"""
if isinstance(dim, str):
dim = [dim]
if shape is None and is_dict_like(dim):
shape = tuple(dim.values())
missing_dims = set(self.dims) - set(dim)
if missing_dims:
raise ValueError(
f"new dimensions {dim!r} must be a superset of "
f"existing dimensions {self.dims!r}"
)
self_dims = set(self.dims)
expanded_dims = tuple(d for d in dim if d not in self_dims) + self.dims
if self.dims == expanded_dims:
# don't use broadcast_to unless necessary so the result remains
# writeable if possible
expanded_data = self.data
elif shape is None or all(
s == 1 for s, e in zip(shape, dim, strict=True) if e not in self_dims
):
# "Trivial" broadcasting, i.e. simply inserting a new dimension
# This is typically easier for duck arrays to implement
# than the full "broadcast_to" semantics
indexer = (None,) * (len(expanded_dims) - self.ndim) + (...,)
expanded_data = self.data[indexer]
else: # elif shape is not None:
dims_map = dict(zip(dim, shape, strict=True))
tmp_shape = tuple(dims_map[d] for d in expanded_dims)
expanded_data = duck_array_ops.broadcast_to(self._data, tmp_shape)
expanded_var = Variable(
expanded_dims, expanded_data, self._attrs, self._encoding, fastpath=True
)
return expanded_var.transpose(*dim)
def _stack_once(self, dim: list[Hashable], new_dim: Hashable):
if not set(dim) <= set(self.dims):
raise ValueError(f"invalid existing dimensions: {dim}")
if new_dim in self.dims:
raise ValueError(
"cannot create a new dimension with the same "
"name as an existing dimension"
)
if len(dim) == 0:
# don't stack
return self.copy(deep=False)
other_dims = [d for d in self.dims if d not in dim]
dim_order = other_dims + list(dim)
reordered = self.transpose(*dim_order)
new_shape = reordered.shape[: len(other_dims)] + (-1,)
new_data = duck_array_ops.reshape(reordered.data, new_shape)
new_dims = reordered.dims[: len(other_dims)] + (new_dim,)
return type(self)(
new_dims, new_data, self._attrs, self._encoding, fastpath=True
)
@partial(deprecate_dims, old_name="dimensions")
def stack(self, dim=None, **dim_kwargs):
"""
Stack any number of existing dim into a single new dimension.
New dim will be added at the end, and the order of the data
along each new dimension will be in contiguous (C) order.
Parameters
----------
dim : mapping of hashable to tuple of hashable
Mapping of form new_name=(dim1, dim2, ...) describing the
names of new dim, and the existing dim that
they replace.
**dim_kwargs
The keyword arguments form of ``dim``.
One of dim or dim_kwargs must be provided.
Returns
-------
stacked : Variable
Variable with the same attributes but stacked data.
See Also
--------
Variable.unstack
"""
dim = either_dict_or_kwargs(dim, dim_kwargs, "stack")
result = self
for new_dim, dims in dim.items():
result = result._stack_once(dims, new_dim)
return result
def _unstack_once_full(self, dim: Mapping[Any, int], old_dim: Hashable) -> Self:
"""
Unstacks the variable without needing an index.
Unlike `_unstack_once`, this function requires the existing dimension to
contain the full product of the new dimensions.
"""
new_dim_names = tuple(dim.keys())
new_dim_sizes = tuple(dim.values())
if old_dim not in self.dims:
raise ValueError(f"invalid existing dimension: {old_dim}")
if set(new_dim_names).intersection(self.dims):
raise ValueError(
"cannot create a new dimension with the same "
"name as an existing dimension"
)
if math.prod(new_dim_sizes) != self.sizes[old_dim]:
raise ValueError(
"the product of the new dimension sizes must "
"equal the size of the old dimension"
)
other_dims = [d for d in self.dims if d != old_dim]
dim_order = other_dims + [old_dim]
reordered = self.transpose(*dim_order)
new_shape = reordered.shape[: len(other_dims)] + new_dim_sizes
new_data = duck_array_ops.reshape(reordered.data, new_shape)
new_dims = reordered.dims[: len(other_dims)] + new_dim_names
return type(self)(
new_dims, new_data, self._attrs, self._encoding, fastpath=True
)
def _unstack_once(
self,
index: pd.MultiIndex,
dim: Hashable,
fill_value=dtypes.NA,
sparse: bool = False,
) -> Variable:
"""
Unstacks this variable given an index to unstack and the name of the
dimension to which the index refers.
"""
reordered = self.transpose(..., dim)
new_dim_sizes = [lev.size for lev in index.levels]
new_dim_names = index.names
indexer = index.codes
# Potentially we could replace `len(other_dims)` with just `-1`
other_dims = [d for d in self.dims if d != dim]
new_shape = tuple(list(reordered.shape[: len(other_dims)]) + new_dim_sizes)
new_dims = reordered.dims[: len(other_dims)] + tuple(new_dim_names)
create_template: Callable
if fill_value is dtypes.NA:
is_missing_values = math.prod(new_shape) > math.prod(self.shape)
if is_missing_values:
dtype, fill_value = dtypes.maybe_promote(self.dtype)
create_template = partial(
duck_array_ops.full_like, fill_value=fill_value
)
else:
dtype = self.dtype
fill_value = dtypes.get_fill_value(dtype)
create_template = duck_array_ops.empty_like
else:
dtype = self.dtype
create_template = partial(duck_array_ops.full_like, fill_value=fill_value)
if sparse:
# unstacking a dense multitindexed array to a sparse array
from sparse import COO
codes = zip(*index.codes, strict=True)
if reordered.ndim == 1:
indexes = codes
else:
sizes = itertools.product(*[range(s) for s in reordered.shape[:-1]])
tuple_indexes = itertools.product(sizes, codes)
indexes = (list(itertools.chain(*x)) for x in tuple_indexes) # type: ignore[assignment]
data = COO(
coords=np.array(list(indexes)).T,
data=self.data.astype(dtype).ravel(),
fill_value=fill_value,
shape=new_shape,
sorted=index.is_monotonic_increasing,
)
else:
data = create_template(self.data, shape=new_shape, dtype=dtype)
# Indexer is a list of lists of locations. Each list is the locations
# on the new dimension. This is robust to the data being sparse; in that
# case the destinations will be NaN / zero.
data[(..., *indexer)] = reordered
return self.to_base_variable()._replace(dims=new_dims, data=data)
@partial(deprecate_dims, old_name="dimensions")
def unstack(self, dim=None, **dim_kwargs) -> Variable:
"""
Unstack an existing dimension into multiple new dimensions.
New dimensions will be added at the end, and the order of the data
along each new dimension will be in contiguous (C) order.
Note that unlike ``DataArray.unstack`` and ``Dataset.unstack``, this
method requires the existing dimension to contain the full product of
the new dimensions.
Parameters
----------
dim : mapping of hashable to mapping of hashable to int
Mapping of the form old_dim={dim1: size1, ...} describing the
names of existing dimensions, and the new dimensions and sizes
that they map to.
**dim_kwargs
The keyword arguments form of ``dim``.
One of dim or dim_kwargs must be provided.
Returns
-------
unstacked : Variable
Variable with the same attributes but unstacked data.
See Also
--------
Variable.stack
DataArray.unstack
Dataset.unstack
"""
dim = either_dict_or_kwargs(dim, dim_kwargs, "unstack")
result = self
for old_dim, dims in dim.items():
result = result._unstack_once_full(dims, old_dim)
return result
def fillna(self, value):
return ops.fillna(self, value)
def where(self, cond, other=dtypes.NA):
return ops.where_method(self, cond, other)
def clip(self, min=None, max=None):
"""
Return an array whose values are limited to ``[min, max]``.
At least one of max or min must be given.
Refer to `numpy.clip` for full documentation.
See Also
--------
numpy.clip : equivalent function
"""
from xarray.computation.apply_ufunc import apply_ufunc
xp = duck_array_ops.get_array_namespace(self.data)
return apply_ufunc(xp.clip, self, min, max, dask="allowed")
def reduce( # type: ignore[override]
self,
func: Callable[..., Any],
dim: Dims = None,
axis: int | Sequence[int] | None = None,
keep_attrs: bool | None = None,
keepdims: bool = False,
**kwargs,
) -> Variable:
"""Reduce this array by applying `func` along some dimension(s).
Parameters
----------
func : callable
Function which can be called in the form
`func(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim : "...", str, Iterable of Hashable or None, optional
Dimension(s) over which to apply `func`. By default `func` is
applied over all dimensions.
axis : int or Sequence of int, optional
Axis(es) over which to apply `func`. Only one of the 'dim'
and 'axis' arguments can be supplied. If neither are supplied, then
the reduction is calculated over the flattened array (by calling
`func(x)` without an axis argument).
keep_attrs : bool, optional
If True (default), the variable's attributes (`attrs`) will be copied from
the original object to the new one. If False, the new
object will be returned without attributes.
keepdims : bool, default: False
If True, the dimensions which are reduced are left in the result
as dimensions of size one
**kwargs : dict
Additional keyword arguments passed on to `func`.
Returns
-------
reduced : Array
Array with summarized data and the indicated dimension(s)
removed.
"""
keep_attrs_ = (
_get_keep_attrs(default=True) if keep_attrs is None else keep_attrs
)
# Note that the call order for Variable.mean is
# Variable.mean -> NamedArray.mean -> Variable.reduce
# -> NamedArray.reduce
result = super().reduce(
func=func, dim=dim, axis=axis, keepdims=keepdims, **kwargs
)
# return Variable always to support IndexVariable
return Variable(
result.dims, result._data, attrs=result._attrs if keep_attrs_ else None
)
@classmethod
def concat(
cls,
variables,
dim="concat_dim",
positions=None,
shortcut=False,
combine_attrs="override",
):
"""Concatenate variables along a new or existing dimension.
Parameters
----------
variables : iterable of Variable
Arrays to stack together. Each variable is expected to have
matching dimensions and shape except for along the stacked
dimension.
dim : str or DataArray, optional
Name of the dimension to stack along. This can either be a new
dimension name, in which case it is added along axis=0, or an
existing dimension name, in which case the location of the
dimension is unchanged. Where to insert the new dimension is
determined by the first variable.
positions : None or list of array-like, optional
List of integer arrays which specifies the integer positions to
which to assign each dataset along the concatenated dimension.
If not supplied, objects are concatenated in the provided order.
shortcut : bool, optional
This option is used internally to speed-up groupby operations.
If `shortcut` is True, some checks of internal consistency between
arrays to concatenate are skipped.
combine_attrs : {"drop", "identical", "no_conflicts", "drop_conflicts", \
"override"}, default: "override"
String indicating how to combine attrs of the objects being merged:
- "drop": empty attrs on returned Dataset.
- "identical": all attrs must be the same on every object.
- "no_conflicts": attrs from all objects are combined, any that have
the same name must also have the same value.
- "drop_conflicts": attrs from all objects are combined, any that have
the same name but different values are dropped.
- "override": skip comparing and copy attrs from the first dataset to
the result.
Returns
-------
stacked : Variable
Concatenated Variable formed by stacking all the supplied variables
along the given dimension.
"""
from xarray.structure.merge import merge_attrs
if not isinstance(dim, str):
(dim,) = dim.dims
# can't do this lazily: we need to loop through variables at least
# twice
variables = list(variables)
first_var = variables[0]
first_var_dims = first_var.dims
arrays = [v._data for v in variables]
if dim in first_var_dims:
axis = first_var.get_axis_num(dim)
dims = first_var_dims
data = duck_array_ops.concatenate(arrays, axis=axis)
if positions is not None:
# TODO: deprecate this option -- we don't need it for groupby
# any more.
indices = nputils.inverse_permutation(np.concatenate(positions))
data = duck_array_ops.take(data, indices, axis=axis)
else:
axis = 0
dims = (dim,) + first_var_dims
data = duck_array_ops.stack(arrays, axis=axis)
attrs = merge_attrs(
[var.attrs for var in variables], combine_attrs=combine_attrs
)
encoding = dict(first_var.encoding)
if not shortcut:
for var in variables:
if var.dims != first_var_dims:
raise ValueError(
f"Variable has dimensions {tuple(var.dims)} but first Variable has dimensions {tuple(first_var_dims)}"
)
return cls(dims, data, attrs, encoding, fastpath=True)
def equals(self, other, equiv=duck_array_ops.array_equiv):
"""True if two Variables have the same dimensions and values;
otherwise False.
Variables can still be equal (like pandas objects) if they have NaN
values in the same locations.
This method is necessary because `v1 == v2` for Variables
does element-wise comparisons (like numpy.ndarrays).
"""
other = getattr(other, "variable", other)
try:
return self.dims == other.dims and (
self._data is other._data or equiv(self.data, other.data)
)
except (TypeError, AttributeError):
return False
def broadcast_equals(self, other, equiv=duck_array_ops.array_equiv):
"""True if two Variables have the values after being broadcast against
each other; otherwise False.
Variables can still be equal (like pandas objects) if they have NaN
values in the same locations.
"""
try:
self, other = broadcast_variables(self, other)
except (ValueError, AttributeError):
return False
return self.equals(other, equiv=equiv)
def identical(self, other, equiv=duck_array_ops.array_equiv):
"""Like equals, but also checks attributes."""
try:
return utils.dict_equiv(self.attrs, other.attrs) and self.equals(
other, equiv=equiv
)
except (TypeError, AttributeError):
return False
def no_conflicts(self, other, equiv=duck_array_ops.array_notnull_equiv):
"""True if the intersection of two Variable's non-null data is
equal; otherwise false.
Variables can thus still be equal if there are locations where either,
or both, contain NaN values.
"""
return self.broadcast_equals(other, equiv=equiv)
def quantile(
self,
q: ArrayLike,
dim: str | Sequence[Hashable] | None = None,
method: QuantileMethods = "linear",
keep_attrs: bool | None = None,
skipna: bool | None = None,
interpolation: QuantileMethods | None = None,
) -> Self:
"""Compute the qth quantile of the data along the specified dimension.
Returns the qth quantiles(s) of the array elements.
Parameters
----------
q : float or sequence of float
Quantile to compute, which must be between 0 and 1
inclusive.
dim : str or sequence of str, optional
Dimension(s) over which to apply quantile.
method : str, default: "linear"
This optional parameter specifies the interpolation method to use when the
desired quantile lies between two data points. The options sorted by their R
type as summarized in the H&F paper [1]_ are:
1. "inverted_cdf"
2. "averaged_inverted_cdf"
3. "closest_observation"
4. "interpolated_inverted_cdf"
5. "hazen"
6. "weibull"
7. "linear" (default)
8. "median_unbiased"
9. "normal_unbiased"
The first three methods are discontiuous. The following discontinuous
variations of the default "linear" (7.) option are also available:
* "lower"
* "higher"
* "midpoint"
* "nearest"
See :py:func:`numpy.quantile` or [1]_ for details. The "method" argument
was previously called "interpolation", renamed in accordance with numpy
version 1.22.0.
keep_attrs : bool, optional
If True, the variable's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
quantiles : Variable
If `q` is a single quantile, then the result
is a scalar. If multiple percentiles are given, first axis of
the result corresponds to the quantile and a quantile dimension
is added to the return array. The other dimensions are the
dimensions that remain after the reduction of the array.
See Also
--------
numpy.nanquantile, pandas.Series.quantile, Dataset.quantile
DataArray.quantile
References
----------
.. [1] R. J. Hyndman and Y. Fan,
"Sample quantiles in statistical packages,"
The American Statistician, 50(4), pp. 361-365, 1996
"""
from xarray.computation.apply_ufunc import apply_ufunc
if interpolation is not None:
warnings.warn(
"The `interpolation` argument to quantile was renamed to `method`.",
FutureWarning,
stacklevel=2,
)
if method != "linear":
raise TypeError("Cannot pass interpolation and method keywords!")
method = interpolation
if skipna or (skipna is None and self.dtype.kind in "cfO"):
_quantile_func = nputils.nanquantile
else:
_quantile_func = duck_array_ops.quantile
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
scalar = utils.is_scalar(q)
q = np.atleast_1d(np.asarray(q, dtype=np.float64))
if dim is None:
dim = self.dims
if utils.is_scalar(dim):
dim = [dim]
xp = duck_array_ops.get_array_namespace(self.data)
def _wrapper(npa, **kwargs):
# move quantile axis to end. required for apply_ufunc
return xp.moveaxis(_quantile_func(npa, **kwargs), 0, -1)
# jax requires hashable
axis = tuple(range(-1, -1 * len(dim) - 1, -1))
kwargs = {"q": q, "axis": axis, "method": method}
result = apply_ufunc(
_wrapper,
self,
input_core_dims=[dim],
exclude_dims=set(dim),
output_core_dims=[["quantile"]],
output_dtypes=[np.float64],
dask_gufunc_kwargs=dict(output_sizes={"quantile": len(q)}),
dask="allowed" if module_available("dask", "2024.11.0") else "parallelized",
kwargs=kwargs,
)
# for backward compatibility
result = result.transpose("quantile", ...)
if scalar:
result = result.squeeze("quantile")
if keep_attrs:
result.attrs = self._attrs
return result
def rank(self, dim, pct=False):
"""Ranks the data.
Equal values are assigned a rank that is the average of the ranks that
would have been otherwise assigned to all of the values within that
set. Ranks begin at 1, not 0. If `pct`, computes percentage ranks.
NaNs in the input array are returned as NaNs.
The `bottleneck` library is required.
Parameters
----------
dim : str
Dimension over which to compute rank.
pct : bool, optional
If True, compute percentage ranks, otherwise compute integer ranks.
Returns
-------
ranked : Variable
See Also
--------
Dataset.rank, DataArray.rank
"""
# This could / should arguably be implemented at the DataArray & Dataset level
if not OPTIONS["use_bottleneck"]:
raise RuntimeError(
"rank requires bottleneck to be enabled."
" Call `xr.set_options(use_bottleneck=True)` to enable it."
)
import bottleneck as bn
func = bn.nanrankdata if self.dtype.kind == "f" else bn.rankdata
ranked = xr.apply_ufunc(
func,
self,
input_core_dims=[[dim]],
output_core_dims=[[dim]],
dask="parallelized",
kwargs=dict(axis=-1),
).transpose(*self.dims)
if pct:
count = self.notnull().sum(dim)
ranked /= count
return ranked
@_deprecate_positional_args("v2024.11.0")
def rolling_window(
self,
dim,
window,
window_dim,
*,
center=False,
fill_value=dtypes.NA,
**kwargs,
):
"""
Make a rolling_window along dim and add a new_dim to the last place.
Parameters
----------
dim : str
Dimension over which to compute rolling_window.
For nd-rolling, should be list of dimensions.
window : int
Window size of the rolling
For nd-rolling, should be list of integers.
window_dim : str
New name of the window dimension.
For nd-rolling, should be list of strings.
center : bool, default: False
If True, pad fill_value for both ends. Otherwise, pad in the head
of the axis.
fill_value
value to be filled.
**kwargs
Keyword arguments that should be passed to the underlying array type's
``sliding_window_view`` function.
Returns
-------
Variable that is a view of the original array with a added dimension of
size w.
The return dim: self.dims + (window_dim, )
The return shape: self.shape + (window, )
See Also
--------
numpy.lib.stride_tricks.sliding_window_view
dask.array.lib.stride_tricks.sliding_window_view
Examples
--------
>>> v = Variable(("a", "b"), np.arange(8).reshape((2, 4)))
>>> v.rolling_window("b", 3, "window_dim")
<xarray.Variable (a: 2, b: 4, window_dim: 3)> Size: 192B
array([[[nan, nan, 0.],
[nan, 0., 1.],
[ 0., 1., 2.],
[ 1., 2., 3.]],
<BLANKLINE>
[[nan, nan, 4.],
[nan, 4., 5.],
[ 4., 5., 6.],
[ 5., 6., 7.]]])
>>> v.rolling_window("b", 3, "window_dim", center=True)
<xarray.Variable (a: 2, b: 4, window_dim: 3)> Size: 192B
array([[[nan, 0., 1.],
[ 0., 1., 2.],
[ 1., 2., 3.],
[ 2., 3., nan]],
<BLANKLINE>
[[nan, 4., 5.],
[ 4., 5., 6.],
[ 5., 6., 7.],
[ 6., 7., nan]]])
"""
if fill_value is dtypes.NA: # np.nan is passed
dtype, fill_value = dtypes.maybe_promote(self.dtype)
var = duck_array_ops.astype(self, dtype, copy=False)
else:
dtype = self.dtype
var = self
if utils.is_scalar(dim):
for name, arg in zip(
["window", "window_dim", "center"],
[window, window_dim, center],
strict=True,
):
if not utils.is_scalar(arg):
raise ValueError(
f"Expected {name}={arg!r} to be a scalar like 'dim'."
)
dim = (dim,)
# dim is now a list
nroll = len(dim)
if utils.is_scalar(window):
window = [window] * nroll
if utils.is_scalar(window_dim):
window_dim = [window_dim] * nroll
if utils.is_scalar(center):
center = [center] * nroll
if (
len(dim) != len(window)
or len(dim) != len(window_dim)
or len(dim) != len(center)
):
raise ValueError(
"'dim', 'window', 'window_dim', and 'center' must be the same length. "
f"Received dim={dim!r}, window={window!r}, window_dim={window_dim!r},"
f" and center={center!r}."
)
pads = {}
for d, win, cent in zip(dim, window, center, strict=True):
if cent:
start = win // 2 # 10 -> 5, 9 -> 4
end = win - 1 - start
pads[d] = (start, end)
else:
pads[d] = (win - 1, 0)
padded = var.pad(pads, mode="constant", constant_values=fill_value)
axis = self.get_axis_num(dim)
new_dims = self.dims + tuple(window_dim)
return Variable(
new_dims,
duck_array_ops.sliding_window_view(
padded.data, window_shape=window, axis=axis, **kwargs
),
)
def coarsen(
self, windows, func, boundary="exact", side="left", keep_attrs=None, **kwargs
):
"""
Apply reduction function.
"""
windows = {k: v for k, v in windows.items() if k in self.dims}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
if keep_attrs:
_attrs = self.attrs
else:
_attrs = None
if not windows:
return self._replace(attrs=_attrs)
reshaped, axes = self.coarsen_reshape(windows, boundary, side)
if isinstance(func, str):
name = func
func = getattr(duck_array_ops, name, None)
if func is None:
raise NameError(f"{name} is not a valid method.")
return self._replace(data=func(reshaped, axis=axes, **kwargs), attrs=_attrs)
def coarsen_reshape(self, windows, boundary, side):
"""
Construct a reshaped-array for coarsen
"""
if not is_dict_like(boundary):
boundary = dict.fromkeys(windows.keys(), boundary)
if not is_dict_like(side):
side = dict.fromkeys(windows.keys(), side)
# remove unrelated dimensions
boundary = {k: v for k, v in boundary.items() if k in windows}
side = {k: v for k, v in side.items() if k in windows}
for d, window in windows.items():
if window <= 0:
raise ValueError(
f"window must be > 0. Given {window} for dimension {d}"
)
variable = self
pad_widths = {}
for d, window in windows.items():
# trim or pad the object
size = variable.shape[self._get_axis_num(d)]
n = int(size / window)
if boundary[d] == "exact":
if n * window != size:
raise ValueError(
f"Could not coarsen a dimension of size {size} with "
f"window {window} and boundary='exact'. Try a different 'boundary' option."
)
elif boundary[d] == "trim":
if side[d] == "left":
variable = variable.isel({d: slice(0, window * n)})
else:
excess = size - window * n
variable = variable.isel({d: slice(excess, None)})
elif boundary[d] == "pad": # pad
pad = window * n - size
if pad < 0:
pad += window
elif pad == 0:
continue
pad_widths[d] = (0, pad) if side[d] == "left" else (pad, 0)
else:
raise TypeError(
f"{boundary[d]} is invalid for boundary. Valid option is 'exact', "
"'trim' and 'pad'"
)
if pad_widths:
variable = variable.pad(pad_widths, mode="constant")
shape = []
axes = []
axis_count = 0
for i, d in enumerate(variable.dims):
if d in windows:
size = variable.shape[i]
shape.extend((int(size / windows[d]), windows[d]))
axis_count += 1
axes.append(i + axis_count)
else:
shape.append(variable.shape[i])
return duck_array_ops.reshape(variable.data, shape), tuple(axes)
def isnull(self, keep_attrs: bool | None = None):
"""Test each value in the array for whether it is a missing value.
Returns
-------
isnull : Variable
Same type and shape as object, but the dtype of the data is bool.
See Also
--------
pandas.isnull
Examples
--------
>>> var = xr.Variable("x", [1, np.nan, 3])
>>> var
<xarray.Variable (x: 3)> Size: 24B
array([ 1., nan, 3.])
>>> var.isnull()
<xarray.Variable (x: 3)> Size: 3B
array([False, True, False])
"""
from xarray.computation.apply_ufunc import apply_ufunc
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
return apply_ufunc(
duck_array_ops.isnull,
self,
dask="allowed",
keep_attrs=keep_attrs,
)
def notnull(self, keep_attrs: bool | None = None):
"""Test each value in the array for whether it is not a missing value.
Returns
-------
notnull : Variable
Same type and shape as object, but the dtype of the data is bool.
See Also
--------
pandas.notnull
Examples
--------
>>> var = xr.Variable("x", [1, np.nan, 3])
>>> var
<xarray.Variable (x: 3)> Size: 24B
array([ 1., nan, 3.])
>>> var.notnull()
<xarray.Variable (x: 3)> Size: 3B
array([ True, False, True])
"""
from xarray.computation.apply_ufunc import apply_ufunc
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
return apply_ufunc(
duck_array_ops.notnull,
self,
dask="allowed",
keep_attrs=keep_attrs,
)
@property
def imag(self) -> Variable:
"""
The imaginary part of the variable.
See Also
--------
numpy.ndarray.imag
"""
return self._new(data=self.data.imag)
@property
def real(self) -> Variable:
"""
The real part of the variable.
See Also
--------
numpy.ndarray.real
"""
return self._new(data=self.data.real)
def __array_wrap__(self, obj, context=None, return_scalar=False):
return Variable(self.dims, obj)
def _unary_op(self, f, *args, **kwargs):
keep_attrs = kwargs.pop("keep_attrs", None)
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
with np.errstate(all="ignore"):
result = self.__array_wrap__(f(self.data, *args, **kwargs))
if keep_attrs:
result.attrs = self.attrs
return result
def _binary_op(self, other, f, reflexive=False):
if isinstance(other, xr.DataTree | xr.DataArray | xr.Dataset):
return NotImplemented
if reflexive and issubclass(type(self), type(other)):
other_data, self_data, dims = _broadcast_compat_data(other, self)
else:
self_data, other_data, dims = _broadcast_compat_data(self, other)
keep_attrs = _get_keep_attrs(default=True)
if keep_attrs:
# Combine attributes from both operands, dropping conflicts
from xarray.structure.merge import merge_attrs
# Access attrs property to normalize None to {} due to property side effect
self_attrs = self.attrs
other_attrs = getattr(other, "attrs", {})
attrs = merge_attrs([self_attrs, other_attrs], "drop_conflicts")
else:
attrs = None
with np.errstate(all="ignore"):
new_data = (
f(self_data, other_data) if not reflexive else f(other_data, self_data)
)
result = Variable(dims, new_data, attrs=attrs)
return result
def _inplace_binary_op(self, other, f):
if isinstance(other, xr.Dataset):
raise TypeError("cannot add a Dataset to a Variable in-place")
self_data, other_data, dims = _broadcast_compat_data(self, other)
if dims != self.dims:
raise ValueError("dimensions cannot change for in-place operations")
with np.errstate(all="ignore"):
self.values = f(self_data, other_data)
return self
def _to_numeric(self, offset=None, datetime_unit=None, dtype=float):
"""A (private) method to convert datetime array to numeric dtype
See duck_array_ops.datetime_to_numeric
"""
numeric_array = duck_array_ops.datetime_to_numeric(
self.data, offset, datetime_unit, dtype
)
return type(self)(self.dims, numeric_array, self._attrs)
def _unravel_argminmax(
self,
argminmax: str,
dim: Dims,
axis: int | None,
keep_attrs: bool | None,
skipna: bool | None,
) -> Variable | dict[Hashable, Variable]:
"""Apply argmin or argmax over one or more dimensions, returning the result as a
dict of DataArray that can be passed directly to isel.
"""
if dim is None and axis is None:
warnings.warn(
"Behaviour of argmin/argmax with neither dim nor axis argument will "
"change to return a dict of indices of each dimension. To get a "
"single, flat index, please use np.argmin(da.data) or "
"np.argmax(da.data) instead of da.argmin() or da.argmax().",
DeprecationWarning,
stacklevel=3,
)
argminmax_func = getattr(duck_array_ops, argminmax)
if dim is ...:
# In future, should do this also when (dim is None and axis is None)
dim = self.dims
if (
dim is None
or axis is not None
or not isinstance(dim, Sequence)
or isinstance(dim, str)
):
# Return int index if single dimension is passed, and is not part of a
# sequence
return self.reduce(
argminmax_func, dim=dim, axis=axis, keep_attrs=keep_attrs, skipna=skipna
)
# Get a name for the new dimension that does not conflict with any existing
# dimension
newdimname = "_unravel_argminmax_dim_0"
count = 1
while newdimname in self.dims:
newdimname = f"_unravel_argminmax_dim_{count}"
count += 1
stacked = self.stack({newdimname: dim})
result_dims = stacked.dims[:-1]
reduce_shape = tuple(self.sizes[d] for d in dim)
result_flat_indices = stacked.reduce(argminmax_func, axis=-1, skipna=skipna)
result_unravelled_indices = duck_array_ops.unravel_index(
result_flat_indices.data, reduce_shape
)
result = {
d: Variable(dims=result_dims, data=i)
for d, i in zip(dim, result_unravelled_indices, strict=True)
}
if keep_attrs is None:
keep_attrs = _get_keep_attrs(default=True)
if keep_attrs:
for v in result.values():
v.attrs = self.attrs
return result
def argmin(
self,
dim: Dims = None,
axis: int | None = None,
keep_attrs: bool | None = None,
skipna: bool | None = None,
) -> Variable | dict[Hashable, Variable]:
"""Index or indices of the minimum of the Variable over one or more dimensions.
If a sequence is passed to 'dim', then result returned as dict of Variables,
which can be passed directly to isel(). If a single str is passed to 'dim' then
returns a Variable with dtype int.
If there are multiple minima, the indices of the first one found will be
returned.
Parameters
----------
dim : "...", str, Iterable of Hashable or None, optional
The dimensions over which to find the minimum. By default, finds minimum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will return a dict with indices for all
dimensions; to return a dict with all dimensions now, pass '...'.
axis : int, optional
Axis over which to apply `argmin`. Only one of the 'dim' and 'axis' arguments
can be supplied.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Variable or dict of Variable
See Also
--------
DataArray.argmin, DataArray.idxmin
"""
return self._unravel_argminmax("argmin", dim, axis, keep_attrs, skipna)
def argmax(
self,
dim: Dims = None,
axis: int | None = None,
keep_attrs: bool | None = None,
skipna: bool | None = None,
) -> Variable | dict[Hashable, Variable]:
"""Index or indices of the maximum of the Variable over one or more dimensions.
If a sequence is passed to 'dim', then result returned as dict of Variables,
which can be passed directly to isel(). If a single str is passed to 'dim' then
returns a Variable with dtype int.
If there are multiple maxima, the indices of the first one found will be
returned.
Parameters
----------
dim : "...", str, Iterable of Hashable or None, optional
The dimensions over which to find the maximum. By default, finds maximum over
all dimensions - for now returning an int for backward compatibility, but
this is deprecated, in future will return a dict with indices for all
dimensions; to return a dict with all dimensions now, pass '...'.
axis : int, optional
Axis over which to apply `argmin`. Only one of the 'dim' and 'axis' arguments
can be supplied.
keep_attrs : bool, optional
If True, the attributes (`attrs`) will be copied from the original
object to the new one. If False (default), the new object will be
returned without attributes.
skipna : bool, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or skipna=True has not been
implemented (object, datetime64 or timedelta64).
Returns
-------
result : Variable or dict of Variable
See Also
--------
DataArray.argmax, DataArray.idxmax
"""
return self._unravel_argminmax("argmax", dim, axis, keep_attrs, skipna)
def _as_sparse(self, sparse_format=_default, fill_value=_default) -> Variable:
"""
Use sparse-array as backend.
"""
from xarray.namedarray._typing import _default as _default_named
if sparse_format is _default:
sparse_format = _default_named
if fill_value is _default:
fill_value = _default_named
out = super()._as_sparse(sparse_format, fill_value)
return cast("Variable", out)
def _to_dense(self) -> Variable:
"""
Change backend from sparse to np.array.
"""
out = super()._to_dense()
return cast("Variable", out)
def chunk( # type: ignore[override]
self,
chunks: T_Chunks = {}, # noqa: B006 # even though it's technically unsafe, it is being used intentionally here (#4667)
name: str | None = None,
lock: bool | None = None,
inline_array: bool | None = None,
chunked_array_type: str | ChunkManagerEntrypoint[Any] | None = None,
from_array_kwargs: Any = None,
**chunks_kwargs: Any,
) -> Self:
"""Coerce this array's data into a dask array with the given chunks.
If this variable is a non-dask array, it will be converted to dask
array. If it's a dask array, it will be rechunked to the given chunk
sizes.
If neither chunks is not provided for one or more dimensions, chunk
sizes along that dimension will not be updated; non-dask arrays will be
converted into dask arrays with a single block.
Parameters
----------
chunks : int, tuple or dict, optional
Chunk sizes along each dimension, e.g., ``5``, ``(5, 5)`` or
``{'x': 5, 'y': 5}``.
name : str, optional
Used to generate the name for this array in the internal dask
graph. Does not need not be unique.
lock : bool, default: False
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
inline_array : bool, default: False
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
chunked_array_type: str, optional
Which chunked array type to coerce this datasets' arrays to.
Defaults to 'dask' if installed, else whatever is registered via the `ChunkManagerEntrypoint` system.
Experimental API that should not be relied upon.
from_array_kwargs: dict, optional
Additional keyword arguments passed on to the `ChunkManagerEntrypoint.from_array` method used to create
chunked arrays, via whichever chunk manager is specified through the `chunked_array_type` kwarg.
For example, with dask as the default chunked array type, this method would pass additional kwargs
to :py:func:`dask.array.from_array`. Experimental API that should not be relied upon.
**chunks_kwargs : {dim: chunks, ...}, optional
The keyword arguments form of ``chunks``.
One of chunks or chunks_kwargs must be provided.
Returns
-------
chunked : xarray.Variable
See Also
--------
Variable.chunks
Variable.chunksizes
xarray.unify_chunks
dask.array.from_array
"""
if from_array_kwargs is None:
from_array_kwargs = {}
# TODO deprecate passing these dask-specific arguments explicitly. In future just pass everything via from_array_kwargs
_from_array_kwargs = consolidate_dask_from_array_kwargs(
from_array_kwargs,
name=name,
lock=lock,
inline_array=inline_array,
)
return super().chunk(
chunks=chunks,
chunked_array_type=chunked_array_type,
from_array_kwargs=_from_array_kwargs,
**chunks_kwargs,
)
| Variable |
python | pypa__pip | src/pip/_vendor/pkg_resources/__init__.py | {
"start": 8335,
"end": 8510
} | class ____(Exception):
"""Abstract base for dependency resolution errors"""
def __repr__(self):
return self.__class__.__name__ + repr(self.args)
| ResolutionError |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_spec.py | {
"start": 383,
"end": 8144
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'default_backend': 'V1IngressBackend',
'ingress_class_name': 'str',
'rules': 'list[V1IngressRule]',
'tls': 'list[V1IngressTLS]'
}
attribute_map = {
'default_backend': 'defaultBackend',
'ingress_class_name': 'ingressClassName',
'rules': 'rules',
'tls': 'tls'
}
def __init__(self, default_backend=None, ingress_class_name=None, rules=None, tls=None, local_vars_configuration=None): # noqa: E501
"""V1IngressSpec - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._default_backend = None
self._ingress_class_name = None
self._rules = None
self._tls = None
self.discriminator = None
if default_backend is not None:
self.default_backend = default_backend
if ingress_class_name is not None:
self.ingress_class_name = ingress_class_name
if rules is not None:
self.rules = rules
if tls is not None:
self.tls = tls
@property
def default_backend(self):
"""Gets the default_backend of this V1IngressSpec. # noqa: E501
:return: The default_backend of this V1IngressSpec. # noqa: E501
:rtype: V1IngressBackend
"""
return self._default_backend
@default_backend.setter
def default_backend(self, default_backend):
"""Sets the default_backend of this V1IngressSpec.
:param default_backend: The default_backend of this V1IngressSpec. # noqa: E501
:type: V1IngressBackend
"""
self._default_backend = default_backend
@property
def ingress_class_name(self):
"""Gets the ingress_class_name of this V1IngressSpec. # noqa: E501
ingressClassName is the name of an IngressClass cluster resource. Ingress controller implementations use this field to know whether they should be serving this Ingress resource, by a transitive connection (controller -> IngressClass -> Ingress resource). Although the `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined, it was widely supported by Ingress controllers to create a direct binding between Ingress controller and Ingress resources. Newly created Ingress resources should prefer using the field. However, even though the annotation is officially deprecated, for backwards compatibility reasons, ingress controllers should still honor that annotation if present. # noqa: E501
:return: The ingress_class_name of this V1IngressSpec. # noqa: E501
:rtype: str
"""
return self._ingress_class_name
@ingress_class_name.setter
def ingress_class_name(self, ingress_class_name):
"""Sets the ingress_class_name of this V1IngressSpec.
ingressClassName is the name of an IngressClass cluster resource. Ingress controller implementations use this field to know whether they should be serving this Ingress resource, by a transitive connection (controller -> IngressClass -> Ingress resource). Although the `kubernetes.io/ingress.class` annotation (simple constant name) was never formally defined, it was widely supported by Ingress controllers to create a direct binding between Ingress controller and Ingress resources. Newly created Ingress resources should prefer using the field. However, even though the annotation is officially deprecated, for backwards compatibility reasons, ingress controllers should still honor that annotation if present. # noqa: E501
:param ingress_class_name: The ingress_class_name of this V1IngressSpec. # noqa: E501
:type: str
"""
self._ingress_class_name = ingress_class_name
@property
def rules(self):
"""Gets the rules of this V1IngressSpec. # noqa: E501
rules is a list of host rules used to configure the Ingress. If unspecified, or no rule matches, all traffic is sent to the default backend. # noqa: E501
:return: The rules of this V1IngressSpec. # noqa: E501
:rtype: list[V1IngressRule]
"""
return self._rules
@rules.setter
def rules(self, rules):
"""Sets the rules of this V1IngressSpec.
rules is a list of host rules used to configure the Ingress. If unspecified, or no rule matches, all traffic is sent to the default backend. # noqa: E501
:param rules: The rules of this V1IngressSpec. # noqa: E501
:type: list[V1IngressRule]
"""
self._rules = rules
@property
def tls(self):
"""Gets the tls of this V1IngressSpec. # noqa: E501
tls represents the TLS configuration. Currently the Ingress only supports a single TLS port, 443. If multiple members of this list specify different hosts, they will be multiplexed on the same port according to the hostname specified through the SNI TLS extension, if the ingress controller fulfilling the ingress supports SNI. # noqa: E501
:return: The tls of this V1IngressSpec. # noqa: E501
:rtype: list[V1IngressTLS]
"""
return self._tls
@tls.setter
def tls(self, tls):
"""Sets the tls of this V1IngressSpec.
tls represents the TLS configuration. Currently the Ingress only supports a single TLS port, 443. If multiple members of this list specify different hosts, they will be multiplexed on the same port according to the hostname specified through the SNI TLS extension, if the ingress controller fulfilling the ingress supports SNI. # noqa: E501
:param tls: The tls of this V1IngressSpec. # noqa: E501
:type: list[V1IngressTLS]
"""
self._tls = tls
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1IngressSpec):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1IngressSpec):
return True
return self.to_dict() != other.to_dict()
| V1IngressSpec |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator_test.py | {
"start": 38885,
"end": 41819
} | class ____(TestCaseWithErrorReportingThread):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.coordinator = make_coordinator(
num_workers=5, num_ps=2,
partitioner=sharded_variable.FixedShardsPartitioner(3))
cls.strategy = cls.coordinator.strategy
def testEmbeddingLookup(self):
# Verify lookup ops use optimized implementations with ClusterCoordinator
with self.strategy.scope():
sv = variables.Variable(initial_value=np.arange(10).reshape((5, 2)) + 1,
dtype=dtypes.float32)
@def_function.function
def lookup():
ids = constant_op.constant([0, 3, 4])
return embedding_ops.embedding_lookup_v2(sv, ids)
@def_function.function
def sparse_lookup():
sp_ids = sparse_tensor.SparseTensor(
indices=[[0, 0], [0, 1], [1, 0], [2, 2]],
values=[0, 3, 4, 1],
dense_shape=[3, 3])
return embedding_ops.embedding_lookup_sparse_v2(sv, sp_ids, None)
@def_function.function
def safe_sparse_lookup():
sp_ids = sparse_tensor.SparseTensor(
indices=[[0, 0], [0, 1], [1, 0], [2, 2]],
values=[0, -1, 4, 1],
dense_shape=[3, 3])
sp_weights = sparse_tensor.SparseTensor(
indices=[[0, 0], [0, 1], [1, 0], [2, 2]],
values=[1., 1., -1., 1.],
dense_shape=[3, 3])
return embedding_ops.safe_embedding_lookup_sparse_v2(
sv, sp_ids, sp_weights)
results = []
for func in [lookup, sparse_lookup, safe_sparse_lookup]:
# Manually create Closure so we can inspect its graph
closure = coordinator_lib.Closure(
func,
self.coordinator._cluster.closure_queue._cancellation_mgr) # pylint: disable=protected-access
result = closure.build_output_remote_value()
self.coordinator._cluster.closure_queue.put(closure)
graph = closure._concrete_function.graph
num_gather_ops = 0
num_rv_ops = 0
for op in graph.get_operations():
if op.type == 'ResourceGather':
num_gather_ops += 1
if op.type == 'ReadVariableOp':
num_rv_ops += 1
self.assertEqual(
num_gather_ops, len(sv.variables), 'Number of ResourceGather op '
f'({num_gather_ops}) does not match expected ({len(sv.variables)}), '
'possibly due to ShardedVariable accidentally being converted to '
f'tensor in {func.__name__} ops.')
self.assertEqual(
num_rv_ops, 0, f'Function {func.__name__} graph has some '
'ReadVariableOps, possibly due to ShardedVariable accidentally being '
'converted to tensor')
results.append(result)
self.assertAllEqual(results[0].fetch(), [[1., 2.], [7., 8.], [9., 10.]])
self.assertAllClose(results[1].fetch(), [[4., 5.], [9., 10.], [3., 4.]])
self.assertAllClose(results[2].fetch(), [[1., 2.], [0., 0.], [3., 4.]])
| ShardedVariableTest |
python | getsentry__sentry | src/sentry/notifications/notifications/activity/resolved.py | {
"start": 142,
"end": 415
} | class ____(GroupActivityNotification):
metrics_key = "resolved_activity"
title = "Resolved Issue"
def get_description(self) -> tuple[str, str | None, Mapping[str, Any]]:
return "{author} marked {an issue} as resolved", None, {}
| ResolvedActivityNotification |
python | pyinstaller__pyinstaller | bootloader/waflib/Errors.py | {
"start": 1123,
"end": 1170
} | class ____(WafError):
pass
| ConfigurationError |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 110484,
"end": 112486
} | class ____(Request):
"""
Get histogram data of all the scalar metrics and variants in the task
:param task: Task ID
:type task: str
:param metric:
:type metric: str
:param variant:
:type variant: str
"""
_service = "events"
_action = "vector_metrics_iter_histogram"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"metric": {"description": "", "type": "string"},
"task": {"description": "Task ID", "type": "string"},
"variant": {"description": "", "type": "string"},
},
"required": ["task", "metric", "variant"],
"type": "object",
}
def __init__(self, task: str, metric: str, variant: str, **kwargs: Any) -> None:
super(VectorMetricsIterHistogramRequest, self).__init__(**kwargs)
self.task = task
self.metric = metric
self.variant = variant
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("metric")
def metric(self) -> str:
return self._property_metric
@metric.setter
def metric(self, value: str) -> None:
if value is None:
self._property_metric = None
return
self.assert_isinstance(value, "metric", six.string_types)
self._property_metric = value
@schema_property("variant")
def variant(self) -> str:
return self._property_variant
@variant.setter
def variant(self, value: str) -> None:
if value is None:
self._property_variant = None
return
self.assert_isinstance(value, "variant", six.string_types)
self._property_variant = value
| VectorMetricsIterHistogramRequest |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/testing/codegen.py | {
"start": 1118,
"end": 1296
} | class ____(NodeSampler):
sample_map = dict((
(gast.Assign, 10),
(gast.Print, 1),
(gast.If, 2),
(gast.While, 2),
(gast.For, 0),
))
| StatementSampler |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 1371,
"end": 2031
} | class ____(nn.Module):
"""
Module that applies gated attention to input data.
Args:
in_size (`int`): The input size.
out_size (`int`): The output size.
"""
def __init__(self, in_size: int, out_size: int):
super().__init__()
self.attn_layer = nn.Linear(in_size, out_size)
self.attn_softmax = nn.Softmax(dim=-1)
def forward(self, inputs):
attn_weight = self.attn_softmax(self.attn_layer(inputs))
inputs = inputs * attn_weight
return inputs
# Copied from transformers.models.patchtst.modeling_patchtst.PatchTSTBatchNorm with PatchTST->PatchTSMixer
| PatchTSMixerGatedAttention |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 26836,
"end": 30149
} | class ____(BooleanFunction):
"""
Logical Not function (negation)
Returns ``true`` if the statement is ``false`` or ``False``.
Returns ``false`` if the statement is ``true`` or ``True``.
Examples
========
>>> from sympy import Not, And, Or
>>> from sympy.abc import x, A, B
>>> Not(True)
False
>>> Not(False)
True
>>> Not(And(True, False))
True
>>> Not(Or(True, False))
False
>>> Not(And(And(True, x), Or(x, False)))
~x
>>> ~x
~x
>>> Not(And(Or(A, B), Or(~A, ~B)))
~((A | B) & (~A | ~B))
Notes
=====
- The ``~`` operator is provided as a convenience, but note that its use
here is different from its normal use in Python, which is bitwise
not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is
an integer. Furthermore, since bools in Python subclass from ``int``,
``~True`` is the same as ``~1`` which is ``-2``, which has a boolean
value of True. To avoid this issue, use the SymPy boolean types
``true`` and ``false``.
- As of Python 3.12, the bitwise not operator ``~`` used on a
Python ``bool`` is deprecated and will emit a warning.
>>> from sympy import true
>>> ~True # doctest: +SKIP
-2
>>> ~true
False
"""
is_Not = True
@classmethod
def eval(cls, arg):
if isinstance(arg, Number) or arg in (True, False):
return false if arg else true
if arg.is_Not:
return arg.args[0]
# Simplify Relational objects.
if arg.is_Relational:
return arg.negated
def _eval_as_set(self):
"""
Rewrite logic operators and relationals in terms of real sets.
Examples
========
>>> from sympy import Not, Symbol
>>> x = Symbol('x')
>>> Not(x > 0).as_set()
Interval(-oo, 0)
"""
return self.args[0].as_set().complement(S.Reals)
def to_nnf(self, simplify=True, form=None):
if is_literal(self):
return self
expr = self.args[0]
func, args = expr.func, expr.args
if func == And:
return Or._to_nnf(*[Not(arg) for arg in args], simplify=simplify, form=form)
if func == Or:
return And._to_nnf(*[Not(arg) for arg in args], simplify=simplify, form=form)
if func == Implies:
a, b = args
return And._to_nnf(a, Not(b), simplify=simplify, form=form)
if func == Equivalent:
return And._to_nnf(Or(*args), Or(*[Not(arg) for arg in args]),
simplify=simplify, form=form)
if func == Xor:
result = []
for i in range(1, len(args)+1, 2):
for neg in combinations(args, i):
clause = [Not(s) if s in neg else s for s in args]
result.append(Or(*clause))
return And._to_nnf(*result, simplify=simplify, form=form)
if func == ITE:
a, b, c = args
return And._to_nnf(Or(a, Not(c)), Or(Not(a), Not(b)), simplify=simplify, form=form)
raise ValueError("Illegal operator %s in expression" % func)
def to_anf(self, deep=True):
return Xor._to_anf(true, self.args[0], deep=deep)
| Not |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 53248,
"end": 64462
} | class ____(DabDetrPreTrainedModel):
def __init__(self, config: DabDetrConfig):
super().__init__(config)
self.auxiliary_loss = config.auxiliary_loss
# Create backbone + positional encoding
self.backbone = DabDetrConvEncoder(config)
object_queries = DabDetrSinePositionEmbedding(config)
self.query_refpoint_embeddings = nn.Embedding(config.num_queries, config.query_dim)
self.random_refpoints_xy = config.random_refpoints_xy
if self.random_refpoints_xy:
self.query_refpoint_embeddings.weight.data[:, :2].uniform_(0, 1)
self.query_refpoint_embeddings.weight.data[:, :2] = inverse_sigmoid(
self.query_refpoint_embeddings.weight.data[:, :2]
)
self.query_refpoint_embeddings.weight.data[:, :2].requires_grad = False
# Create projection layer
self.input_projection = nn.Conv2d(
self.backbone.intermediate_channel_sizes[-1], config.hidden_size, kernel_size=1
)
self.backbone = DabDetrConvModel(self.backbone, object_queries)
self.encoder = DabDetrEncoder(config)
self.decoder = DabDetrDecoder(config)
# decoder related variables
self.hidden_size = config.hidden_size
self.num_queries = config.num_queries
self.num_patterns = config.num_patterns
if not isinstance(self.num_patterns, int):
logger.warning(f"num_patterns should be int but {type(self.num_patterns)}")
self.num_patterns = 0
if self.num_patterns > 0:
self.patterns = nn.Embedding(self.num_patterns, self.hidden_size)
self.aux_loss = config.auxiliary_loss
# Initialize weights and apply final processing
self.post_init()
def freeze_backbone(self):
for name, param in self.backbone.conv_encoder.model.named_parameters():
param.requires_grad_(False)
def unfreeze_backbone(self):
for name, param in self.backbone.conv_encoder.model.named_parameters():
param.requires_grad_(True)
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
pixel_mask: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.LongTensor] = None,
encoder_outputs: Optional[torch.FloatTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple[torch.FloatTensor], DabDetrModelOutput]:
r"""
decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
Not used by default. Can be used to mask object queries.
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
can choose to directly pass a flattened representation of an image.
decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
embedded representation.
Examples:
```python
>>> from transformers import AutoImageProcessor, AutoModel
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image_processor = AutoImageProcessor.from_pretrained("IDEA-Research/dab_detr-base")
>>> model = AutoModel.from_pretrained("IDEA-Research/dab_detr-base")
>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")
>>> # forward pass
>>> outputs = model(**inputs)
>>> # the last hidden states are the final query embeddings of the Transformer decoder
>>> # these are of shape (batch_size, num_queries, hidden_size)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]
```"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
batch_size, _, height, width = pixel_values.shape
device = pixel_values.device
if pixel_mask is None:
pixel_mask = torch.ones(((batch_size, height, width)), device=device)
# First, sent pixel_values + pixel_mask through Backbone to obtain the features
# pixel_values should be of shape (batch_size, num_channels, height, width)
# pixel_mask should be of shape (batch_size, height, width)
features, object_queries_list = self.backbone(pixel_values, pixel_mask)
# get final feature map and downsampled mask
feature_map, mask = features[-1]
if mask is None:
raise ValueError("Backbone does not return downsampled pixel mask")
flattened_mask = mask.flatten(1)
# Second, apply 1x1 convolution to reduce the channel dimension to hidden_size (256 by default)
projected_feature_map = self.input_projection(feature_map)
# Third, flatten the feature map + object_queries of shape NxCxHxW to HWxNxC, and permute it to NxHWxC
# In other words, turn their shape into ( sequence_length, batch_size, hidden_size)
flattened_features = projected_feature_map.flatten(2).permute(0, 2, 1)
object_queries = object_queries_list[-1].flatten(2).permute(0, 2, 1)
reference_position_embeddings = self.query_refpoint_embeddings.weight.unsqueeze(0).repeat(batch_size, 1, 1)
# Fourth, sent flattened_features + flattened_mask + object_queries through encoder
# flattened_features is a Tensor of shape (height*width, batch_size, hidden_size)
# flattened_mask is a Tensor of shape (batch_size, height*width)
if encoder_outputs is None:
encoder_outputs = self.encoder(
inputs_embeds=flattened_features,
attention_mask=flattened_mask,
object_queries=object_queries,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
encoder_outputs = BaseModelOutput(
last_hidden_state=encoder_outputs[0],
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
)
# Fifth, sent query embeddings + object_queries through the decoder (which is conditioned on the encoder output)
num_queries = reference_position_embeddings.shape[1]
if self.num_patterns == 0:
queries = torch.zeros(batch_size, num_queries, self.hidden_size, device=device)
else:
queries = (
self.patterns.weight[:, None, None, :]
.repeat(1, self.num_queries, batch_size, 1)
.flatten(0, 1)
.permute(1, 0, 2)
) # bs, n_q*n_pat, hidden_size
reference_position_embeddings = reference_position_embeddings.repeat(
1, self.num_patterns, 1
) # bs, n_q*n_pat, hidden_size
# decoder outputs consists of (dec_features, dec_hidden, dec_attn)
decoder_outputs = self.decoder(
inputs_embeds=queries,
query_position_embeddings=reference_position_embeddings,
object_queries=object_queries,
encoder_hidden_states=encoder_outputs[0],
memory_key_padding_mask=flattened_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if not return_dict:
# last_hidden_state
output = (decoder_outputs[0],)
reference_points = decoder_outputs[-1]
intermediate_hidden_states = decoder_outputs[-2]
# it has to follow the order of DABDETRModelOutput that is based on ModelOutput
# If we only use one of the variables then the indexing will change.
# E.g: if we return everything then 'decoder_attentions' is decoder_outputs[2], if we only use output_attentions then its decoder_outputs[1]
if output_hidden_states and output_attentions:
output += (
decoder_outputs[1],
decoder_outputs[2],
decoder_outputs[3],
encoder_outputs[0],
encoder_outputs[1],
encoder_outputs[2],
)
elif output_hidden_states:
# decoder_hidden_states, encoder_last_hidden_state, encoder_hidden_states
output += (
decoder_outputs[1],
encoder_outputs[0],
encoder_outputs[1],
)
elif output_attentions:
# decoder_self_attention, decoder_cross_attention, encoder_attentions
output += (
decoder_outputs[1],
decoder_outputs[2],
encoder_outputs[1],
)
output += (intermediate_hidden_states, reference_points)
return output
reference_points = decoder_outputs.reference_points
intermediate_hidden_states = decoder_outputs.intermediate_hidden_states
return DabDetrModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
decoder_hidden_states=decoder_outputs.hidden_states if output_hidden_states else None,
decoder_attentions=decoder_outputs.attentions if output_attentions else None,
cross_attentions=decoder_outputs.cross_attentions if output_attentions else None,
encoder_last_hidden_state=encoder_outputs.last_hidden_state if output_hidden_states else None,
encoder_hidden_states=encoder_outputs.hidden_states if output_hidden_states else None,
encoder_attentions=encoder_outputs.attentions if output_attentions else None,
intermediate_hidden_states=intermediate_hidden_states,
reference_points=reference_points,
)
# Copied from transformers.models.detr.modeling_detr.DetrMHAttentionMap with Detr->DabDetr
| DabDetrModel |
python | walkccc__LeetCode | solutions/1220. Count Vowels Permutation/1220.py | {
"start": 0,
"end": 415
} | class ____:
def countVowelPermutation(self, n: int) -> int:
MOD = 1_000_000_007
dp = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1}
for _ in range(n - 1):
newDp = {'a': dp['e'] + dp['i'] + dp['u'],
'e': dp['a'] + dp['i'],
'i': dp['e'] + dp['o'],
'o': dp['i'],
'u': dp['i'] + dp['o']}
dp = newDp
return sum(dp.values()) % MOD
| Solution |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py | {
"start": 8838,
"end": 10059
} | class ____(unittest.TestCase):
def setUp(self):
self.mock_index = MagicMock()
self.mock_index.dimension = 2
self.mock_index.query.return_value = [
{
"id": "1",
"similarity": 0.9,
"meta": {"text": "mock text"},
"vector": [0.1, 0.2],
}
]
self.store = VectorXVectorStore(
vectorx_index=self.mock_index, dimension=2, index_name="mock_index"
)
def test_add_and_query_mock(self):
query = VectorStoreQuery(query_embedding=[0.1, 0.2], similarity_top_k=1)
result = self.store.query(query)
self.assertEqual(result.similarities[0], 0.9)
self.assertEqual(len(result.nodes), 1)
def test_delete_non_existent_node(self):
self.store.delete("nonexistent")
def test_query_with_empty_filters(self):
query = VectorStoreQuery(
query_embedding=[0.1, 0.2],
similarity_top_k=1,
filters=MetadataFilters(filters=[]),
)
result = self.store.query(query)
self.assertEqual(len(result.nodes), 1)
# ------------------ Advanced Tests with Mocking ------------------
| TestVectorXMock |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 77135,
"end": 90959
} | class ____(
roles.DDLConstraintColumnRole,
roles.DDLExpressionRole,
roles.StatementOptionRole,
roles.WhereHavingRole,
roles.OrderByRole,
roles.FromClauseRole,
roles.SelectStatementRole,
roles.InElementRole,
Generative,
ExecutableStatement,
DQLDMLClauseElement,
roles.BinaryElementRole[Any],
inspection.Inspectable["TextClause"],
):
"""Represent a literal SQL text fragment.
E.g.::
from sqlalchemy import text
t = text("SELECT * FROM users")
result = connection.execute(t)
The :class:`_expression.TextClause` construct is produced using the
:func:`_expression.text`
function; see that function for full documentation.
.. seealso::
:func:`_expression.text`
"""
__visit_name__ = "textclause"
_traverse_internals: _TraverseInternalsType = [
("_bindparams", InternalTraversal.dp_string_clauseelement_dict),
("text", InternalTraversal.dp_string),
] + ExecutableStatement._executable_traverse_internals
_is_text_clause = True
_is_textual = True
_bind_params_regex = re.compile(r"(?<![:\w\x5c]):(\w+)(?!:)", re.UNICODE)
_is_implicitly_boolean = False
_render_label_in_columns_clause = False
_omit_from_statements = False
_is_collection_aggregate = False
@property
def _hide_froms(self) -> Iterable[FromClause]:
return ()
def __and__(self, other):
# support use in select.where(), query.filter()
return and_(self, other)
@property
def _select_iterable(self) -> _SelectIterable:
return (self,)
# help in those cases where text() is
# interpreted in a column expression situation
key: Optional[str] = None
_label: Optional[str] = None
_allow_label_resolve = False
@property
def _is_star(self): # type: ignore[override]
return self.text == "*"
def __init__(self, text: str):
self._bindparams: Dict[str, BindParameter[Any]] = {}
def repl(m):
self._bindparams[m.group(1)] = BindParameter(m.group(1))
return ":%s" % m.group(1)
# scan the string and search for bind parameter names, add them
# to the list of bindparams
self.text = self._bind_params_regex.sub(repl, text)
@_generative
def bindparams(
self,
*binds: BindParameter[Any],
**names_to_values: Any,
) -> Self:
"""Establish the values and/or types of bound parameters within
this :class:`_expression.TextClause` construct.
Given a text construct such as::
from sqlalchemy import text
stmt = text(
"SELECT id, name FROM user WHERE name=:name AND timestamp=:timestamp"
)
the :meth:`_expression.TextClause.bindparams`
method can be used to establish
the initial value of ``:name`` and ``:timestamp``,
using simple keyword arguments::
stmt = stmt.bindparams(
name="jack", timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)
Where above, new :class:`.BindParameter` objects
will be generated with the names ``name`` and ``timestamp``, and
values of ``jack`` and ``datetime.datetime(2012, 10, 8, 15, 12, 5)``,
respectively. The types will be
inferred from the values given, in this case :class:`.String` and
:class:`.DateTime`.
When specific typing behavior is needed, the positional ``*binds``
argument can be used in which to specify :func:`.bindparam` constructs
directly. These constructs must include at least the ``key``
argument, then an optional value and type::
from sqlalchemy import bindparam
stmt = stmt.bindparams(
bindparam("name", value="jack", type_=String),
bindparam("timestamp", type_=DateTime),
)
Above, we specified the type of :class:`.DateTime` for the
``timestamp`` bind, and the type of :class:`.String` for the ``name``
bind. In the case of ``name`` we also set the default value of
``"jack"``.
Additional bound parameters can be supplied at statement execution
time, e.g.::
result = connection.execute(
stmt, timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)
The :meth:`_expression.TextClause.bindparams`
method can be called repeatedly,
where it will re-use existing :class:`.BindParameter` objects to add
new information. For example, we can call
:meth:`_expression.TextClause.bindparams`
first with typing information, and a
second time with value information, and it will be combined::
stmt = text(
"SELECT id, name FROM user WHERE name=:name "
"AND timestamp=:timestamp"
)
stmt = stmt.bindparams(
bindparam("name", type_=String), bindparam("timestamp", type_=DateTime)
)
stmt = stmt.bindparams(
name="jack", timestamp=datetime.datetime(2012, 10, 8, 15, 12, 5)
)
The :meth:`_expression.TextClause.bindparams`
method also supports the concept of
**unique** bound parameters. These are parameters that are
"uniquified" on name at statement compilation time, so that multiple
:func:`_expression.text`
constructs may be combined together without the names
conflicting. To use this feature, specify the
:paramref:`.BindParameter.unique` flag on each :func:`.bindparam`
object::
stmt1 = text("select id from table where name=:name").bindparams(
bindparam("name", value="name1", unique=True)
)
stmt2 = text("select id from table where name=:name").bindparams(
bindparam("name", value="name2", unique=True)
)
union = union_all(stmt1.columns(column("id")), stmt2.columns(column("id")))
The above statement will render as:
.. sourcecode:: sql
select id from table where name=:name_1
UNION ALL select id from table where name=:name_2
""" # noqa: E501
self._bindparams = new_params = self._bindparams.copy()
for bind in binds:
try:
# the regex used for text() currently will not match
# a unique/anonymous key in any case, so use the _orig_key
# so that a text() construct can support unique parameters
existing = new_params[bind._orig_key]
except KeyError as err:
raise exc.ArgumentError(
"This text() construct doesn't define a "
"bound parameter named %r" % bind._orig_key
) from err
else:
new_params[existing._orig_key] = bind
for key, value in names_to_values.items():
try:
existing = new_params[key]
except KeyError as err:
raise exc.ArgumentError(
"This text() construct doesn't define a "
"bound parameter named %r" % key
) from err
else:
new_params[key] = existing._with_value(value, required=False)
return self
@util.preload_module("sqlalchemy.sql.selectable")
def columns(
self,
*cols: _ColumnExpressionArgument[Any],
**types: _TypeEngineArgument[Any],
) -> TextualSelect:
r"""Turn this :class:`_expression.TextClause` object into a
:class:`_expression.TextualSelect`
object that serves the same role as a SELECT
statement.
The :class:`_expression.TextualSelect` is part of the
:class:`_expression.SelectBase`
hierarchy and can be embedded into another statement by using the
:meth:`_expression.TextualSelect.subquery` method to produce a
:class:`.Subquery`
object, which can then be SELECTed from.
This function essentially bridges the gap between an entirely
textual SELECT statement and the SQL expression language concept
of a "selectable"::
from sqlalchemy.sql import column, text
stmt = text("SELECT id, name FROM some_table")
stmt = stmt.columns(column("id"), column("name")).subquery("st")
stmt = (
select(mytable)
.select_from(mytable.join(stmt, mytable.c.name == stmt.c.name))
.where(stmt.c.id > 5)
)
Above, we pass a series of :func:`_expression.column` elements to the
:meth:`_expression.TextClause.columns` method positionally. These
:func:`_expression.column`
elements now become first class elements upon the
:attr:`_expression.TextualSelect.selected_columns` column collection,
which then
become part of the :attr:`.Subquery.c` collection after
:meth:`_expression.TextualSelect.subquery` is invoked.
The column expressions we pass to
:meth:`_expression.TextClause.columns` may
also be typed; when we do so, these :class:`.TypeEngine` objects become
the effective return type of the column, so that SQLAlchemy's
result-set-processing systems may be used on the return values.
This is often needed for types such as date or boolean types, as well
as for unicode processing on some dialect configurations::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(
column("id", Integer),
column("name", Unicode),
column("timestamp", DateTime),
)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
As a shortcut to the above syntax, keyword arguments referring to
types alone may be used, if only type conversion is needed::
stmt = text("SELECT id, name, timestamp FROM some_table")
stmt = stmt.columns(id=Integer, name=Unicode, timestamp=DateTime)
for id, name, timestamp in connection.execute(stmt):
print(id, name, timestamp)
The positional form of :meth:`_expression.TextClause.columns`
also provides the
unique feature of **positional column targeting**, which is
particularly useful when using the ORM with complex textual queries. If
we specify the columns from our model to
:meth:`_expression.TextClause.columns`,
the result set will match to those columns positionally, meaning the
name or origin of the column in the textual SQL doesn't matter::
stmt = text(
"SELECT users.id, addresses.id, users.id, "
"users.name, addresses.email_address AS email "
"FROM users JOIN addresses ON users.id=addresses.user_id "
"WHERE users.id = 1"
).columns(
User.id,
Address.id,
Address.user_id,
User.name,
Address.email_address,
)
query = (
session.query(User)
.from_statement(stmt)
.options(contains_eager(User.addresses))
)
The :meth:`_expression.TextClause.columns` method provides a direct
route to calling :meth:`_expression.FromClause.subquery` as well as
:meth:`_expression.SelectBase.cte`
against a textual SELECT statement::
stmt = stmt.columns(id=Integer, name=String).cte("st")
stmt = select(sometable).where(sometable.c.id == stmt.c.id)
:param \*cols: A series of :class:`_expression.ColumnElement` objects,
typically
:class:`_schema.Column` objects from a :class:`_schema.Table`
or ORM level
column-mapped attributes, representing a set of columns that this
textual string will SELECT from.
:param \**types: A mapping of string names to :class:`.TypeEngine`
type objects indicating the datatypes to use for names that are
SELECTed from the textual string. Prefer to use the ``*cols``
argument as it also indicates positional ordering.
"""
selectable = util.preloaded.sql_selectable
input_cols: List[NamedColumn[Any]] = [
coercions.expect(roles.LabeledColumnExprRole, col) for col in cols
]
positional_input_cols = [
(
ColumnClause(col.key, types.pop(col.key))
if col.key in types
else col
)
for col in input_cols
]
keyed_input_cols: List[NamedColumn[Any]] = [
ColumnClause(key, type_) for key, type_ in types.items()
]
elem = selectable.TextualSelect.__new__(selectable.TextualSelect)
elem._init(
self,
positional_input_cols + keyed_input_cols,
positional=bool(positional_input_cols) and not keyed_input_cols,
)
return elem
@property
def type(self) -> TypeEngine[Any]:
return type_api.NULLTYPE
@property
def comparator(self):
# TODO: this seems wrong, it seems like we might not
# be using this method.
return self.type.comparator_factory(self) # type: ignore
def self_group(
self, against: Optional[OperatorType] = None
) -> Union[Self, Grouping[Any]]:
if against is operators.in_op:
return Grouping(self)
else:
return self
| TextClause |
python | coleifer__peewee | tests/psycopg3_ext.py | {
"start": 17704,
"end": 19683
} | class ____(ModelTestCase):
database = db
requires = [KX]
def setUp(self):
super(TestPsycopg3AutocommitIntegration, self).setUp()
with self.database.atomic():
kx1 = KX.create(key='k1', value=1)
def force_integrity_error(self):
# Force an integrity error, then verify that the current
# transaction has been aborted.
self.assertRaises(IntegrityError, KX.create, key='k1', value=10)
def test_autocommit_default(self):
kx2 = KX.create(key='k2', value=2) # Will be committed.
self.assertTrue(kx2.id > 0)
self.force_integrity_error()
self.assertEqual(KX.select().count(), 2)
self.assertEqual([(kx.key, kx.value)
for kx in KX.select().order_by(KX.key)],
[('k1', 1), ('k2', 2)])
def test_autocommit_disabled(self):
with self.database.manual_commit():
self.database.begin()
kx2 = KX.create(key='k2', value=2) # Not committed.
self.assertTrue(kx2.id > 0) # Yes, we have a primary key.
self.force_integrity_error()
self.database.rollback()
self.assertEqual(KX.select().count(), 1)
kx1_db = KX.get(KX.key == 'k1')
self.assertEqual(kx1_db.value, 1)
def test_atomic_block(self):
with self.database.atomic() as txn:
kx2 = KX.create(key='k2', value=2)
self.assertTrue(kx2.id > 0)
self.force_integrity_error()
txn.rollback(False)
self.assertEqual(KX.select().count(), 1)
kx1_db = KX.get(KX.key == 'k1')
self.assertEqual(kx1_db.value, 1)
def test_atomic_block_exception(self):
with self.assertRaises(IntegrityError):
with self.database.atomic():
KX.create(key='k2', value=2)
KX.create(key='k1', value=10)
self.assertEqual(KX.select().count(), 1)
| TestPsycopg3AutocommitIntegration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/config_migrations.py | {
"start": 3742,
"end": 4331
} | class ____(MigrateConfig):
"""
This class stands for migrating the config azure_blob_storage_account_key inside object `credentials`
"""
@classmethod
def should_migrate(cls, config: Mapping[str, Any]) -> bool:
return "credentials" not in config
@classmethod
def migrate_config(cls, config: Mapping[str, Any]) -> Mapping[str, Any]:
config["credentials"] = {
"auth_type": "storage_account_key",
"azure_blob_storage_account_key": config.pop("azure_blob_storage_account_key"),
}
return config
| MigrateCredentials |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 2366,
"end": 2573
} | class ____(Generic[P, R, M]):
uuid: uuid_package.UUID
metadata: M
properties: P
references: R
vector: Dict[str, Union[List[float], List[List[float]]]]
collection: str
@dataclass
| _Object |
python | keras-team__keras | keras/src/layers/convolutional/base_conv_transpose.py | {
"start": 599,
"end": 10719
} | class ____(Layer):
"""Abstract N-D transposed convolution layer.
The need for transposed convolutions generally arises from the desire to use
a transformation going in the opposite direction of a normal convolution,
i.e., from something that has the shape of the output of some convolution to
something that has the shape of its input while maintaining a connectivity
pattern that is compatible with said convolution.
Args:
rank: int, the rank of the transposed convolution, e.g. 2 for 2D
transposed convolution.
filters: int, the dimension of the output space (the number of filters
in the transposed convolution).
kernel_size: int or tuple/list of `rank` integers, specifying the size
of the transposed convolution window.
strides: int or tuple/list of `rank` integers, specifying the stride
length of the transposed convolution. If only one int is specified,
the same stride size will be used for all dimensions.
`strides > 1` is incompatible with `dilation_rate > 1`.
padding: string, either `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input such that output has the same
height/width dimension as the input.
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, steps, features)`
while `"channels_first"` corresponds to inputs with shape
`(batch, features, steps)`. It defaults to the `image_data_format`
value found in your Keras config file at `~/.keras/keras.json`.
If you never set it, then it will be `"channels_last"`.
dilation_rate: int or tuple/list of `rank` integers, specifying the
dilation rate to use for dilated convolution. If only one int is
specified, the same dilation rate will be used for all dimensions.
activation: Activation function. If `None`, no activation is applied.
use_bias: bool, if `True`, bias will be added to the output.
kernel_initializer: Initializer for the convolution kernel. If `None`,
the default initializer (`"glorot_uniform"`) will be used.
bias_initializer: Initializer for the bias vector. If `None`, the
default initializer (`"zeros"`) will be used.
kernel_regularizer: Optional regularizer for the convolution kernel.
bias_regularizer: Optional regularizer for the bias vector.
activity_regularizer: Optional regularizer function for the output.
kernel_constraint: Optional projection function to be applied to the
kernel after being updated by an `Optimizer` (e.g. used to implement
norm constraints or value constraints for layer weights). The
function must take as input the unprojected variable and must return
the projected variable (which must have the same shape). Constraints
are not safe to use when doing asynchronous distributed training.
bias_constraint: Optional projection function to be applied to the
bias after being updated by an `Optimizer`.
"""
def __init__(
self,
rank,
filters,
kernel_size,
strides=1,
padding="valid",
output_padding=None,
data_format=None,
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer="glorot_uniform",
bias_initializer="zeros",
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
trainable=True,
name=None,
**kwargs,
):
super().__init__(
trainable=trainable,
name=name,
activity_regularizer=activity_regularizer,
**kwargs,
)
self.rank = rank
self.filters = filters
self.kernel_size = standardize_tuple(kernel_size, rank, "kernel_size")
self.strides = standardize_tuple(strides, rank, "strides")
self.dilation_rate = standardize_tuple(
dilation_rate, rank, "dilation_rate"
)
self.padding = standardize_padding(padding)
if output_padding is None:
self.output_padding = None
else:
self.output_padding = standardize_tuple(
output_padding,
rank,
"output_padding",
allow_zero=True,
)
self.data_format = standardize_data_format(data_format)
self.activation = activations.get(activation)
self.use_bias = use_bias
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.input_spec = InputSpec(min_ndim=self.rank + 2)
self.data_format = self.data_format
if self.filters is not None and self.filters <= 0:
raise ValueError(
"Invalid value for argument `filters`. Expected a strictly "
f"positive value. Received filters={self.filters}."
)
if not all(self.kernel_size):
raise ValueError(
"The argument `kernel_size` cannot contain 0. Received "
f"kernel_size={self.kernel_size}."
)
if not all(self.strides):
raise ValueError(
"The argument `strides` cannot contains 0. Received "
f"strides={self.strides}."
)
if max(self.strides) > 1 and max(self.dilation_rate) > 1:
raise ValueError(
"`strides > 1` not supported in conjunction with "
f"`dilation_rate > 1`. Received: strides={self.strides} and "
f"dilation_rate={self.dilation_rate}"
)
def build(self, input_shape):
if self.data_format == "channels_last":
channel_axis = -1
input_channel = input_shape[-1]
else:
channel_axis = 1
input_channel = input_shape[1]
self.input_spec = InputSpec(
min_ndim=self.rank + 2, axes={channel_axis: input_channel}
)
kernel_shape = self.kernel_size + (
self.filters,
input_channel,
)
self.kernel = self.add_weight(
name="kernel",
shape=kernel_shape,
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
trainable=True,
dtype=self.dtype,
)
if self.use_bias:
self.bias = self.add_weight(
name="bias",
shape=(self.filters,),
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint,
trainable=True,
dtype=self.dtype,
)
else:
self.bias = None
def call(self, inputs):
outputs = ops.conv_transpose(
inputs,
self.kernel,
strides=list(self.strides),
padding=self.padding,
output_padding=self.output_padding,
dilation_rate=self.dilation_rate,
data_format=self.data_format,
)
if self.use_bias:
if self.data_format == "channels_last":
bias_shape = (1,) * (self.rank + 1) + (self.filters,)
else:
bias_shape = (1, self.filters) + (1,) * self.rank
bias = ops.reshape(self.bias, bias_shape)
outputs = ops.add(outputs, bias)
if self.activation is not None:
return self.activation(outputs)
return outputs
def compute_output_shape(self, input_shape):
return compute_conv_transpose_output_shape(
input_shape,
self.kernel_size,
self.filters,
strides=self.strides,
padding=self.padding,
output_padding=self.output_padding,
data_format=self.data_format,
dilation_rate=self.dilation_rate,
)
def get_config(self):
config = super().get_config()
config.update(
{
"filters": self.filters,
"kernel_size": self.kernel_size,
"strides": self.strides,
"padding": self.padding,
"data_format": self.data_format,
"dilation_rate": self.dilation_rate,
"activation": activations.serialize(self.activation),
"use_bias": self.use_bias,
"kernel_initializer": initializers.serialize(
self.kernel_initializer
),
"bias_initializer": initializers.serialize(
self.bias_initializer
),
"kernel_regularizer": regularizers.serialize(
self.kernel_regularizer
),
"bias_regularizer": regularizers.serialize(
self.bias_regularizer
),
"activity_regularizer": regularizers.serialize(
self.activity_regularizer
),
"kernel_constraint": constraints.serialize(
self.kernel_constraint
),
"bias_constraint": constraints.serialize(self.bias_constraint),
}
)
return config
| BaseConvTranspose |
python | falconry__falcon | falcon/testing/srmock.py | {
"start": 919,
"end": 2264
} | class ____:
"""Mock object representing a WSGI `start_response` callable."""
status: str | None
"""HTTP status line, e.g. '785 TPS Cover Sheet not attached'."""
headers: HeaderIter | None
"""Raw headers list passed to `start_response`, per PEP-3333."""
headers_dict: Headers
"""Headers as a case-insensitive ``dict``-like object, instead of a ``list``."""
def __init__(self) -> None:
self._called = 0
self.status = None
self.headers = None
self.exc_info: Any | None = None
def __call__(
self,
status: str,
headers: HeaderIter,
exc_info: Any | None = None,
) -> Any:
"""Implement the PEP-3333 `start_response` protocol."""
self._called += 1
self.status = status
# NOTE(kgriffs): Normalize headers to be lowercase regardless
# of what Falcon returns, so asserts in tests don't have to
# worry about the case-insensitive nature of header names.
self.headers = [(name.lower(), value) for name, value in headers]
self.headers_dict = util.CaseInsensitiveDict(headers) # type: ignore[assignment]
self.exc_info = exc_info
@property
def call_count(self) -> int:
"""Number of times `start_response` was called."""
return self._called
| StartResponseMock |
python | vyperlang__vyper | vyper/ast/pre_parser.py | {
"start": 4619,
"end": 6389
} | class ____:
def __init__(self, code):
self._code = code
self.annotations = {}
self._current_annotation = None
self._state = ParserState.NOT_RUNNING
self._current_for_loop = None
def consume(self, token):
# state machine: we can start slurping tokens soon
if token.type == NAME and token.string == "for":
# note: self._state should be NOT_RUNNING here, but we don't sanity
# check here as that should be an error the parser will handle.
self._state = ParserState.START_SOON
self._current_for_loop = token.start
if self._state == ParserState.NOT_RUNNING:
return False
# state machine: start slurping tokens
if token.type == OP and token.string == ":":
self._state = ParserState.RUNNING
# sanity check -- this should never really happen, but if it does,
# try to raise an exception which pinpoints the source.
if self._current_annotation is not None:
raise SyntaxException(
"for loop parse error", self._code, token.start[0], token.start[1]
)
self._current_annotation = []
return True # do not add ":" to tokens.
# state machine: end slurping tokens
if token.type == NAME and token.string == "in":
self._state = ParserState.NOT_RUNNING
self.annotations[self._current_for_loop] = self._current_annotation or []
self._current_annotation = None
return False
if self._state != ParserState.RUNNING:
return False
# slurp the token
self._current_annotation.append(token)
return True
| ForParser |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 31758,
"end": 38337
} | class ____(BlipPreTrainedModel, GenerationMixin):
config: BlipConfig
main_input_name = "pixel_values"
_tied_weights_keys = {
"text_decoder.cls.predictions.decoder.bias": "text_decoder.cls.predictions.bias",
"text_decoder.cls.predictions.decoder.weight": "text_decoder.bert.embeddings.word_embeddings.weight",
} # TODO @arthurzucker check why we need this when for other models, their subPreTrainedModel handle it themselves.
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_decoder = BlipTextLMHeadModel(config.text_config)
self.decoder_input_ids = config.text_config.bos_token_id
self.decoder_pad_token_id = config.text_config.pad_token_id
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.text_decoder.get_input_embeddings()
def set_input_embeddings(self, value):
self.text_decoder.set_input_embeddings(value)
@can_return_tuple
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
interpolate_pos_encoding: bool = False,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BlipForConditionalGenerationModelOutput]:
r"""
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = "A picture of"
>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model(**inputs)
```"""
vision_outputs = self.vision_model(
pixel_values=pixel_values,
interpolate_pos_encoding=interpolate_pos_encoding,
**kwargs,
)
image_embeds = vision_outputs.last_hidden_state
outputs = self.text_decoder(
input_ids=input_ids,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
labels=labels,
reduction="mean",
logits_to_keep=logits_to_keep,
**kwargs,
)
return BlipForConditionalGenerationModelOutput(
loss=outputs.loss,
logits=outputs.logits,
image_embeds=image_embeds,
last_hidden_state=vision_outputs.last_hidden_state,
hidden_states=vision_outputs.hidden_states,
attentions=vision_outputs.attentions,
)
@torch.no_grad()
def generate(
self,
pixel_values: torch.FloatTensor,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
interpolate_pos_encoding: bool = False,
**generate_kwargs,
) -> torch.LongTensor:
r"""
Overrides *generate* function to be able to use the model as a conditional generator
Parameters:
pixel_values (*torch.FloatTensor* of shape *(batch_size, num_channels, image_height, image_width)*:
Input image to be processed
input_ids (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
The sequence used as a prompt for the generation.
attention_mask (*torch.LongTensor* of shape *(batch_size, sequence_length)*, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
Examples:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, BlipForConditionalGeneration
>>> model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
>>> processor = AutoProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> outputs = model.generate(**inputs)
>>> print(processor.decode(outputs[0], skip_special_tokens=True))
two cats sleeping on a couch
```
"""
batch_size = pixel_values.shape[0]
vision_outputs = self.vision_model(
pixel_values=pixel_values,
interpolate_pos_encoding=interpolate_pos_encoding,
)
image_embeds = vision_outputs[0]
image_attention_mask = torch.ones(image_embeds.size()[:-1], dtype=torch.long, device=image_embeds.device)
if isinstance(input_ids, list):
input_ids = torch.LongTensor(input_ids)
elif input_ids is None:
input_ids = (
torch.LongTensor([[self.decoder_input_ids, self.config.text_config.eos_token_id]])
.repeat(batch_size, 1)
.to(image_embeds.device)
)
input_ids[:, 0] = self.config.text_config.bos_token_id
attention_mask = attention_mask[:, :-1] if attention_mask is not None else None
outputs = self.text_decoder.generate(
input_ids=input_ids[:, :-1],
eos_token_id=self.config.text_config.sep_token_id,
pad_token_id=self.config.text_config.pad_token_id,
attention_mask=attention_mask,
encoder_hidden_states=image_embeds,
encoder_attention_mask=image_attention_mask,
**generate_kwargs,
)
return outputs
@auto_docstring(
custom_intro="""
BLIP Model for visual question answering. The model consists of a vision encoder, a text encoder as well as a text
decoder. The vision encoder will encode the input image, the text encoder will encode the input question together
with the encoding of the image, and the text decoder will output the answer to the question.
"""
)
| BlipForConditionalGeneration |
python | pennersr__django-allauth | allauth/account/internal/flows/email_verification_by_code.py | {
"start": 560,
"end": 5004
} | class ____(AbstractCodeVerificationProcess):
def __init__(self, request, state: dict, user=None) -> None:
self.request = request
super().__init__(
state=state,
user=user,
max_attempts=app_settings.EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS,
timeout=app_settings.EMAIL_VERIFICATION_BY_CODE_TIMEOUT,
)
@property
def email(self) -> str:
return self.state["email"]
def persist(self) -> None:
self.request.session[EMAIL_VERIFICATION_CODE_SESSION_KEY] = self.state
def abort(self) -> None:
self.request.session.pop(EMAIL_VERIFICATION_CODE_SESSION_KEY, None)
clear_login(self.request)
def send(self, skip_enumeration_mails: bool = False) -> None:
from allauth.account.internal.flows.email_verification import (
send_verification_email_to_address,
)
email_address = self.email_address
signup = (
(not did_user_login(email_address.user)) if email_address.user_id else True
)
self.did_send = send_verification_email_to_address(
self.request,
email_address,
signup=signup,
process=self,
skip_enumeration_mails=skip_enumeration_mails,
)
@cached_property
def email_address(self) -> EmailAddress:
email = self.state["email"]
if not self.user or self.state.get("account_already_exists"):
return EmailAddress(email=email)
try:
email_address = EmailAddress.objects.get_for_user(self.user, email)
except EmailAddress.DoesNotExist:
email_address = EmailAddress(user=self.user, email=email)
return email_address
def finish(self) -> Optional[EmailAddress]:
from allauth.account.internal.flows.email_verification import (
mark_email_address_as_verified,
)
if not self.user or self.state.get("account_already_exists"):
raise ValueError
self.request.session.pop(EMAIL_VERIFICATION_CODE_SESSION_KEY, None)
return mark_email_address_as_verified(self.request, self.email_address)
def generate_code(self) -> None:
self.state["code"] = get_adapter().generate_email_verification_code()
@classmethod
def initiate(cls, *, request, user, email: str) -> "EmailVerificationProcess":
state = cls.initial_state(user, email)
process = EmailVerificationProcess(request=request, user=user, state=state)
process.generate_code()
process.send()
process.persist()
return process
@classmethod
def resume(cls, request) -> Optional["EmailVerificationProcess"]:
if not app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED:
return None
state = request.session.get(EMAIL_VERIFICATION_CODE_SESSION_KEY)
if not state:
return None
process = EmailVerificationProcess(request=request, state=state)
return process.abort_if_invalid()
@property
def can_change(self) -> bool:
# TODO: Prevent enumeration flaw: if we don't have a user, we cannot
# change the email. To fix this, we would need to serialize
# the user and perform an on-the-fly signup here.
return (
not self.is_change_quota_reached(
app_settings.EMAIL_VERIFICATION_MAX_CHANGE_COUNT
)
and bool(self.user)
and not did_user_login(self.user)
)
def change_to(self, email: str, account_already_exists: bool) -> None:
self.state["account_already_exists"] = account_already_exists
self.generate_code()
if account_already_exists:
pass
else:
EmailAddress.objects.add_new_email(
context.request, self.user, email, send_verification=False
)
user_email(self.user, email, commit=True)
self.record_change(email=email)
self.send()
self.persist()
@property
def can_resend(self) -> bool:
return not self.is_resend_quota_reached(
app_settings.EMAIL_VERIFICATION_MAX_RESEND_COUNT
)
def resend(self) -> None:
self.generate_code()
self.send(skip_enumeration_mails=True)
self.record_resend()
self.persist()
@property
def key(self):
return self.code
| EmailVerificationProcess |
python | faif__python-patterns | patterns/behavioral/command.py | {
"start": 1442,
"end": 1911
} | class ____:
"""
A command to delete a file given its name
"""
def __init__(self) -> None:
# an array of deleted files, to undo them as needed
self._deleted_files: List[str] = []
def execute(self, filename: str) -> None:
print(f"deleting {filename}")
self._deleted_files.append(filename)
def undo(self) -> None:
filename = self._deleted_files.pop()
print(f"restoring {filename}")
| DeleteFileCommand |
python | gevent__gevent | src/greentest/3.13/test_weakref.py | {
"start": 2142,
"end": 34197
} | class ____(TestBase):
def test_basic_ref(self):
self.check_basic_ref(C)
self.check_basic_ref(create_function)
self.check_basic_ref(create_bound_method)
# Just make sure the tp_repr handler doesn't raise an exception.
# Live reference:
o = C()
wr = weakref.ref(o)
repr(wr)
# Dead reference:
del o
repr(wr)
@support.cpython_only
def test_ref_repr(self):
obj = C()
ref = weakref.ref(obj)
regex = (
rf"<weakref at 0x[0-9a-fA-F]+; "
rf"to '{'' if __name__ == '__main__' else C.__module__ + '.'}{C.__qualname__}' "
rf"at 0x[0-9a-fA-F]+>"
)
self.assertRegex(repr(ref), regex)
obj = None
gc_collect()
self.assertRegex(repr(ref),
rf'<weakref at 0x[0-9a-fA-F]+; dead>')
# test type with __name__
class WithName:
@property
def __name__(self):
return "custom_name"
obj2 = WithName()
ref2 = weakref.ref(obj2)
regex = (
rf"<weakref at 0x[0-9a-fA-F]+; "
rf"to '{'' if __name__ == '__main__' else WithName.__module__ + '.'}"
rf"{WithName.__qualname__}' "
rf"at 0x[0-9a-fA-F]+ +\(custom_name\)>"
)
self.assertRegex(repr(ref2), regex)
def test_repr_failure_gh99184(self):
class MyConfig(dict):
def __getattr__(self, x):
return self[x]
obj = MyConfig(offset=5)
obj_weakref = weakref.ref(obj)
self.assertIn('MyConfig', repr(obj_weakref))
self.assertIn('MyConfig', str(obj_weakref))
def test_basic_callback(self):
self.check_basic_callback(C)
self.check_basic_callback(create_function)
self.check_basic_callback(create_bound_method)
@support.cpython_only
def test_cfunction(self):
_testcapi = import_helper.import_module("_testcapi")
create_cfunction = _testcapi.create_cfunction
f = create_cfunction()
wr = weakref.ref(f)
self.assertIs(wr(), f)
del f
self.assertIsNone(wr())
self.check_basic_ref(create_cfunction)
self.check_basic_callback(create_cfunction)
def test_multiple_callbacks(self):
o = C()
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del o
gc_collect() # For PyPy or other GCs.
self.assertIsNone(ref1(), "expected reference to be invalidated")
self.assertIsNone(ref2(), "expected reference to be invalidated")
self.assertEqual(self.cbcalled, 2,
"callback not called the right number of times")
def test_multiple_selfref_callbacks(self):
# Make sure all references are invalidated before callbacks are called
#
# What's important here is that we're using the first
# reference in the callback invoked on the second reference
# (the most recently created ref is cleaned up first). This
# tests that all references to the object are invalidated
# before any of the callbacks are invoked, so that we only
# have one invocation of _weakref.c:cleanup_helper() active
# for a particular object at a time.
#
def callback(object, self=self):
self.ref()
c = C()
self.ref = weakref.ref(c, callback)
ref1 = weakref.ref(c, callback)
del c
def test_constructor_kwargs(self):
c = C()
self.assertRaises(TypeError, weakref.ref, c, callback=None)
def test_proxy_ref(self):
o = C()
o.bar = 1
ref1 = weakref.proxy(o, self.callback)
ref2 = weakref.proxy(o, self.callback)
del o
gc_collect() # For PyPy or other GCs.
def check(proxy):
proxy.bar
self.assertRaises(ReferenceError, check, ref1)
self.assertRaises(ReferenceError, check, ref2)
ref3 = weakref.proxy(C())
gc_collect() # For PyPy or other GCs.
self.assertRaises(ReferenceError, bool, ref3)
self.assertEqual(self.cbcalled, 2)
@support.cpython_only
def test_proxy_repr(self):
obj = C()
ref = weakref.proxy(obj, self.callback)
regex = (
rf"<weakproxy at 0x[0-9a-fA-F]+; "
rf"to '{'' if __name__ == '__main__' else C.__module__ + '.'}{C.__qualname__}' "
rf"at 0x[0-9a-fA-F]+>"
)
self.assertRegex(repr(ref), regex)
obj = None
gc_collect()
self.assertRegex(repr(ref),
rf'<weakproxy at 0x[0-9a-fA-F]+; dead>')
def check_basic_ref(self, factory):
o = factory()
ref = weakref.ref(o)
self.assertIsNotNone(ref(),
"weak reference to live object should be live")
o2 = ref()
self.assertIs(o, o2,
"<ref>() should return original object if live")
def check_basic_callback(self, factory):
self.cbcalled = 0
o = factory()
ref = weakref.ref(o, self.callback)
del o
gc_collect() # For PyPy or other GCs.
self.assertEqual(self.cbcalled, 1,
"callback did not properly set 'cbcalled'")
self.assertIsNone(ref(),
"ref2 should be dead after deleting object reference")
def test_ref_reuse(self):
o = C()
ref1 = weakref.ref(o)
# create a proxy to make sure that there's an intervening creation
# between these two; it should make no difference
proxy = weakref.proxy(o)
ref2 = weakref.ref(o)
self.assertIs(ref1, ref2,
"reference object w/out callback should be re-used")
o = C()
proxy = weakref.proxy(o)
ref1 = weakref.ref(o)
ref2 = weakref.ref(o)
self.assertIs(ref1, ref2,
"reference object w/out callback should be re-used")
self.assertEqual(weakref.getweakrefcount(o), 2,
"wrong weak ref count for object")
del proxy
gc_collect() # For PyPy or other GCs.
self.assertEqual(weakref.getweakrefcount(o), 1,
"wrong weak ref count for object after deleting proxy")
def test_proxy_reuse(self):
o = C()
proxy1 = weakref.proxy(o)
ref = weakref.ref(o)
proxy2 = weakref.proxy(o)
self.assertIs(proxy1, proxy2,
"proxy object w/out callback should have been re-used")
def test_basic_proxy(self):
o = C()
self.check_proxy(o, weakref.proxy(o))
L = collections.UserList()
p = weakref.proxy(L)
self.assertFalse(p, "proxy for empty UserList should be false")
p.append(12)
self.assertEqual(len(L), 1)
self.assertTrue(p, "proxy for non-empty UserList should be true")
p[:] = [2, 3]
self.assertEqual(len(L), 2)
self.assertEqual(len(p), 2)
self.assertIn(3, p, "proxy didn't support __contains__() properly")
p[1] = 5
self.assertEqual(L[1], 5)
self.assertEqual(p[1], 5)
L2 = collections.UserList(L)
p2 = weakref.proxy(L2)
self.assertEqual(p, p2)
## self.assertEqual(repr(L2), repr(p2))
L3 = collections.UserList(range(10))
p3 = weakref.proxy(L3)
self.assertEqual(L3[:], p3[:])
self.assertEqual(L3[5:], p3[5:])
self.assertEqual(L3[:5], p3[:5])
self.assertEqual(L3[2:5], p3[2:5])
def test_proxy_unicode(self):
# See bug 5037
class C(object):
def __str__(self):
return "string"
def __bytes__(self):
return b"bytes"
instance = C()
self.assertIn("__bytes__", dir(weakref.proxy(instance)))
self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
def test_proxy_index(self):
class C:
def __index__(self):
return 10
o = C()
p = weakref.proxy(o)
self.assertEqual(operator.index(p), 10)
def test_proxy_div(self):
class C:
def __floordiv__(self, other):
return 42
def __ifloordiv__(self, other):
return 21
o = C()
p = weakref.proxy(o)
self.assertEqual(p // 5, 42)
p //= 5
self.assertEqual(p, 21)
def test_proxy_matmul(self):
class C:
def __matmul__(self, other):
return 1729
def __rmatmul__(self, other):
return -163
def __imatmul__(self, other):
return 561
o = C()
p = weakref.proxy(o)
self.assertEqual(p @ 5, 1729)
self.assertEqual(5 @ p, -163)
p @= 5
self.assertEqual(p, 561)
# The PyWeakref_* C API is documented as allowing either NULL or
# None as the value for the callback, where either means "no
# callback". The "no callback" ref and proxy objects are supposed
# to be shared so long as they exist by all callers so long as
# they are active. In Python 2.3.3 and earlier, this guarantee
# was not honored, and was broken in different ways for
# PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
def test_shared_ref_without_callback(self):
self.check_shared_without_callback(weakref.ref)
def test_shared_proxy_without_callback(self):
self.check_shared_without_callback(weakref.proxy)
def check_shared_without_callback(self, makeref):
o = Object(1)
p1 = makeref(o, None)
p2 = makeref(o, None)
self.assertIs(p1, p2, "both callbacks were None in the C API")
del p1, p2
p1 = makeref(o)
p2 = makeref(o, None)
self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
del p1, p2
p1 = makeref(o)
p2 = makeref(o)
self.assertIs(p1, p2, "both callbacks were NULL in the C API")
del p1, p2
p1 = makeref(o, None)
p2 = makeref(o)
self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
def test_callable_proxy(self):
o = Callable()
ref1 = weakref.proxy(o)
self.check_proxy(o, ref1)
self.assertIs(type(ref1), weakref.CallableProxyType,
"proxy is not of callable type")
ref1('twinkies!')
self.assertEqual(o.bar, 'twinkies!',
"call through proxy not passed through to original")
ref1(x='Splat.')
self.assertEqual(o.bar, 'Splat.',
"call through proxy not passed through to original")
# expect due to too few args
self.assertRaises(TypeError, ref1)
# expect due to too many args
self.assertRaises(TypeError, ref1, 1, 2, 3)
def check_proxy(self, o, proxy):
o.foo = 1
self.assertEqual(proxy.foo, 1,
"proxy does not reflect attribute addition")
o.foo = 2
self.assertEqual(proxy.foo, 2,
"proxy does not reflect attribute modification")
del o.foo
self.assertFalse(hasattr(proxy, 'foo'),
"proxy does not reflect attribute removal")
proxy.foo = 1
self.assertEqual(o.foo, 1,
"object does not reflect attribute addition via proxy")
proxy.foo = 2
self.assertEqual(o.foo, 2,
"object does not reflect attribute modification via proxy")
del proxy.foo
self.assertFalse(hasattr(o, 'foo'),
"object does not reflect attribute removal via proxy")
def test_proxy_deletion(self):
# Test clearing of SF bug #762891
class Foo:
result = None
def __delitem__(self, accessor):
self.result = accessor
g = Foo()
f = weakref.proxy(g)
del f[0]
self.assertEqual(f.result, 0)
def test_proxy_bool(self):
# Test clearing of SF bug #1170766
class List(list): pass
lyst = List()
self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
def test_proxy_iter(self):
# Test fails with a debug build of the interpreter
# (see bpo-38395).
obj = None
class MyObj:
def __iter__(self):
nonlocal obj
del obj
return NotImplemented
obj = MyObj()
p = weakref.proxy(obj)
with self.assertRaises(TypeError):
# "blech" in p calls MyObj.__iter__ through the proxy,
# without keeping a reference to the real object, so it
# can be killed in the middle of the call
"blech" in p
def test_proxy_next(self):
arr = [4, 5, 6]
def iterator_func():
yield from arr
it = iterator_func()
class IteratesWeakly:
def __iter__(self):
return weakref.proxy(it)
weak_it = IteratesWeakly()
# Calls proxy.__next__
self.assertEqual(list(weak_it), [4, 5, 6])
def test_proxy_bad_next(self):
# bpo-44720: PyIter_Next() shouldn't be called if the reference
# isn't an iterator.
not_an_iterator = lambda: 0
class A:
def __iter__(self):
return weakref.proxy(not_an_iterator)
a = A()
msg = "Weakref proxy referenced a non-iterator"
with self.assertRaisesRegex(TypeError, msg):
list(a)
def test_proxy_reversed(self):
class MyObj:
def __len__(self):
return 3
def __reversed__(self):
return iter('cba')
obj = MyObj()
self.assertEqual("".join(reversed(weakref.proxy(obj))), "cba")
def test_proxy_hash(self):
class MyObj:
def __hash__(self):
return 42
obj = MyObj()
with self.assertRaises(TypeError):
hash(weakref.proxy(obj))
class MyObj:
__hash__ = None
obj = MyObj()
with self.assertRaises(TypeError):
hash(weakref.proxy(obj))
def test_getweakrefcount(self):
o = C()
ref1 = weakref.ref(o)
ref2 = weakref.ref(o, self.callback)
self.assertEqual(weakref.getweakrefcount(o), 2,
"got wrong number of weak reference objects")
proxy1 = weakref.proxy(o)
proxy2 = weakref.proxy(o, self.callback)
self.assertEqual(weakref.getweakrefcount(o), 4,
"got wrong number of weak reference objects")
del ref1, ref2, proxy1, proxy2
gc_collect() # For PyPy or other GCs.
self.assertEqual(weakref.getweakrefcount(o), 0,
"weak reference objects not unlinked from"
" referent when discarded.")
# assumes ints do not support weakrefs
self.assertEqual(weakref.getweakrefcount(1), 0,
"got wrong number of weak reference objects for int")
def test_getweakrefs(self):
o = C()
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del ref1
gc_collect() # For PyPy or other GCs.
self.assertEqual(weakref.getweakrefs(o), [ref2],
"list of refs does not match")
o = C()
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del ref2
gc_collect() # For PyPy or other GCs.
self.assertEqual(weakref.getweakrefs(o), [ref1],
"list of refs does not match")
del ref1
gc_collect() # For PyPy or other GCs.
self.assertEqual(weakref.getweakrefs(o), [],
"list of refs not cleared")
# assumes ints do not support weakrefs
self.assertEqual(weakref.getweakrefs(1), [],
"list of refs does not match for int")
def test_newstyle_number_ops(self):
class F(float):
pass
f = F(2.0)
p = weakref.proxy(f)
self.assertEqual(p + 1.0, 3.0)
self.assertEqual(1.0 + p, 3.0) # this used to SEGV
def test_callbacks_protected(self):
# Callbacks protected from already-set exceptions?
# Regression test for SF bug #478534.
class BogusError(Exception):
pass
data = {}
def remove(k):
del data[k]
def encapsulate():
f = lambda : ()
data[weakref.ref(f, remove)] = None
raise BogusError
try:
encapsulate()
except BogusError:
pass
else:
self.fail("exception not properly restored")
try:
encapsulate()
except BogusError:
pass
else:
self.fail("exception not properly restored")
def test_sf_bug_840829(self):
# "weakref callbacks and gc corrupt memory"
# subtype_dealloc erroneously exposed a new-style instance
# already in the process of getting deallocated to gc,
# causing double-deallocation if the instance had a weakref
# callback that triggered gc.
# If the bug exists, there probably won't be an obvious symptom
# in a release build. In a debug build, a segfault will occur
# when the second attempt to remove the instance from the "list
# of all objects" occurs.
import gc
class C(object):
pass
c = C()
wr = weakref.ref(c, lambda ignore: gc.collect())
del c
# There endeth the first part. It gets worse.
del wr
c1 = C()
c1.i = C()
wr = weakref.ref(c1.i, lambda ignore: gc.collect())
c2 = C()
c2.c1 = c1
del c1 # still alive because c2 points to it
# Now when subtype_dealloc gets called on c2, it's not enough just
# that c2 is immune from gc while the weakref callbacks associated
# with c2 execute (there are none in this 2nd half of the test, btw).
# subtype_dealloc goes on to call the base classes' deallocs too,
# so any gc triggered by weakref callbacks associated with anything
# torn down by a base class dealloc can also trigger double
# deallocation of c2.
del c2
@suppress_immortalization()
def test_callback_in_cycle(self):
import gc
class J(object):
pass
class II(object):
def acallback(self, ignore):
self.J
I = II()
I.J = J
I.wr = weakref.ref(J, I.acallback)
# Now J and II are each in a self-cycle (as all new-style class
# objects are, since their __mro__ points back to them). I holds
# both a weak reference (I.wr) and a strong reference (I.J) to class
# J. I is also in a cycle (I.wr points to a weakref that references
# I.acallback). When we del these three, they all become trash, but
# the cycles prevent any of them from getting cleaned up immediately.
# Instead they have to wait for cyclic gc to deduce that they're
# trash.
#
# gc used to call tp_clear on all of them, and the order in which
# it does that is pretty accidental. The exact order in which we
# built up these things manages to provoke gc into running tp_clear
# in just the right order (I last). Calling tp_clear on II leaves
# behind an insane class object (its __mro__ becomes NULL). Calling
# tp_clear on J breaks its self-cycle, but J doesn't get deleted
# just then because of the strong reference from I.J. Calling
# tp_clear on I starts to clear I's __dict__, and just happens to
# clear I.J first -- I.wr is still intact. That removes the last
# reference to J, which triggers the weakref callback. The callback
# tries to do "self.J", and instances of new-style classes look up
# attributes ("J") in the class dict first. The class (II) wants to
# search II.__mro__, but that's NULL. The result was a segfault in
# a release build, and an assert failure in a debug build.
del I, J, II
gc.collect()
def test_callback_reachable_one_way(self):
import gc
# This one broke the first patch that fixed the previous test. In this case,
# the objects reachable from the callback aren't also reachable
# from the object (c1) *triggering* the callback: you can get to
# c1 from c2, but not vice-versa. The result was that c2's __dict__
# got tp_clear'ed by the time the c2.cb callback got invoked.
class C:
def cb(self, ignore):
self.me
self.c1
self.wr
c1, c2 = C(), C()
c2.me = c2
c2.c1 = c1
c2.wr = weakref.ref(c1, c2.cb)
del c1, c2
gc.collect()
def test_callback_different_classes(self):
import gc
# Like test_callback_reachable_one_way, except c2 and c1 have different
# classes. c2's class (C) isn't reachable from c1 then, so protecting
# objects reachable from the dying object (c1) isn't enough to stop
# c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
# The result was a segfault (C.__mro__ was NULL when the callback
# tried to look up self.me).
class C(object):
def cb(self, ignore):
self.me
self.c1
self.wr
class D:
pass
c1, c2 = D(), C()
c2.me = c2
c2.c1 = c1
c2.wr = weakref.ref(c1, c2.cb)
del c1, c2, C, D
gc.collect()
@suppress_immortalization()
def test_callback_in_cycle_resurrection(self):
import gc
# Do something nasty in a weakref callback: resurrect objects
# from dead cycles. For this to be attempted, the weakref and
# its callback must also be part of the cyclic trash (else the
# objects reachable via the callback couldn't be in cyclic trash
# to begin with -- the callback would act like an external root).
# But gc clears trash weakrefs with callbacks early now, which
# disables the callbacks, so the callbacks shouldn't get called
# at all (and so nothing actually gets resurrected).
alist = []
class C(object):
def __init__(self, value):
self.attribute = value
def acallback(self, ignore):
alist.append(self.c)
c1, c2 = C(1), C(2)
c1.c = c2
c2.c = c1
c1.wr = weakref.ref(c2, c1.acallback)
c2.wr = weakref.ref(c1, c2.acallback)
def C_went_away(ignore):
alist.append("C went away")
wr = weakref.ref(C, C_went_away)
del c1, c2, C # make them all trash
self.assertEqual(alist, []) # del isn't enough to reclaim anything
gc.collect()
# c1.wr and c2.wr were part of the cyclic trash, so should have
# been cleared without their callbacks executing. OTOH, the weakref
# to C is bound to a function local (wr), and wasn't trash, so that
# callback should have been invoked when C went away.
self.assertEqual(alist, ["C went away"])
# The remaining weakref should be dead now (its callback ran).
self.assertEqual(wr(), None)
del alist[:]
gc.collect()
self.assertEqual(alist, [])
def test_callbacks_on_callback(self):
import gc
# Set up weakref callbacks *on* weakref callbacks.
alist = []
def safe_callback(ignore):
alist.append("safe_callback called")
class C(object):
def cb(self, ignore):
alist.append("cb called")
c, d = C(), C()
c.other = d
d.other = c
callback = c.cb
c.wr = weakref.ref(d, callback) # this won't trigger
d.wr = weakref.ref(callback, d.cb) # ditto
external_wr = weakref.ref(callback, safe_callback) # but this will
self.assertIs(external_wr(), callback)
# The weakrefs attached to c and d should get cleared, so that
# C.cb is never called. But external_wr isn't part of the cyclic
# trash, and no cyclic trash is reachable from it, so safe_callback
# should get invoked when the bound method object callback (c.cb)
# -- which is itself a callback, and also part of the cyclic trash --
# gets reclaimed at the end of gc.
del callback, c, d, C
self.assertEqual(alist, []) # del isn't enough to clean up cycles
gc.collect()
self.assertEqual(alist, ["safe_callback called"])
self.assertEqual(external_wr(), None)
del alist[:]
gc.collect()
self.assertEqual(alist, [])
def test_gc_during_ref_creation(self):
self.check_gc_during_creation(weakref.ref)
def test_gc_during_proxy_creation(self):
self.check_gc_during_creation(weakref.proxy)
def check_gc_during_creation(self, makeref):
thresholds = gc.get_threshold()
gc.set_threshold(1, 1, 1)
gc.collect()
class A:
pass
def callback(*args):
pass
referenced = A()
a = A()
a.a = a
a.wr = makeref(referenced)
try:
# now make sure the object and the ref get labeled as
# cyclic trash:
a = A()
weakref.ref(referenced, callback)
finally:
gc.set_threshold(*thresholds)
def test_ref_created_during_del(self):
# Bug #1377858
# A weakref created in an object's __del__() would crash the
# interpreter when the weakref was cleaned up since it would refer to
# non-existent memory. This test should not segfault the interpreter.
class Target(object):
def __del__(self):
global ref_from_del
ref_from_del = weakref.ref(self)
w = Target()
def test_init(self):
# Issue 3634
# <weakref to class>.__init__() doesn't check errors correctly
r = weakref.ref(Exception)
self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
# No exception should be raised here
gc.collect()
@suppress_immortalization()
def test_classes(self):
# Check that classes are weakrefable.
class A(object):
pass
l = []
weakref.ref(int)
a = weakref.ref(A, l.append)
A = None
gc.collect()
self.assertEqual(a(), None)
self.assertEqual(l, [a])
def test_equality(self):
# Alive weakrefs defer equality testing to their underlying object.
x = Object(1)
y = Object(1)
z = Object(2)
a = weakref.ref(x)
b = weakref.ref(y)
c = weakref.ref(z)
d = weakref.ref(x)
# Note how we directly test the operators here, to stress both
# __eq__ and __ne__.
self.assertTrue(a == b)
self.assertFalse(a != b)
self.assertFalse(a == c)
self.assertTrue(a != c)
self.assertTrue(a == d)
self.assertFalse(a != d)
self.assertFalse(a == x)
self.assertTrue(a != x)
self.assertTrue(a == ALWAYS_EQ)
self.assertFalse(a != ALWAYS_EQ)
del x, y, z
gc.collect()
for r in a, b, c:
# Sanity check
self.assertIs(r(), None)
# Dead weakrefs compare by identity: whether `a` and `d` are the
# same weakref object is an implementation detail, since they pointed
# to the same original object and didn't have a callback.
# (see issue #16453).
self.assertFalse(a == b)
self.assertTrue(a != b)
self.assertFalse(a == c)
self.assertTrue(a != c)
self.assertEqual(a == d, a is d)
self.assertEqual(a != d, a is not d)
def test_ordering(self):
# weakrefs cannot be ordered, even if the underlying objects can.
ops = [operator.lt, operator.gt, operator.le, operator.ge]
x = Object(1)
y = Object(1)
a = weakref.ref(x)
b = weakref.ref(y)
for op in ops:
self.assertRaises(TypeError, op, a, b)
# Same when dead.
del x, y
gc.collect()
for op in ops:
self.assertRaises(TypeError, op, a, b)
def test_hashing(self):
# Alive weakrefs hash the same as the underlying object
x = Object(42)
y = Object(42)
a = weakref.ref(x)
b = weakref.ref(y)
self.assertEqual(hash(a), hash(42))
del x, y
gc.collect()
# Dead weakrefs:
# - retain their hash is they were hashed when alive;
# - otherwise, cannot be hashed.
self.assertEqual(hash(a), hash(42))
self.assertRaises(TypeError, hash, b)
@unittest.skipIf(is_wasi and Py_DEBUG, "requires deep stack")
def test_trashcan_16602(self):
# Issue #16602: when a weakref's target was part of a long
# deallocation chain, the trashcan mechanism could delay clearing
# of the weakref and make the target object visible from outside
# code even though its refcount had dropped to 0. A crash ensued.
class C:
def __init__(self, parent):
if not parent:
return
wself = weakref.ref(self)
def cb(wparent):
o = wself()
self.wparent = weakref.ref(parent, cb)
d = weakref.WeakKeyDictionary()
root = c = C(None)
for n in range(100):
d[c] = c = C(c)
del root
gc.collect()
def test_callback_attribute(self):
x = Object(1)
callback = lambda ref: None
ref1 = weakref.ref(x, callback)
self.assertIs(ref1.__callback__, callback)
ref2 = weakref.ref(x)
self.assertIsNone(ref2.__callback__)
def test_callback_attribute_after_deletion(self):
x = Object(1)
ref = weakref.ref(x, self.callback)
self.assertIsNotNone(ref.__callback__)
del x
support.gc_collect()
self.assertIsNone(ref.__callback__)
def test_set_callback_attribute(self):
x = Object(1)
callback = lambda ref: None
ref1 = weakref.ref(x, callback)
with self.assertRaises(AttributeError):
ref1.__callback__ = lambda ref: None
def test_callback_gcs(self):
class ObjectWithDel(Object):
def __del__(self): pass
x = ObjectWithDel(1)
ref1 = weakref.ref(x, lambda ref: support.gc_collect())
del x
support.gc_collect()
@support.cpython_only
def test_no_memory_when_clearing(self):
# gh-118331: Make sure we do not raise an exception from the destructor
# when clearing weakrefs if allocating the intermediate tuple fails.
code = textwrap.dedent("""
import _testcapi
import weakref
class TestObj:
pass
def callback(obj):
pass
obj = TestObj()
# The choice of 50 is arbitrary, but must be large enough to ensure
# the allocation won't be serviced by the free list.
wrs = [weakref.ref(obj, callback) for _ in range(50)]
_testcapi.set_nomemory(0)
del obj
""").strip()
res, _ = script_helper.run_python_until_end("-c", code)
stderr = res.err.decode("ascii", "backslashreplace")
self.assertNotRegex(stderr, "_Py_Dealloc: Deallocator of type 'TestObj'")
| ReferencesTestCase |
python | PrefectHQ__prefect | src/prefect/tasks.py | {
"start": 9991,
"end": 79590
} | class ____(Generic[P, R]):
"""
A Prefect task definition.
Wraps a function with an entrypoint to the Prefect engine. Calling this class within a flow function
creates a new task run.
To preserve the input and output types, we use the generic type variables P and R for "Parameters" and
"Returns" respectively.
Args:
fn: The function defining the task.
name: An optional name for the task; if not provided, the name will be inferred
from the given function.
description: An optional string description for the task.
tags: An optional set of tags to be associated with runs of this task. These
tags are combined with any tags defined by a `prefect.tags` context at
task runtime.
version: An optional string specifying the version of this task definition
cache_policy: A cache policy that determines the level of caching for this task
cache_key_fn: An optional callable that, given the task run context and call
parameters, generates a string key; if the key matches a previous completed
state, that state result will be restored instead of running the task again.
cache_expiration: An optional amount of time indicating how long cached states
for this task should be restorable; if not provided, cached states will
never expire.
task_run_name: An optional name to distinguish runs of this task; this name can be provided
as a string template with the task's keyword arguments as variables,
or a function that returns a string.
retries: An optional number of times to retry on task run failure.
retry_delay_seconds: Optionally configures how long to wait before retrying the
task after failure. This is only applicable if `retries` is nonzero. This
setting can either be a number of seconds, a list of retry delays, or a
callable that, given the total number of retries, generates a list of retry
delays. If a number of seconds, that delay will be applied to all retries.
If a list, each retry will wait for the corresponding delay before retrying.
When passing a callable or a list, the number of configured retry delays
cannot exceed 50.
retry_jitter_factor: An optional factor that defines the factor to which a retry
can be jittered in order to avoid a "thundering herd".
persist_result: A toggle indicating whether the result of this task
should be persisted to result storage. Defaults to `None`, which
indicates that the global default should be used (which is `True` by
default).
result_storage: An optional block to use to persist the result of this task.
Defaults to the value set in the flow the task is called in.
result_storage_key: An optional key to store the result in storage at when persisted.
Defaults to a unique identifier.
result_serializer: An optional serializer to use to serialize the result of this
task for persistence. Defaults to the value set in the flow the task is
called in.
timeout_seconds: An optional number of seconds indicating a maximum runtime for
the task. If the task exceeds this runtime, it will be marked as failed.
log_prints: If set, `print` statements in the task will be redirected to the
Prefect logger for the task run. Defaults to `None`, which indicates
that the value from the flow should be used.
refresh_cache: If set, cached results for the cache key are not used.
Defaults to `None`, which indicates that a cached result from a previous
execution with matching cache key is used.
on_failure: An optional list of callables to run when the task enters a failed state.
on_completion: An optional list of callables to run when the task enters a completed state.
on_commit: An optional list of callables to run when the task's idempotency record is committed.
on_rollback: An optional list of callables to run when the task rolls back.
retry_condition_fn: An optional callable run when a task run returns a Failed state. Should
return `True` if the task should continue to its retry policy (e.g. `retries=3`), and `False` if the task
should end as failed. Defaults to `None`, indicating the task should always continue
to its retry policy.
viz_return_value: An optional value to return when the task dependency tree is visualized.
asset_deps: An optional list of upstream assets that this task depends on.
"""
# NOTE: These parameters (types, defaults, and docstrings) should be duplicated
# exactly in the @task decorator
def __init__(
self,
fn: Callable[P, R] | "classmethod[Any, P, R]" | "staticmethod[P, R]",
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
version: Optional[str] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Optional[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]]
] = None,
cache_expiration: Optional[datetime.timedelta] = None,
task_run_name: Optional[TaskRunNameValueOrCallable] = None,
retries: Optional[int] = None,
retry_delay_seconds: Optional[
Union[
float,
int,
list[float],
Callable[[int], list[float]],
]
] = None,
retry_jitter_factor: Optional[float] = None,
persist_result: Optional[bool] = None,
result_storage: Optional[ResultStorage] = None,
result_serializer: Optional[ResultSerializer] = None,
result_storage_key: Optional[str] = None,
cache_result_in_memory: bool = True,
timeout_seconds: Union[int, float, None] = None,
log_prints: Optional[bool] = False,
refresh_cache: Optional[bool] = None,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
on_rollback: Optional[list[Callable[["Transaction"], None]]] = None,
on_commit: Optional[list[Callable[["Transaction"], None]]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Optional[Any] = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
):
# Validate if hook passed is list and contains callables
hook_categories = [on_completion, on_failure, on_running]
hook_names = ["on_completion", "on_failure", "on_running"]
for hooks, hook_name in zip(hook_categories, hook_names):
if hooks is not None:
try:
hooks = list(hooks)
except TypeError:
raise TypeError(
f"Expected iterable for '{hook_name}'; got"
f" {type(hooks).__name__} instead. Please provide a list of"
f" hooks to '{hook_name}':\n\n"
f"@task({hook_name}=[hook1, hook2])\ndef"
" my_task():\n\tpass"
)
for hook in hooks:
if not callable(hook):
raise TypeError(
f"Expected callables in '{hook_name}'; got"
f" {type(hook).__name__} instead. Please provide a list of"
f" hooks to '{hook_name}':\n\n"
f"@task({hook_name}=[hook1, hook2])\ndef"
" my_task():\n\tpass"
)
if isinstance(fn, classmethod):
fn = cast(Callable[P, R], fn.__func__)
self._isclassmethod = True
if isinstance(fn, staticmethod):
fn = cast(Callable[P, R], fn.__func__)
self._isstaticmethod = True
if not callable(fn):
raise TypeError("'fn' must be callable")
self.description: str | None = description or inspect.getdoc(fn)
update_wrapper(self, fn)
self.fn = fn
# the task is considered async if its function is async or an async
# generator
self.isasync: bool = inspect.iscoroutinefunction(
self.fn
) or inspect.isasyncgenfunction(self.fn)
# the task is considered a generator if its function is a generator or
# an async generator
self.isgenerator: bool = inspect.isgeneratorfunction(
self.fn
) or inspect.isasyncgenfunction(self.fn)
if not name:
if not hasattr(self.fn, "__name__"):
self.name = type(self.fn).__name__
else:
self.name = self.fn.__name__
else:
self.name: str = name
if task_run_name is not None:
if not isinstance(task_run_name, str) and not callable(task_run_name):
raise TypeError(
"Expected string or callable for 'task_run_name'; got"
f" {type(task_run_name).__name__} instead."
)
self.task_run_name = task_run_name
self.version = version
self.log_prints = log_prints
raise_for_reserved_arguments(self.fn, ["return_state", "wait_for"])
self.tags: set[str] = set(tags if tags else [])
self.task_key: str = _generate_task_key(self.fn)
# determine cache and result configuration
settings = get_current_settings()
if settings.tasks.default_no_cache and cache_policy is NotSet:
cache_policy = NO_CACHE
if cache_policy is not NotSet and cache_key_fn is not None:
logger.warning(
f"Both `cache_policy` and `cache_key_fn` are set on task {self}. `cache_key_fn` will be used."
)
if cache_key_fn:
cache_policy = CachePolicy.from_cache_key_fn(cache_key_fn)
# TODO: manage expiration and cache refresh
self.cache_key_fn = cache_key_fn
self.cache_expiration = cache_expiration
self.refresh_cache = refresh_cache
# result persistence settings
if persist_result is None:
if any(
[
cache_policy
and cache_policy != NO_CACHE
and cache_policy != NotSet,
cache_key_fn is not None,
result_storage_key is not None,
result_storage is not None,
result_serializer is not None,
]
):
persist_result = True
# Check for global cache disable setting
if settings.tasks.disable_caching:
cache_policy = NO_CACHE
if persist_result is False:
self.cache_policy = None if cache_policy is None else NO_CACHE
if cache_policy and cache_policy is not NotSet and cache_policy != NO_CACHE:
logger.warning(
"Ignoring `cache_policy` because `persist_result` is False"
)
elif cache_policy is NotSet and result_storage_key is None:
self.cache_policy = DEFAULT
elif cache_policy != NO_CACHE and result_storage_key:
# TODO: handle this situation with double storage
self.cache_policy = None
else:
self.cache_policy: Union[CachePolicy, type[NotSet], None] = cache_policy
# TaskRunPolicy settings
# TODO: We can instantiate a `TaskRunPolicy` and add Pydantic bound checks to
# validate that the user passes positive numbers here
self.retries: int = (
retries if retries is not None else settings.tasks.default_retries
)
if retry_delay_seconds is None:
retry_delay_seconds = settings.tasks.default_retry_delay_seconds
if callable(retry_delay_seconds):
self.retry_delay_seconds = retry_delay_seconds(self.retries)
elif not isinstance(retry_delay_seconds, (list, int, float, type(None))):
raise TypeError(
f"Invalid `retry_delay_seconds` provided; must be an int, float, list or callable. Received type {type(retry_delay_seconds)}"
)
else:
self.retry_delay_seconds: Union[float, int, list[float], None] = (
retry_delay_seconds
)
if isinstance(self.retry_delay_seconds, list) and (
len(self.retry_delay_seconds) > 50
):
raise ValueError("Can not configure more than 50 retry delays per task.")
if retry_jitter_factor is not None and retry_jitter_factor < 0:
raise ValueError("`retry_jitter_factor` must be >= 0.")
self.retry_jitter_factor = retry_jitter_factor
self.persist_result = persist_result
if result_storage and not isinstance(result_storage, str):
if getattr(result_storage, "_block_document_id", None) is None:
raise TypeError(
"Result storage configuration must be persisted server-side."
" Please call `.save()` on your block before passing it in."
)
self.result_storage = result_storage
self.result_serializer = result_serializer
self.result_storage_key = result_storage_key
self.cache_result_in_memory = cache_result_in_memory
self.timeout_seconds: Union[float, None] = (
float(timeout_seconds) if timeout_seconds else None
)
self.on_rollback_hooks: list[Callable[["Transaction"], None]] = (
on_rollback or []
)
self.on_commit_hooks: list[Callable[["Transaction"], None]] = on_commit or []
self.on_completion_hooks: list[StateHookCallable] = on_completion or []
self.on_failure_hooks: list[StateHookCallable] = on_failure or []
self.on_running_hooks: list[StateHookCallable] = on_running or []
# retry_condition_fn must be a callable or None. If it is neither, raise a TypeError
if retry_condition_fn is not None and not (callable(retry_condition_fn)):
raise TypeError(
"Expected `retry_condition_fn` to be callable, got"
f" {type(retry_condition_fn).__name__} instead."
)
self.retry_condition_fn = retry_condition_fn
self.viz_return_value = viz_return_value
from prefect.assets import Asset
self.asset_deps: list[Asset] = (
[Asset(key=a) if isinstance(a, str) else a for a in asset_deps]
if asset_deps
else []
)
@property
def ismethod(self) -> bool:
return hasattr(self.fn, "__prefect_self__")
@property
def isclassmethod(self) -> bool:
return getattr(self, "_isclassmethod", False)
@property
def isstaticmethod(self) -> bool:
return getattr(self, "_isstaticmethod", False)
def __get__(self, instance: Any, owner: Any) -> "Task[P, R]":
"""
Implement the descriptor protocol so that the task can be used as an instance method.
When an instance method is loaded, this method is called with the "self" instance as
an argument. We return a copy of the task with that instance bound to the task's function.
"""
# wrapped function is a classmethod
if self.isclassmethod:
bound_task = copy(self)
setattr(bound_task.fn, "__prefect_cls__", owner)
return bound_task
# if the task is being accessed on an instance, bind the instance to the __prefect_self__ attribute
# of the task's function. This will allow it to be automatically added to the task's parameters
if instance:
bound_task = copy(self)
bound_task.fn.__prefect_self__ = instance # type: ignore[attr-defined]
return bound_task
return self
def with_options(
self,
*,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Optional[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]]
] = None,
task_run_name: Optional[
Union[TaskRunNameValueOrCallable, type[NotSet]]
] = NotSet,
cache_expiration: Optional[datetime.timedelta] = None,
retries: Union[int, type[NotSet]] = NotSet,
retry_delay_seconds: Union[
float,
int,
list[float],
Callable[[int], list[float]],
type[NotSet],
] = NotSet,
retry_jitter_factor: Union[float, type[NotSet]] = NotSet,
persist_result: Union[bool, type[NotSet]] = NotSet,
result_storage: Union[ResultStorage, type[NotSet]] = NotSet,
result_serializer: Union[ResultSerializer, type[NotSet]] = NotSet,
result_storage_key: Union[str, type[NotSet]] = NotSet,
cache_result_in_memory: Optional[bool] = None,
timeout_seconds: Union[int, float, None] = None,
log_prints: Union[bool, type[NotSet]] = NotSet,
refresh_cache: Union[bool, type[NotSet]] = NotSet,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Optional[Any] = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
) -> "Task[P, R]":
"""
Create a new task from the current object, updating provided options.
Args:
name: A new name for the task.
description: A new description for the task.
tags: A new set of tags for the task. If given, existing tags are ignored,
not merged.
cache_key_fn: A new cache key function for the task.
cache_expiration: A new cache expiration time for the task.
task_run_name: An optional name to distinguish runs of this task; this name can be provided
as a string template with the task's keyword arguments as variables,
or a function that returns a string.
retries: A new number of times to retry on task run failure.
retry_delay_seconds: Optionally configures how long to wait before retrying
the task after failure. This is only applicable if `retries` is nonzero.
This setting can either be a number of seconds, a list of retry delays,
or a callable that, given the total number of retries, generates a list
of retry delays. If a number of seconds, that delay will be applied to
all retries. If a list, each retry will wait for the corresponding delay
before retrying. When passing a callable or a list, the number of
configured retry delays cannot exceed 50.
retry_jitter_factor: An optional factor that defines the factor to which a
retry can be jittered in order to avoid a "thundering herd".
persist_result: A new option for enabling or disabling result persistence.
result_storage: A new storage type to use for results.
result_serializer: A new serializer to use for results.
result_storage_key: A new key for the persisted result to be stored at.
timeout_seconds: A new maximum time for the task to complete in seconds.
log_prints: A new option for enabling or disabling redirection of `print` statements.
refresh_cache: A new option for enabling or disabling cache refresh.
on_completion: A new list of callables to run when the task enters a completed state.
on_failure: A new list of callables to run when the task enters a failed state.
retry_condition_fn: An optional callable run when a task run returns a Failed state.
Should return `True` if the task should continue to its retry policy, and `False`
if the task should end as failed. Defaults to `None`, indicating the task should
always continue to its retry policy.
viz_return_value: An optional value to return when the task dependency tree is visualized.
Returns:
A new `Task` instance.
Examples:
Create a new task from an existing task and update the name:
```python
@task(name="My task")
def my_task():
return 1
new_task = my_task.with_options(name="My new task")
```
Create a new task from an existing task and update the retry settings:
```python
from random import randint
@task(retries=1, retry_delay_seconds=5)
def my_task():
x = randint(0, 5)
if x >= 3: # Make a task that fails sometimes
raise ValueError("Retry me please!")
return x
new_task = my_task.with_options(retries=5, retry_delay_seconds=2)
```
Use a task with updated options within a flow:
```python
@task(name="My task")
def my_task():
return 1
@flow
my_flow():
new_task = my_task.with_options(name="My new task")
new_task()
```
"""
return Task(
fn=self.fn,
name=name or self.name,
description=description or self.description,
tags=tags or copy(self.tags),
cache_policy=cache_policy
if cache_policy is not NotSet
else self.cache_policy,
cache_key_fn=cache_key_fn or self.cache_key_fn,
cache_expiration=cache_expiration or self.cache_expiration,
task_run_name=task_run_name
if task_run_name is not NotSet
else self.task_run_name,
retries=retries if retries is not NotSet else self.retries,
retry_delay_seconds=(
retry_delay_seconds
if retry_delay_seconds is not NotSet
else self.retry_delay_seconds
),
retry_jitter_factor=(
retry_jitter_factor
if retry_jitter_factor is not NotSet
else self.retry_jitter_factor
),
persist_result=(
persist_result if persist_result is not NotSet else self.persist_result
),
result_storage=(
result_storage if result_storage is not NotSet else self.result_storage
),
result_storage_key=(
result_storage_key
if result_storage_key is not NotSet
else self.result_storage_key
),
result_serializer=(
result_serializer
if result_serializer is not NotSet
else self.result_serializer
),
cache_result_in_memory=(
cache_result_in_memory
if cache_result_in_memory is not None
else self.cache_result_in_memory
),
timeout_seconds=(
timeout_seconds if timeout_seconds is not None else self.timeout_seconds
),
log_prints=(log_prints if log_prints is not NotSet else self.log_prints),
refresh_cache=(
refresh_cache if refresh_cache is not NotSet else self.refresh_cache
),
on_completion=on_completion or self.on_completion_hooks,
on_failure=on_failure or self.on_failure_hooks,
on_running=on_running or self.on_running_hooks,
retry_condition_fn=retry_condition_fn or self.retry_condition_fn,
viz_return_value=viz_return_value or self.viz_return_value,
asset_deps=asset_deps or self.asset_deps,
)
def on_completion(self, fn: StateHookCallable) -> StateHookCallable:
self.on_completion_hooks.append(fn)
return fn
def on_failure(self, fn: StateHookCallable) -> StateHookCallable:
self.on_failure_hooks.append(fn)
return fn
def on_running(self, fn: StateHookCallable) -> StateHookCallable:
self.on_running_hooks.append(fn)
return fn
def on_commit(
self, fn: Callable[["Transaction"], None]
) -> Callable[["Transaction"], None]:
self.on_commit_hooks.append(fn)
return fn
def on_rollback(
self, fn: Callable[["Transaction"], None]
) -> Callable[["Transaction"], None]:
self.on_rollback_hooks.append(fn)
return fn
async def create_run(
self,
client: Optional["PrefectClient"] = None,
id: Optional[UUID] = None,
parameters: Optional[dict[str, Any]] = None,
flow_run_context: Optional[FlowRunContext] = None,
parent_task_run_context: Optional[TaskRunContext] = None,
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
extra_task_inputs: Optional[dict[str, set[RunInput]]] = None,
deferred: bool = False,
) -> TaskRun:
from prefect.utilities._engine import dynamic_key_for_task_run
from prefect.utilities.engine import collect_task_run_inputs_sync
if flow_run_context is None:
flow_run_context = FlowRunContext.get()
if parent_task_run_context is None:
parent_task_run_context = TaskRunContext.get()
if parameters is None:
parameters = {}
if client is None:
client = get_client()
async with client:
if not flow_run_context:
dynamic_key = f"{self.task_key}-{str(uuid4().hex)}"
task_run_name = self.name
else:
dynamic_key = dynamic_key_for_task_run(
context=flow_run_context, task=self
)
task_run_name = f"{self.name}-{dynamic_key}"
if deferred:
state = Scheduled()
state.state_details.deferred = True
else:
state = Pending()
# store parameters for background tasks so that task worker
# can retrieve them at runtime
if deferred and (parameters or wait_for):
from prefect.task_worker import store_parameters
parameters_id = uuid4()
state.state_details.task_parameters_id = parameters_id
# TODO: Improve use of result storage for parameter storage / reference
self.persist_result = True
store = await ResultStore(
result_storage=await get_or_create_default_task_scheduling_storage()
).update_for_task(self)
context = serialize_context()
data: dict[str, Any] = {"context": context}
if parameters:
data["parameters"] = parameters
if wait_for:
data["wait_for"] = wait_for
await store_parameters(store, parameters_id, data)
# collect task inputs
task_inputs = {
k: collect_task_run_inputs_sync(v) for k, v in parameters.items()
}
# collect all parent dependencies
if task_parents := _infer_parent_task_runs(
flow_run_context=flow_run_context,
task_run_context=parent_task_run_context,
parameters=parameters,
):
task_inputs["__parents__"] = task_parents
# check wait for dependencies
if wait_for:
task_inputs["wait_for"] = collect_task_run_inputs_sync(wait_for)
# Join extra task inputs
for k, extras in (extra_task_inputs or {}).items():
task_inputs[k] = task_inputs[k].union(extras)
# create the task run
task_run = client.create_task_run(
task=self,
name=task_run_name,
flow_run_id=(
getattr(flow_run_context.flow_run, "id", None)
if flow_run_context and flow_run_context.flow_run
else None
),
dynamic_key=str(dynamic_key),
id=id,
state=state,
task_inputs=task_inputs,
extra_tags=TagsContext.get().current_tags,
)
# the new engine uses sync clients but old engines use async clients
if inspect.isawaitable(task_run):
task_run = await task_run
return task_run
async def create_local_run(
self,
client: Optional["PrefectClient"] = None,
id: Optional[UUID] = None,
parameters: Optional[dict[str, Any]] = None,
flow_run_context: Optional[FlowRunContext] = None,
parent_task_run_context: Optional[TaskRunContext] = None,
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
extra_task_inputs: Optional[dict[str, set[RunInput]]] = None,
deferred: bool = False,
) -> TaskRun:
from prefect.utilities._engine import dynamic_key_for_task_run
from prefect.utilities.engine import (
collect_task_run_inputs_sync,
)
if flow_run_context is None:
flow_run_context = FlowRunContext.get()
if parent_task_run_context is None:
parent_task_run_context = TaskRunContext.get()
if parameters is None:
parameters = {}
if client is None:
client = get_client()
async with client:
if not flow_run_context:
dynamic_key = f"{self.task_key}-{str(uuid4().hex)}"
task_run_name = self.name
else:
dynamic_key = dynamic_key_for_task_run(
context=flow_run_context, task=self, stable=False
)
task_run_name = f"{self.name}-{dynamic_key[:3]}"
if deferred:
state = Scheduled()
state.state_details.deferred = True
else:
state = Pending()
# store parameters for background tasks so that task worker
# can retrieve them at runtime
if deferred and (parameters or wait_for):
from prefect.task_worker import store_parameters
parameters_id = uuid4()
state.state_details.task_parameters_id = parameters_id
# TODO: Improve use of result storage for parameter storage / reference
self.persist_result = True
store = await ResultStore(
result_storage=await get_or_create_default_task_scheduling_storage()
).update_for_task(self)
context = serialize_context()
data: dict[str, Any] = {"context": context}
if parameters:
data["parameters"] = parameters
if wait_for:
data["wait_for"] = wait_for
await store_parameters(store, parameters_id, data)
# collect task inputs
task_inputs = {
k: collect_task_run_inputs_sync(v) for k, v in parameters.items()
}
# collect all parent dependencies
if task_parents := _infer_parent_task_runs(
flow_run_context=flow_run_context,
task_run_context=parent_task_run_context,
parameters=parameters,
):
task_inputs["__parents__"] = task_parents
# check wait for dependencies
if wait_for:
task_inputs["wait_for"] = collect_task_run_inputs_sync(wait_for)
# Join extra task inputs
for k, extras in (extra_task_inputs or {}).items():
task_inputs[k] = task_inputs[k].union(extras)
flow_run_id = (
getattr(flow_run_context.flow_run, "id", None)
if flow_run_context and flow_run_context.flow_run
else None
)
task_run_id = id or uuid7()
state = prefect.states.Pending(
state_details=StateDetails(
task_run_id=task_run_id,
flow_run_id=flow_run_id,
)
)
task_run = TaskRun(
id=task_run_id,
name=task_run_name,
flow_run_id=flow_run_id,
task_key=self.task_key,
dynamic_key=str(dynamic_key),
task_version=self.version,
empirical_policy=TaskRunPolicy(
retries=self.retries,
retry_delay=self.retry_delay_seconds,
retry_jitter_factor=self.retry_jitter_factor,
),
tags=list(set(self.tags).union(TagsContext.get().current_tags or [])),
task_inputs=task_inputs or {},
expected_start_time=state.timestamp,
state_id=state.id,
state_type=state.type,
state_name=state.name,
state=state,
created=state.timestamp,
updated=state.timestamp,
)
return task_run
# PRIORITY OVERLOADS: Clean ParamSpec signatures for normal usage (no return_state/wait_for)
# These preserve full parameter type checking when users call tasks normally
@overload
def __call__(
self: "Task[P, Coroutine[Any, Any, R]]",
*args: P.args,
**kwargs: P.kwargs,
) -> Coroutine[Any, Any, R]: ...
@overload
def __call__(
self: "Task[P, R]",
*args: P.args,
**kwargs: P.kwargs,
) -> R: ...
@overload
def __call__(
self: "Task[P, NoReturn]",
*args: P.args,
**kwargs: P.kwargs,
) -> None:
# `NoReturn` matches if a type can't be inferred for the function which stops a
# sync function from matching the `Coroutine` overload
...
# SECONDARY OVERLOADS: With return_state/wait_for using Any
# When return_state or wait_for are used, we can't preserve ParamSpec semantics,
# so we use Any for parameters. This is an acceptable tradeoff since these
# are advanced use cases.
@overload
def __call__(
self: "Task[..., Coroutine[Any, Any, R]]",
*args: Any,
return_state: Literal[False],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
) -> Coroutine[Any, Any, R]: ...
@overload
def __call__(
self: "Task[..., Coroutine[Any, Any, R]]",
*args: Any,
return_state: Literal[True],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
) -> State[R]: ...
@overload
def __call__(
self: "Task[..., R]",
*args: Any,
return_state: Literal[False],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
) -> R: ...
@overload
def __call__(
self: "Task[..., R]",
*args: Any,
return_state: Literal[True],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
) -> State[R]: ...
@overload
def __call__(
self: "Task[..., Coroutine[Any, Any, R]]",
*args: Any,
wait_for: OneOrManyFutureOrResult[Any],
return_state: Literal[False] = False,
**kwargs: Any,
) -> Coroutine[Any, Any, R]: ...
@overload
def __call__(
self: "Task[..., R]",
*args: Any,
wait_for: OneOrManyFutureOrResult[Any],
return_state: Literal[False] = False,
**kwargs: Any,
) -> R: ...
def __call__(
self: "Union[Task[..., R], Task[..., NoReturn]]",
*args: Any,
return_state: bool = False,
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
) -> Union[R, State[R], None]:
"""
Run the task and return the result. If `return_state` is True returns
the result is wrapped in a Prefect State which provides error handling.
"""
from prefect.utilities.visualization import (
get_task_viz_tracker,
track_viz_task,
)
# Convert the call args/kwargs to a parameter dict
parameters = get_call_parameters(self.fn, args, kwargs)
return_type = "state" if return_state else "result"
task_run_tracker = get_task_viz_tracker()
if task_run_tracker:
return track_viz_task(
self.isasync, self.name, parameters, self.viz_return_value
)
from prefect.task_engine import run_task
return run_task(
task=self,
parameters=parameters,
wait_for=wait_for,
return_type=return_type,
)
@overload
def submit(
self: "Task[P, R]",
*args: P.args,
**kwargs: P.kwargs,
) -> PrefectFuture[R]: ...
@overload
def submit(
self: "Task[P, Coroutine[Any, Any, R]]",
*args: P.args,
return_state: Literal[False],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: P.kwargs,
) -> PrefectFuture[R]: ...
@overload
def submit(
self: "Task[P, R]",
*args: P.args,
return_state: Literal[False],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: P.kwargs,
) -> PrefectFuture[R]: ...
@overload
def submit(
self: "Task[P, Coroutine[Any, Any, R]]",
*args: P.args,
return_state: Literal[True],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: P.kwargs,
) -> State[R]: ...
@overload
def submit(
self: "Task[P, R]",
*args: P.args,
return_state: Literal[True],
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: P.kwargs,
) -> State[R]: ...
def submit(
self: "Union[Task[P, R], Task[P, Coroutine[Any, Any, R]]]",
*args: Any,
return_state: bool = False,
wait_for: Optional[OneOrManyFutureOrResult[Any]] = None,
**kwargs: Any,
):
"""
Submit a run of the task to the engine.
Will create a new task run in the backing API and submit the task to the flow's
task runner. This call only blocks execution while the task is being submitted,
once it is submitted, the flow function will continue executing.
This method is always synchronous, even if the underlying user function is asynchronous.
Args:
*args: Arguments to run the task with
return_state: Return the result of the flow run wrapped in a
Prefect State.
wait_for: Upstream task futures to wait for before starting the task
**kwargs: Keyword arguments to run the task with
Returns:
If `return_state` is False a future allowing asynchronous access to
the state of the task
If `return_state` is True a future wrapped in a Prefect State allowing asynchronous access to
the state of the task
Examples:
Define a task
```python
from prefect import task
@task
def my_task():
return "hello"
```
Run a task in a flow
```python
from prefect import flow
@flow
def my_flow():
my_task.submit()
```
Wait for a task to finish
```python
@flow
def my_flow():
my_task.submit().wait()
```
Use the result from a task in a flow
```python
@flow
def my_flow():
print(my_task.submit().result())
my_flow()
# hello
```
Run an async task in an async flow
```python
@task
async def my_async_task():
pass
@flow
async def my_flow():
my_async_task.submit()
```
Run a sync task in an async flow
```python
@flow
async def my_flow():
my_task.submit()
```
Enforce ordering between tasks that do not exchange data
```python
@task
def task_1():
pass
@task
def task_2():
pass
@flow
def my_flow():
x = task_1.submit()
# task 2 will wait for task_1 to complete
y = task_2.submit(wait_for=[x])
```
"""
from prefect.utilities.visualization import (
VisualizationUnsupportedError,
get_task_viz_tracker,
)
# Convert the call args/kwargs to a parameter dict
parameters = get_call_parameters(self.fn, args, kwargs)
flow_run_context = FlowRunContext.get()
if not flow_run_context:
raise RuntimeError(
"Unable to determine task runner to use for submission. If you are"
" submitting a task outside of a flow, please use `.delay`"
" to submit the task run for deferred execution."
)
task_viz_tracker = get_task_viz_tracker()
if task_viz_tracker:
raise VisualizationUnsupportedError(
"`task.submit()` is not currently supported by `flow.visualize()`"
)
task_runner = flow_run_context.task_runner
future = task_runner.submit(self, parameters, wait_for)
if return_state:
future.wait()
return future.state
else:
return future
@overload
def map(
self: "Task[P, R]",
*args: Any,
return_state: Literal[True],
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> list[State[R]]: ...
@overload
def map(
self: "Task[P, R]",
*args: Any,
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> PrefectFutureList[R]: ...
@overload
def map(
self: "Task[P, R]",
*args: Any,
return_state: Literal[True],
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> list[State[R]]: ...
@overload
def map(
self: "Task[P, R]",
*args: Any,
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> PrefectFutureList[R]: ...
@overload
def map(
self: "Task[P, Coroutine[Any, Any, R]]",
*args: Any,
return_state: Literal[True],
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> list[State[R]]: ...
@overload
def map(
self: "Task[P, Coroutine[Any, Any, R]]",
*args: Any,
return_state: Literal[False],
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = ...,
deferred: bool = ...,
**kwargs: Any,
) -> PrefectFutureList[R]: ...
def map(
self,
*args: Any,
return_state: bool = False,
wait_for: Optional[Iterable[Union[PrefectFuture[R], R]]] = None,
deferred: bool = False,
**kwargs: Any,
) -> Union[list[State[R]], PrefectFutureList[R]]:
"""
Submit a mapped run of the task to a worker.
Must be called within a flow run context. Will return a list of futures
that should be waited on before exiting the flow context to ensure all
mapped tasks have completed.
Must be called with at least one iterable and all iterables must be
the same length. Any arguments that are not iterable will be treated as
a static value and each task run will receive the same value.
Will create as many task runs as the length of the iterable(s) in the
backing API and submit the task runs to the flow's task runner. This
call blocks if given a future as input while the future is resolved. It
also blocks while the tasks are being submitted, once they are
submitted, the flow function will continue executing.
This method is always synchronous, even if the underlying user function is asynchronous.
Args:
*args: Iterable and static arguments to run the tasks with
return_state: Return a list of Prefect States that wrap the results
of each task run.
wait_for: Upstream task futures to wait for before starting the
task
**kwargs: Keyword iterable arguments to run the task with
Returns:
A list of futures allowing asynchronous access to the state of the
tasks
Examples:
Define a task
```python
from prefect import task
@task
def my_task(x):
return x + 1
```
Create mapped tasks
```python
from prefect import flow
@flow
def my_flow():
return my_task.map([1, 2, 3])
```
Wait for all mapped tasks to finish
```python
@flow
def my_flow():
futures = my_task.map([1, 2, 3])
futures.wait():
# Now all of the mapped tasks have finished
my_task(10)
```
Use the result from mapped tasks in a flow
```python
@flow
def my_flow():
futures = my_task.map([1, 2, 3])
for x in futures.result():
print(x)
my_flow()
# 2
# 3
# 4
```
Enforce ordering between tasks that do not exchange data
```python
@task
def task_1(x):
pass
@task
def task_2(y):
pass
@flow
def my_flow():
x = task_1.submit()
# task 2 will wait for task_1 to complete
y = task_2.map([1, 2, 3], wait_for=[x])
return y
```
Use a non-iterable input as a constant across mapped tasks
```python
@task
def display(prefix, item):
print(prefix, item)
@flow
def my_flow():
return display.map("Check it out: ", [1, 2, 3])
my_flow()
# Check it out: 1
# Check it out: 2
# Check it out: 3
```
Use `unmapped` to treat an iterable argument as a constant
```python
from prefect import unmapped
@task
def add_n_to_items(items, n):
return [item + n for item in items]
@flow
def my_flow():
return add_n_to_items.map(unmapped([10, 20]), n=[1, 2, 3])
my_flow()
# [[11, 21], [12, 22], [13, 23]]
```
"""
from prefect.task_runners import TaskRunner
from prefect.utilities.visualization import (
VisualizationUnsupportedError,
get_task_viz_tracker,
)
# Convert the call args/kwargs to a parameter dict; do not apply defaults
# since they should not be mapped over
parameters = get_call_parameters(self.fn, args, kwargs, apply_defaults=False)
flow_run_context = FlowRunContext.get()
task_viz_tracker = get_task_viz_tracker()
if task_viz_tracker:
raise VisualizationUnsupportedError(
"`task.map()` is not currently supported by `flow.visualize()`"
)
if deferred:
parameters_list = expand_mapping_parameters(self.fn, parameters)
futures = [
self.apply_async(kwargs=parameters, wait_for=wait_for)
for parameters in parameters_list
]
elif task_runner := getattr(flow_run_context, "task_runner", None):
assert isinstance(task_runner, TaskRunner)
futures = task_runner.map(self, parameters, wait_for)
else:
raise RuntimeError(
"Unable to determine task runner to use for mapped task runs. If"
" you are mapping a task outside of a flow, please provide"
" `deferred=True` to submit the mapped task runs for deferred"
" execution."
)
if return_state:
states: list[State[R]] = []
for future in futures:
future.wait()
states.append(future.state)
return states
else:
return futures
# Background task methods
def apply_async(
self,
args: Optional[tuple[Any, ...]] = None,
kwargs: Optional[dict[str, Any]] = None,
wait_for: Optional[Iterable[PrefectFuture[R]]] = None,
dependencies: Optional[dict[str, set[RunInput]]] = None,
) -> PrefectDistributedFuture[R]:
"""
Create a pending task run for a task worker to execute.
Args:
args: Arguments to run the task with
kwargs: Keyword arguments to run the task with
Returns:
A PrefectDistributedFuture object representing the pending task run
Examples:
Define a task
```python
from prefect import task
@task
def my_task(name: str = "world"):
return f"hello {name}"
```
Create a pending task run for the task
```python
from prefect import flow
@flow
def my_flow():
my_task.apply_async(("marvin",))
```
Wait for a task to finish
```python
@flow
def my_flow():
my_task.apply_async(("marvin",)).wait()
```
```python
@flow
def my_flow():
print(my_task.apply_async(("marvin",)).result())
my_flow()
# hello marvin
```
TODO: Enforce ordering between tasks that do not exchange data
```python
@task
def task_1():
pass
@task
def task_2():
pass
@flow
def my_flow():
x = task_1.apply_async()
# task 2 will wait for task_1 to complete
y = task_2.apply_async(wait_for=[x])
```
"""
from prefect.utilities.visualization import (
VisualizationUnsupportedError,
get_task_viz_tracker,
)
task_viz_tracker = get_task_viz_tracker()
if task_viz_tracker:
raise VisualizationUnsupportedError(
"`task.apply_async()` is not currently supported by `flow.visualize()`"
)
args = args or ()
kwargs = kwargs or {}
# Convert the call args/kwargs to a parameter dict
parameters = get_call_parameters(self.fn, args, kwargs)
task_run: TaskRun = run_coro_as_sync(
self.create_run(
parameters=parameters,
deferred=True,
wait_for=wait_for,
extra_task_inputs=dependencies,
)
) # type: ignore
from prefect.utilities.engine import emit_task_run_state_change_event
# emit a `SCHEDULED` event for the task run
emit_task_run_state_change_event(
task_run=task_run,
initial_state=None,
validated_state=task_run.state,
)
if get_current_settings().ui_url and (task_run_url := url_for(task_run)):
logger.info(
f"Created task run {task_run.name!r}. View it in the UI at {task_run_url!r}"
)
return PrefectDistributedFuture(task_run_id=task_run.id)
def delay(self, *args: P.args, **kwargs: P.kwargs) -> PrefectDistributedFuture[R]:
"""
An alias for `apply_async` with simpler calling semantics.
Avoids having to use explicit "args" and "kwargs" arguments. Arguments
will pass through as-is to the task.
Examples:
Define a task
```python
from prefect import task
@task
def my_task(name: str = "world"):
return f"hello {name}"
```
Create a pending task run for the task
```python
from prefect import flow
@flow
def my_flow():
my_task.delay("marvin")
```
Wait for a task to finish
```python
@flow
def my_flow():
my_task.delay("marvin").wait()
```
Use the result from a task in a flow
```python
@flow
def my_flow():
print(my_task.delay("marvin").result())
my_flow()
# hello marvin
```
"""
return self.apply_async(args=args, kwargs=kwargs)
@sync_compatible
async def serve(self) -> NoReturn:
"""Serve the task using the provided task runner. This method is used to
establish a websocket connection with the Prefect server and listen for
submitted task runs to execute.
Args:
task_runner: The task runner to use for serving the task. If not provided,
the default task runner will be used.
Examples:
Serve a task using the default task runner
```python
@task
def my_task():
return 1
my_task.serve()
```
"""
from prefect.task_worker import serve
await serve(self)
@overload
def task(__fn: Callable[P, R]) -> Task[P, R]: ...
# see https://github.com/PrefectHQ/prefect/issues/16380
@overload
def task(
__fn: Literal[None] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
version: Optional[str] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Optional[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]]
] = None,
cache_expiration: Optional[datetime.timedelta] = None,
task_run_name: Optional[TaskRunNameValueOrCallable] = None,
retries: int = 0,
retry_delay_seconds: Union[
float, int, list[float], Callable[[int], list[float]], None
] = None,
retry_jitter_factor: Optional[float] = None,
persist_result: Optional[bool] = None,
result_storage: Optional[ResultStorage] = None,
result_storage_key: Optional[str] = None,
result_serializer: Optional[ResultSerializer] = None,
cache_result_in_memory: bool = True,
timeout_seconds: Union[int, float, None] = None,
log_prints: Optional[bool] = None,
refresh_cache: Optional[bool] = None,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Any = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
) -> Callable[[Callable[P, R]], Task[P, R]]: ...
# see https://github.com/PrefectHQ/prefect/issues/16380
@overload
def task(
__fn: Literal[None] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
version: Optional[str] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Optional[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]]
] = None,
cache_expiration: Optional[datetime.timedelta] = None,
task_run_name: Optional[TaskRunNameValueOrCallable] = None,
retries: int = 0,
retry_delay_seconds: Union[
float, int, list[float], Callable[[int], list[float]], None
] = None,
retry_jitter_factor: Optional[float] = None,
persist_result: Optional[bool] = None,
result_storage: Optional[ResultStorage] = None,
result_storage_key: Optional[str] = None,
result_serializer: Optional[ResultSerializer] = None,
cache_result_in_memory: bool = True,
timeout_seconds: Union[int, float, None] = None,
log_prints: Optional[bool] = None,
refresh_cache: Optional[bool] = None,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Any = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
) -> Callable[[Callable[P, R]], Task[P, R]]: ...
@overload # TODO: do we need this overload?
def task(
*,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
version: Optional[str] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Optional[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]]
] = None,
cache_expiration: Optional[datetime.timedelta] = None,
task_run_name: Optional[TaskRunNameValueOrCallable] = None,
retries: int = 0,
retry_delay_seconds: Union[
float,
int,
list[float],
Callable[[int], list[float]],
] = 0,
retry_jitter_factor: Optional[float] = None,
persist_result: Optional[bool] = None,
result_storage: Optional[ResultStorage] = None,
result_storage_key: Optional[str] = None,
result_serializer: Optional[ResultSerializer] = None,
cache_result_in_memory: bool = True,
timeout_seconds: Union[int, float, None] = None,
log_prints: Optional[bool] = None,
refresh_cache: Optional[bool] = None,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Any = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
) -> Callable[[Callable[P, R]], Task[P, R]]: ...
def task(
__fn: Optional[Callable[P, R]] = None,
*,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[Iterable[str]] = None,
version: Optional[str] = None,
cache_policy: Union[CachePolicy, type[NotSet]] = NotSet,
cache_key_fn: Union[
Callable[["TaskRunContext", dict[str, Any]], Optional[str]], None
] = None,
cache_expiration: Optional[datetime.timedelta] = None,
task_run_name: Optional[TaskRunNameValueOrCallable] = None,
retries: Optional[int] = None,
retry_delay_seconds: Union[
float, int, list[float], Callable[[int], list[float]], None
] = None,
retry_jitter_factor: Optional[float] = None,
persist_result: Optional[bool] = None,
result_storage: Optional[ResultStorage] = None,
result_storage_key: Optional[str] = None,
result_serializer: Optional[ResultSerializer] = None,
cache_result_in_memory: bool = True,
timeout_seconds: Union[int, float, None] = None,
log_prints: Optional[bool] = None,
refresh_cache: Optional[bool] = None,
on_completion: Optional[list[StateHookCallable]] = None,
on_failure: Optional[list[StateHookCallable]] = None,
on_running: Optional[list[StateHookCallable]] = None,
retry_condition_fn: Optional[RetryConditionCallable] = None,
viz_return_value: Any = None,
asset_deps: Optional[list[Union[str, Asset]]] = None,
):
"""
Decorator to designate a function as a task in a Prefect workflow.
This decorator may be used for asynchronous or synchronous functions.
Args:
name: An optional name for the task; if not provided, the name will be inferred
from the given function.
description: An optional string description for the task.
tags: An optional set of tags to be associated with runs of this task. These
tags are combined with any tags defined by a `prefect.tags` context at
task runtime.
version: An optional string specifying the version of this task definition
cache_key_fn: An optional callable that, given the task run context and call
parameters, generates a string key; if the key matches a previous completed
state, that state result will be restored instead of running the task again.
cache_expiration: An optional amount of time indicating how long cached states
for this task should be restorable; if not provided, cached states will
never expire.
task_run_name: An optional name to distinguish runs of this task; this name can be provided
as a string template with the task's keyword arguments as variables,
or a function that returns a string.
retries: An optional number of times to retry on task run failure
retry_delay_seconds: Optionally configures how long to wait before retrying the
task after failure. This is only applicable if `retries` is nonzero. This
setting can either be a number of seconds, a list of retry delays, or a
callable that, given the total number of retries, generates a list of retry
delays. If a number of seconds, that delay will be applied to all retries.
If a list, each retry will wait for the corresponding delay before retrying.
When passing a callable or a list, the number of
configured retry delays cannot exceed 50.
retry_jitter_factor: An optional factor that defines the factor to which a
retry can be jittered in order to avoid a "thundering herd".
persist_result: A toggle indicating whether the result of this task
should be persisted to result storage. Defaults to `None`, which
indicates that the global default should be used (which is `True` by
default).
result_storage: An optional block to use to persist the result of this task.
Defaults to the value set in the flow the task is called in.
result_storage_key: An optional key to store the result in storage at when persisted.
Defaults to a unique identifier.
result_serializer: An optional serializer to use to serialize the result of this
task for persistence. Defaults to the value set in the flow the task is
called in.
timeout_seconds: An optional number of seconds indicating a maximum runtime for
the task. If the task exceeds this runtime, it will be marked as failed.
log_prints: If set, `print` statements in the task will be redirected to the
Prefect logger for the task run. Defaults to `None`, which indicates
that the value from the flow should be used.
refresh_cache: If set, cached results for the cache key are not used.
Defaults to `None`, which indicates that a cached result from a previous
execution with matching cache key is used.
on_failure: An optional list of callables to run when the task enters a failed state.
on_completion: An optional list of callables to run when the task enters a completed state.
retry_condition_fn: An optional callable run when a task run returns a Failed state. Should
return `True` if the task should continue to its retry policy (e.g. `retries=3`), and `False` if the task
should end as failed. Defaults to `None`, indicating the task should always continue
to its retry policy.
viz_return_value: An optional value to return when the task dependency tree is visualized.
asset_deps: An optional list of upstream assets that this task depends on.
Returns:
A callable `Task` object which, when called, will submit the task for execution.
Examples:
Define a simple task
```python
@task
def add(x, y):
return x + y
```
Define an async task
```python
@task
async def add(x, y):
return x + y
```
Define a task with tags and a description
```python
@task(tags={"a", "b"}, description="This task is empty but its my first!")
def my_task():
pass
```
Define a task with a custom name
```python
@task(name="The Ultimate Task")
def my_task():
pass
```
Define a task that retries 3 times with a 5 second delay between attempts
```python
from random import randint
@task(retries=3, retry_delay_seconds=5)
def my_task():
x = randint(0, 5)
if x >= 3: # Make a task that fails sometimes
raise ValueError("Retry me please!")
return x
```
Define a task that is cached for a day based on its inputs
```python
from prefect.tasks import task_input_hash
from datetime import timedelta
@task(cache_key_fn=task_input_hash, cache_expiration=timedelta(days=1))
def my_task():
return "hello"
```
"""
if __fn:
return Task(
fn=__fn,
name=name,
description=description,
tags=tags,
version=version,
cache_policy=cache_policy,
cache_key_fn=cache_key_fn,
cache_expiration=cache_expiration,
task_run_name=task_run_name,
retries=retries,
retry_delay_seconds=retry_delay_seconds,
retry_jitter_factor=retry_jitter_factor,
persist_result=persist_result,
result_storage=result_storage,
result_storage_key=result_storage_key,
result_serializer=result_serializer,
cache_result_in_memory=cache_result_in_memory,
timeout_seconds=timeout_seconds,
log_prints=log_prints,
refresh_cache=refresh_cache,
on_completion=on_completion,
on_failure=on_failure,
on_running=on_running,
retry_condition_fn=retry_condition_fn,
viz_return_value=viz_return_value,
asset_deps=asset_deps,
)
else:
return cast(
Callable[[Callable[P, R]], Task[P, R]],
partial(
task,
name=name,
description=description,
tags=tags,
version=version,
cache_policy=cache_policy,
cache_key_fn=cache_key_fn,
cache_expiration=cache_expiration,
task_run_name=task_run_name,
retries=retries,
retry_delay_seconds=retry_delay_seconds,
retry_jitter_factor=retry_jitter_factor,
persist_result=persist_result,
result_storage=result_storage,
result_storage_key=result_storage_key,
result_serializer=result_serializer,
cache_result_in_memory=cache_result_in_memory,
timeout_seconds=timeout_seconds,
log_prints=log_prints,
refresh_cache=refresh_cache,
on_completion=on_completion,
on_failure=on_failure,
on_running=on_running,
retry_condition_fn=retry_condition_fn,
viz_return_value=viz_return_value,
asset_deps=asset_deps,
),
)
| Task |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 91296,
"end": 91372
} | class ____(BinOpFrame):
operation = M.ge
_operator_repr = ">="
| GEFrame |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 5731,
"end": 10397
} | class ____(GoogleCloudBaseOperator):
"""
Create a deidentify template to reuse frequently-used configurations for content, images, and storage.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPCreateDeidentifyTemplateOperator`
:param organization_id: (Optional) The organization ID. Required to set this
field if parent resource is an organization.
:param project_id: (Optional) Google Cloud project ID where the
DLP Instance exists. Only set this field if the parent resource is
a project instead of an organization.
:param deidentify_template: (Optional) The DeidentifyTemplate to create.
:param template_id: (Optional) The template ID.
:param retry: (Optional) A retry object used to retry requests.
If None is specified, requests will not be retried.
:param timeout: (Optional) The amount of time, in seconds, to wait for the request
to complete. Note that if retry is specified, the timeout applies to each
individual attempt.
:param metadata: (Optional) Additional metadata that is provided to the method.
:param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud.
:param impersonation_chain: Optional service account to impersonate using short-term
credentials, or chained list of accounts required to get the access_token
of the last account in the list, which will be impersonated in the request.
If set as a string, the account must grant the originating account
the Service Account Token Creator IAM role.
If set as a sequence, the identities from the list must grant
Service Account Token Creator IAM role to the directly preceding identity, with first
account from the list granting this role to the originating account (templated).
"""
template_fields: Sequence[str] = (
"organization_id",
"project_id",
"deidentify_template",
"template_id",
"gcp_conn_id",
"impersonation_chain",
)
operator_extra_links = (CloudDLPDeidentifyTemplateDetailsLink(),)
def __init__(
self,
*,
organization_id: str | None = None,
project_id: str = PROVIDE_PROJECT_ID,
deidentify_template: dict | DeidentifyTemplate | None = None,
template_id: str | None = None,
retry: Retry | _MethodDefault = DEFAULT,
timeout: float | None = None,
metadata: Sequence[tuple[str, str]] = (),
gcp_conn_id: str = "google_cloud_default",
impersonation_chain: str | Sequence[str] | None = None,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.organization_id = organization_id
self.project_id = project_id
self.deidentify_template = deidentify_template
self.template_id = template_id
self.retry = retry
self.timeout = timeout
self.metadata = metadata
self.gcp_conn_id = gcp_conn_id
self.impersonation_chain = impersonation_chain
def execute(self, context: Context):
hook = CloudDLPHook(
gcp_conn_id=self.gcp_conn_id,
impersonation_chain=self.impersonation_chain,
)
try:
template = hook.create_deidentify_template(
organization_id=self.organization_id,
project_id=self.project_id,
deidentify_template=self.deidentify_template,
template_id=self.template_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
except AlreadyExists:
if self.template_id is None:
raise RuntimeError("The template_id should be set here!")
template = hook.get_deidentify_template(
organization_id=self.organization_id,
project_id=self.project_id,
template_id=self.template_id,
retry=self.retry,
timeout=self.timeout,
metadata=self.metadata,
)
result = DeidentifyTemplate.to_dict(template)
project_id = self.project_id or hook.project_id
template_id = self.template_id or result["name"].split("/")[-1] if result["name"] else None
if project_id and template_id:
CloudDLPDeidentifyTemplateDetailsLink.persist(
context=context,
project_id=project_id,
template_name=template_id,
)
return result
| CloudDLPCreateDeidentifyTemplateOperator |
python | scipy__scipy | scipy/stats/_qmc.py | {
"start": 58212,
"end": 70966
} | class ____(QMCEngine):
"""Engine for generating (scrambled) Sobol' sequences.
Sobol' sequences are low-discrepancy, quasi-random numbers. Points
can be drawn using two methods:
* `random_base2`: safely draw :math:`n=2^m` points. This method
guarantees the balance properties of the sequence.
* `random`: draw an arbitrary number of points from the
sequence. See warning below.
Parameters
----------
d : int
Dimensionality of the sequence. Max dimensionality is 21201.
scramble : bool, optional
If True, use LMS+shift scrambling. Otherwise, no scrambling is done.
Default is True.
bits : int, optional
Number of bits of the generator. Control the maximum number of points
that can be generated, which is ``2**bits``. Maximal value is 64.
It does not correspond to the return type, which is always
``np.float64`` to prevent points from repeating themselves.
Default is None, which for backward compatibility, corresponds to 30.
.. versionadded:: 1.9.0
optimization : {None, "random-cd", "lloyd"}, optional
Whether to use an optimization scheme to improve the quality after
sampling. Note that this is a post-processing step that does not
guarantee that all properties of the sample will be conserved.
Default is None.
* ``random-cd``: random permutations of coordinates to lower the
centered discrepancy. The best sample based on the centered
discrepancy is constantly updated. Centered discrepancy-based
sampling shows better space-filling robustness toward 2D and 3D
subprojections compared to using other discrepancy measures.
* ``lloyd``: Perturb samples using a modified Lloyd-Max algorithm.
The process converges to equally spaced samples.
.. versionadded:: 1.10.0
rng : `numpy.random.Generator`, optional
Pseudorandom number generator state. When `rng` is None, a new
`numpy.random.Generator` is created using entropy from the
operating system. Types other than `numpy.random.Generator` are
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
.. versionchanged:: 1.15.0
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
transition from use of `numpy.random.RandomState` to
`numpy.random.Generator`, this keyword was changed from `seed` to
`rng`. For an interim period, both keywords will continue to work, although
only one may be specified at a time. After the interim period, function
calls using the `seed` keyword will emit warnings. Following a
deprecation period, the `seed` keyword will be removed.
Notes
-----
Sobol' sequences [1]_ provide :math:`n=2^m` low discrepancy points in
:math:`[0,1)^{d}`. Scrambling them [3]_ makes them suitable for singular
integrands, provides a means of error estimation, and can improve their
rate of convergence. The scrambling strategy which is implemented is a
(left) linear matrix scramble (LMS) followed by a digital random shift
(LMS+shift) [2]_.
There are many versions of Sobol' sequences depending on their
'direction numbers'. This code uses direction numbers from [4]_. Hence,
the maximum number of dimension is 21201. The direction numbers have been
precomputed with search criterion 6 and can be retrieved at
https://web.maths.unsw.edu.au/~fkuo/sobol/.
.. warning::
Sobol' sequences are a quadrature rule and they lose their balance
properties if one uses a sample size that is not a power of 2, or skips
the first point, or thins the sequence [5]_.
If :math:`n=2^m` points are not enough then one should take :math:`2^M`
points for :math:`M>m`. When scrambling, the number R of independent
replicates does not have to be a power of 2.
Sobol' sequences are generated to some number :math:`B` of bits.
After :math:`2^B` points have been generated, the sequence would
repeat. Hence, an error is raised.
The number of bits can be controlled with the parameter `bits`.
References
----------
.. [1] I. M. Sobol', "The distribution of points in a cube and the accurate
evaluation of integrals." Zh. Vychisl. Mat. i Mat. Phys., 7:784-802,
1967.
.. [2] J. Matousek, "On the L2-discrepancy for anchored boxes."
J. of Complexity 14, 527-556, 1998.
.. [3] Art B. Owen, "Scrambling Sobol and Niederreiter-Xing points."
Journal of Complexity, 14(4):466-489, December 1998.
.. [4] S. Joe and F. Y. Kuo, "Constructing sobol sequences with better
two-dimensional projections." SIAM Journal on Scientific Computing,
30(5):2635-2654, 2008.
.. [5] Art B. Owen, "On dropping the first Sobol' point."
:arxiv:`2008.08051`, 2020.
Examples
--------
Generate samples from a low discrepancy sequence of Sobol'.
>>> from scipy.stats import qmc
>>> sampler = qmc.Sobol(d=2, scramble=False)
>>> sample = sampler.random_base2(m=3)
>>> sample
array([[0. , 0. ],
[0.5 , 0.5 ],
[0.75 , 0.25 ],
[0.25 , 0.75 ],
[0.375, 0.375],
[0.875, 0.875],
[0.625, 0.125],
[0.125, 0.625]])
Compute the quality of the sample using the discrepancy criterion.
>>> qmc.discrepancy(sample)
0.013882107204860938
To continue an existing design, extra points can be obtained
by calling again `random_base2`. Alternatively, you can skip some
points like:
>>> _ = sampler.reset()
>>> _ = sampler.fast_forward(4)
>>> sample_continued = sampler.random_base2(m=2)
>>> sample_continued
array([[0.375, 0.375],
[0.875, 0.875],
[0.625, 0.125],
[0.125, 0.625]])
Finally, samples can be scaled to bounds.
>>> l_bounds = [0, 2]
>>> u_bounds = [10, 5]
>>> qmc.scale(sample_continued, l_bounds, u_bounds)
array([[3.75 , 3.125],
[8.75 , 4.625],
[6.25 , 2.375],
[1.25 , 3.875]])
"""
MAXDIM: ClassVar[int] = _MAXDIM
@_transition_to_rng('seed', replace_doc=False)
def __init__(
self, d: IntNumber, *, scramble: bool = True,
bits: IntNumber | None = None, rng: SeedType = None,
optimization: Literal["random-cd", "lloyd"] | None = None
) -> None:
# Used in `scipy.integrate.qmc_quad`
self._init_quad = {'d': d, 'scramble': True, 'bits': bits,
'optimization': optimization}
super()._initialize(d=d, optimization=optimization, rng=rng)
if d > self.MAXDIM:
raise ValueError(
f"Maximum supported dimensionality is {self.MAXDIM}."
)
self.bits = bits
self.dtype_i: type
self.scramble = scramble
if self.bits is None:
self.bits = 30
if self.bits <= 32:
self.dtype_i = np.uint32
elif 32 < self.bits <= 64:
self.dtype_i = np.uint64
else:
raise ValueError("Maximum supported 'bits' is 64")
self.maxn = 2**self.bits
# v is d x maxbit matrix
self._sv: np.ndarray = np.zeros((d, self.bits), dtype=self.dtype_i)
_initialize_v(self._sv, dim=d, bits=self.bits)
if not scramble:
self._shift: np.ndarray = np.zeros(d, dtype=self.dtype_i)
else:
# scramble self._shift and self._sv
self._scramble()
self._quasi = self._shift.copy()
# normalization constant with the largest possible number
# calculate in Python to not overflow int with 2**64
self._scale = 1.0 / 2 ** self.bits
self._first_point = (self._quasi * self._scale).reshape(1, -1)
# explicit casting to float64
self._first_point = self._first_point.astype(np.float64)
def _scramble(self) -> None:
"""Scramble the sequence using LMS+shift."""
# Generate shift vector
self._shift = np.dot(
rng_integers(self.rng, 2, size=(self.d, self.bits),
dtype=self.dtype_i),
2 ** np.arange(self.bits, dtype=self.dtype_i),
)
# Generate lower triangular matrices (stacked across dimensions)
ltm = np.tril(rng_integers(self.rng, 2,
size=(self.d, self.bits, self.bits),
dtype=self.dtype_i))
_cscramble(
dim=self.d, bits=self.bits, # type: ignore[arg-type]
ltm=ltm, sv=self._sv
)
def _random(
self, n: IntNumber = 1, *, workers: IntNumber = 1
) -> np.ndarray:
"""Draw next point(s) in the Sobol' sequence.
Parameters
----------
n : int, optional
Number of samples to generate in the parameter space. Default is 1.
Returns
-------
sample : array_like (n, d)
Sobol' sample.
"""
sample: np.ndarray = np.empty((n, self.d), dtype=np.float64)
if n == 0:
return sample
total_n = self.num_generated + n
if total_n > self.maxn:
msg = (
f"At most 2**{self.bits}={self.maxn} distinct points can be "
f"generated. {self.num_generated} points have been previously "
f"generated, then: n={self.num_generated}+{n}={total_n}. "
)
if self.bits != 64:
msg += "Consider increasing `bits`."
raise ValueError(msg)
if self.num_generated == 0:
# verify n is 2**n
if not (n & (n - 1) == 0):
warnings.warn("The balance properties of Sobol' points require"
" n to be a power of 2.", stacklevel=3)
if n == 1:
sample = self._first_point
else:
_draw(
n=n - 1, num_gen=self.num_generated, dim=self.d,
scale=self._scale, sv=self._sv, quasi=self._quasi,
sample=sample
)
sample = np.concatenate(
[self._first_point, sample]
)[:n]
else:
_draw(
n=n, num_gen=self.num_generated - 1, dim=self.d,
scale=self._scale, sv=self._sv, quasi=self._quasi,
sample=sample
)
return sample
def random_base2(self, m: IntNumber) -> np.ndarray:
"""Draw point(s) from the Sobol' sequence.
This function draws :math:`n=2^m` points in the parameter space
ensuring the balance properties of the sequence.
Parameters
----------
m : int
Logarithm in base 2 of the number of samples; i.e., n = 2^m.
Returns
-------
sample : array_like (n, d)
Sobol' sample.
"""
n = 2 ** m
total_n = self.num_generated + n
if not (total_n & (total_n - 1) == 0):
raise ValueError('The balance properties of Sobol\' points require '
f'n to be a power of 2. {self.num_generated} points '
'have been previously generated, then: '
f'n={self.num_generated}+2**{m}={total_n}. '
'If you still want to do this, the function '
'\'Sobol.random()\' can be used.'
)
return self.random(n)
def reset(self) -> "Sobol":
"""Reset the engine to base state.
Returns
-------
engine : Sobol
Engine reset to its base state.
"""
super().reset()
self._quasi = self._shift.copy()
return self
def fast_forward(self, n: IntNumber) -> "Sobol":
"""Fast-forward the sequence by `n` positions.
Parameters
----------
n : int
Number of points to skip in the sequence.
Returns
-------
engine : Sobol
The fast-forwarded engine.
"""
if self.num_generated == 0:
_fast_forward(
n=n - 1, num_gen=self.num_generated, dim=self.d,
sv=self._sv, quasi=self._quasi
)
else:
_fast_forward(
n=n, num_gen=self.num_generated - 1, dim=self.d,
sv=self._sv, quasi=self._quasi
)
self.num_generated += n
return self
| Sobol |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modular_deepseek_v3.py | {
"start": 1083,
"end": 3279
} | class ____(Qwen2MoeMLP):
pass
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
r"""
TODO let's just use the original freqcis computation to not have the view
transpose + reshape! This is not optimized!
Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`):
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
used to pass offsetted position ids when working with a KV-cache.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
b, h, s, d = q.shape
q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
b, h, s, d = k.shape
k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def yarn_get_mscale(scale=1, mscale=1):
if scale <= 1:
return 1.0
return 0.1 * mscale * math.log(scale) + 1.0
| DeepseekV3MLP |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/default_types.py | {
"start": 12282,
"end": 17570
} | class ____(trace.TraceType, serialization.Serializable):
"""Represents a NamedTuple of TraceType objects."""
def __init__(self,
type_name: str,
attribute_names: PythonTuple[str],
attributes: PythonTuple[trace.TraceType],
placeholder_type: Optional[Type[Any]] = None):
self.type_name = type_name
self.attribute_names = attribute_names
self.attributes = Tuple(*attributes)
self._placeholder_type = placeholder_type
@classmethod
def from_type_and_attributes(
cls, named_tuple_type: Any,
attributes: PythonTuple[trace.TraceType]) -> "NamedTuple":
return NamedTuple(named_tuple_type.__name__, named_tuple_type._fields,
attributes, named_tuple_type)
def is_subtype_of(self, other: trace.TraceType) -> bool:
if not isinstance(other, NamedTuple):
return False
return (self.type_name == other.type_name and
self.attribute_names == other.attribute_names and
self.attributes.is_subtype_of(other.attributes))
def most_specific_common_supertype(
self, others: Sequence[trace.TraceType]) -> Optional["NamedTuple"]:
"""See base class."""
if not all(
isinstance(other, NamedTuple) and self.type_name == other.type_name and
self.attribute_names == other.attribute_names for other in others):
return None
supertyped_attributes = self.attributes.most_specific_common_supertype(
[other.attributes for other in others])
if supertyped_attributes is None:
return None
return NamedTuple(self.type_name, self.attribute_names,
supertyped_attributes.components, self._placeholder_type)
@classmethod
def experimental_type_proto(
cls) -> Type[default_types_pb2.SerializedNamedTuple]:
return default_types_pb2.SerializedNamedTuple
@classmethod
def experimental_from_proto(
cls, proto: default_types_pb2.SerializedNamedTuple) -> "NamedTuple":
return NamedTuple(
proto.type_name, tuple(proto.attribute_names),
Tuple.experimental_from_proto(proto.attributes).components)
def experimental_as_proto(self) -> default_types_pb2.SerializedNamedTuple:
return default_types_pb2.SerializedNamedTuple(
type_name=self.type_name,
attribute_names=list(self.attribute_names),
attributes=self.attributes.experimental_as_proto())
def placeholder_value(self, placeholder_context) -> Any:
if self._placeholder_type is None:
# We don't need to trace after serialization so it is not needed but we
# can generate a placeholder type using the description if ever needed.
raise ValueError("Can not generate placeholder value for NamedTuple with"
" unspecified placeholder_type. Note: placeholder_type "
"is lost during serialization.")
attribute_placeholders = [
attribute.placeholder_value(placeholder_context)
for attribute in self.attributes.components
]
return self._placeholder_type(*attribute_placeholders)
def to_tensors(self, value: Any):
assert util.is_namedtuple(value)
flattened_values = []
for attribute_name, attribute_type in zip(
self.attribute_names, self.attributes.components):
attribute_value = getattr(value, attribute_name)
flattened_values.extend(attribute_type.to_tensors(attribute_value))
return flattened_values
def from_tensors(self, tensors) -> Any:
if self._placeholder_type is None:
raise ValueError("Packing serialized NamedTuples is not supported.")
return self._placeholder_type(
*[c.from_tensors(tensors) for c in self.attributes.components]
)
def flatten(self) -> PythonList[trace.TraceType]:
flattened_types = []
for component in self.attributes.components:
flattened_types.extend(component.flatten())
return flattened_types
def cast(self, value: Any, casting_context) -> Any:
# Value must have same attributes with the TraceType
assert util.is_namedtuple(
value
), f"Cannot cast {value!r} to type {self._placeholder_type!r}."
value_dict = value._asdict()
assert set(value_dict.keys()) == set(
self.attribute_names
), f"{value!r} has different attributes with the TraceType {self!r}"
casted_values, was_casted = util.cast_and_return_whether_casted(
self.attributes.components,
[getattr(value, name) for name in self.attribute_names],
casting_context,
)
if was_casted:
return self._placeholder_type(*casted_values)
else:
return value
def __hash__(self) -> int:
return hash((self.type_name, self.attribute_names, self.attributes))
def __eq__(self, other: Any) -> bool:
if not isinstance(other, trace.TraceType):
return NotImplemented
if not isinstance(other, NamedTuple):
return False
return (self.type_name == other.type_name and
self.attribute_names == other.attribute_names and
self.attributes == other.attributes)
def __repr__(self) -> str:
paired = [
f"[{n!r}, {c!r}]"
for n, c in zip(self.attribute_names, self.attributes.components)
]
return f"{self.type_name}[{', '.join(paired)}]"
| NamedTuple |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol32.py | {
"start": 392,
"end": 492
} | class ____(Base2[Value], Protocol[Arg, Value]):
def another(self, arg: Arg) -> None: ...
| Interface |
python | pydata__xarray | xarray/core/_aggregations.py | {
"start": 235067,
"end": 285932
} | class ____:
_obj: DataArray
def reduce(
self,
func: Callable[..., Any],
dim: Dims = None,
*,
axis: int | Sequence[int] | None = None,
keep_attrs: bool | None = None,
keepdims: bool = False,
**kwargs: Any,
) -> DataArray:
raise NotImplementedError()
def _flox_reduce(
self,
dim: Dims,
**kwargs: Any,
) -> DataArray:
raise NotImplementedError()
def count(
self,
dim: Dims = None,
*,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``count`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``count``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``count`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``count`` applied to its data and the
indicated dimension(s) removed
See Also
--------
pandas.DataFrame.count
dask.dataframe.DataFrame.count
DataArray.count
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").count()
<xarray.DataArray (labels: 3)> Size: 24B
array([1, 2, 2])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="count",
dim=dim,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.count,
dim=dim,
keep_attrs=keep_attrs,
**kwargs,
)
def all(
self,
dim: Dims = None,
*,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``all`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``all``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``all`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``all`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.all
dask.array.all
DataArray.all
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([True, True, True, True, True, False], dtype=bool),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 6B
array([ True, True, True, True, True, False])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").all()
<xarray.DataArray (labels: 3)> Size: 3B
array([False, True, True])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="all",
dim=dim,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.array_all,
dim=dim,
keep_attrs=keep_attrs,
**kwargs,
)
def any(
self,
dim: Dims = None,
*,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``any`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``any``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``any`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``any`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.any
dask.array.any
DataArray.any
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([True, True, True, True, True, False], dtype=bool),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 6B
array([ True, True, True, True, True, False])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").any()
<xarray.DataArray (labels: 3)> Size: 3B
array([ True, True, True])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="any",
dim=dim,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.array_any,
dim=dim,
keep_attrs=keep_attrs,
**kwargs,
)
def max(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``max`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``max``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``max`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``max`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.max
dask.array.max
DataArray.max
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").max()
<xarray.DataArray (labels: 3)> Size: 24B
array([1., 2., 3.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").max(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 2., 3.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="max",
dim=dim,
skipna=skipna,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.max,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
def min(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``min`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``min``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``min`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``min`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.min
dask.array.min
DataArray.min
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").min()
<xarray.DataArray (labels: 3)> Size: 24B
array([1., 2., 0.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").min(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 2., 0.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="min",
dim=dim,
skipna=skipna,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.min,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
def mean(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``mean`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``mean``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``mean`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``mean`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.mean
dask.array.mean
DataArray.mean
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").mean()
<xarray.DataArray (labels: 3)> Size: 24B
array([1. , 2. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").mean(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 2. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="mean",
dim=dim,
skipna=skipna,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.mean,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
def prod(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
min_count: int | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``prod`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``prod``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
min_count : int or None, optional
The required number of valid values to perform the operation. If
fewer than min_count non-NA values are present the result will be
NA. Only used if skipna is set to True or defaults to True for the
array's dtype. Changed in version 0.17.0: if specified on an integer
array and skipna=True, the result will be a float array.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``prod`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``prod`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.prod
dask.array.prod
DataArray.prod
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").prod()
<xarray.DataArray (labels: 3)> Size: 24B
array([1., 4., 0.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").prod(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 4., 0.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Specify ``min_count`` for finer control over when NaNs are ignored.
>>> da.groupby("labels").prod(skipna=True, min_count=2)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 4., 0.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="prod",
dim=dim,
skipna=skipna,
min_count=min_count,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.prod,
dim=dim,
skipna=skipna,
min_count=min_count,
keep_attrs=keep_attrs,
**kwargs,
)
def sum(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
min_count: int | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``sum`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``sum``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
min_count : int or None, optional
The required number of valid values to perform the operation. If
fewer than min_count non-NA values are present the result will be
NA. Only used if skipna is set to True or defaults to True for the
array's dtype. Changed in version 0.17.0: if specified on an integer
array and skipna=True, the result will be a float array.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``sum`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``sum`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.sum
dask.array.sum
DataArray.sum
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").sum()
<xarray.DataArray (labels: 3)> Size: 24B
array([1., 4., 3.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").sum(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 4., 3.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Specify ``min_count`` for finer control over when NaNs are ignored.
>>> da.groupby("labels").sum(skipna=True, min_count=2)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 4., 3.])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="sum",
dim=dim,
skipna=skipna,
min_count=min_count,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.sum,
dim=dim,
skipna=skipna,
min_count=min_count,
keep_attrs=keep_attrs,
**kwargs,
)
def std(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
ddof: int = 0,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``std`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``std``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
ddof : int, default: 0
“Delta Degrees of Freedom”: the divisor used in the calculation is ``N - ddof``,
where ``N`` represents the number of elements.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``std`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``std`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.std
dask.array.std
DataArray.std
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").std()
<xarray.DataArray (labels: 3)> Size: 24B
array([0. , 0. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").std(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 0. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Specify ``ddof=1`` for an unbiased estimate.
>>> da.groupby("labels").std(skipna=True, ddof=1)
<xarray.DataArray (labels: 3)> Size: 24B
array([ nan, 0. , 2.12132034])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="std",
dim=dim,
skipna=skipna,
ddof=ddof,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.std,
dim=dim,
skipna=skipna,
ddof=ddof,
keep_attrs=keep_attrs,
**kwargs,
)
def var(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
ddof: int = 0,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``var`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``var``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
ddof : int, default: 0
“Delta Degrees of Freedom”: the divisor used in the calculation is ``N - ddof``,
where ``N`` represents the number of elements.
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``var`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``var`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.var
dask.array.var
DataArray.var
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").var()
<xarray.DataArray (labels: 3)> Size: 24B
array([0. , 0. , 2.25])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").var(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([ nan, 0. , 2.25])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Specify ``ddof=1`` for an unbiased estimate.
>>> da.groupby("labels").var(skipna=True, ddof=1)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 0. , 4.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
if (
flox_available
and OPTIONS["use_flox"]
and contains_only_chunked_or_numpy(self._obj)
):
return self._flox_reduce(
func="var",
dim=dim,
skipna=skipna,
ddof=ddof,
# fill_value=fill_value,
keep_attrs=keep_attrs,
**kwargs,
)
else:
return self.reduce(
duck_array_ops.var,
dim=dim,
skipna=skipna,
ddof=ddof,
keep_attrs=keep_attrs,
**kwargs,
)
def median(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``median`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``median``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``median`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``median`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.median
dask.array.median
DataArray.median
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").median()
<xarray.DataArray (labels: 3)> Size: 24B
array([1. , 2. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").median(skipna=False)
<xarray.DataArray (labels: 3)> Size: 24B
array([nan, 2. , 1.5])
Coordinates:
* labels (labels) object 24B 'a' 'b' 'c'
"""
return self.reduce(
duck_array_ops.median,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
def cumsum(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``cumsum`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``cumsum``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``cumsum`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``cumsum`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.cumsum
dask.array.cumsum
DataArray.cumsum
DataArray.cumulative
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Note that the methods on the ``cumulative`` method are more performant (with numbagg installed)
and better supported. ``cumsum`` and ``cumprod`` may be deprecated
in the future.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").cumsum()
<xarray.DataArray (time: 6)> Size: 48B
array([1., 2., 3., 3., 4., 1.])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").cumsum(skipna=False)
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 3., 4., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
"""
return self.reduce(
duck_array_ops.cumsum,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
def cumprod(
self,
dim: Dims = None,
*,
skipna: bool | None = None,
keep_attrs: bool | None = None,
**kwargs: Any,
) -> DataArray:
"""
Reduce this DataArray's data by applying ``cumprod`` along some dimension(s).
Parameters
----------
dim : str, Iterable of Hashable, "..." or None, default: None
Name of dimension[s] along which to apply ``cumprod``. For e.g. ``dim="x"``
or ``dim=["x", "y"]``. If None, will reduce over the GroupBy dimensions.
If "...", will reduce over all dimensions.
skipna : bool or None, optional
If True, skip missing values (as marked by NaN). By default, only
skips missing values for float dtypes; other dtypes either do not
have a sentinel missing value (int) or ``skipna=True`` has not been
implemented (object, datetime64 or timedelta64).
keep_attrs : bool or None, optional
If True, ``attrs`` will be copied from the original
object to the new one. If False, the new object will be
returned without attributes.
**kwargs : Any
Additional keyword arguments passed on to the appropriate array
function for calculating ``cumprod`` on this object's data.
These could include dask-specific kwargs like ``split_every``.
Returns
-------
reduced : DataArray
New DataArray with ``cumprod`` applied to its data and the
indicated dimension(s) removed
See Also
--------
numpy.cumprod
dask.array.cumprod
DataArray.cumprod
DataArray.cumulative
:ref:`groupby`
User guide on groupby operations.
Notes
-----
Use the ``flox`` package to significantly speed up groupby computations,
especially with dask arrays. Xarray will use flox by default if installed.
Pass flox-specific keyword arguments in ``**kwargs``.
See the `flox documentation <https://flox.readthedocs.io>`_ for more.
Non-numeric variables will be removed prior to reducing.
Note that the methods on the ``cumulative`` method are more performant (with numbagg installed)
and better supported. ``cumsum`` and ``cumprod`` may be deprecated
in the future.
Examples
--------
>>> da = xr.DataArray(
... np.array([1, 2, 3, 0, 2, np.nan]),
... dims="time",
... coords=dict(
... time=("time", pd.date_range("2001-01-01", freq="ME", periods=6)),
... labels=("time", np.array(["a", "b", "c", "c", "b", "a"])),
... ),
... )
>>> da
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 2., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
>>> da.groupby("labels").cumprod()
<xarray.DataArray (time: 6)> Size: 48B
array([1., 2., 3., 0., 4., 1.])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
Use ``skipna`` to control whether NaNs are ignored.
>>> da.groupby("labels").cumprod(skipna=False)
<xarray.DataArray (time: 6)> Size: 48B
array([ 1., 2., 3., 0., 4., nan])
Coordinates:
* time (time) datetime64[ns] 48B 2001-01-31 2001-02-28 ... 2001-06-30
labels (time) <U1 24B 'a' 'b' 'c' 'c' 'b' 'a'
"""
return self.reduce(
duck_array_ops.cumprod,
dim=dim,
skipna=skipna,
keep_attrs=keep_attrs,
**kwargs,
)
| DataArrayGroupByAggregations |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 34095,
"end": 34451
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("it_IT")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in ItItProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in ItItProvider.MONTH_NAMES.values()
| TestItIt |
python | django__django | tests/i18n/test_extraction.py | {
"start": 38435,
"end": 41427
} | class ____(ExtractorTests):
def test_no_location_enabled(self):
"""
Behavior is correct if --no-location switch is specified. See #16903.
"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_location=True
)
self.assertTrue(os.path.exists(self.PO_FILE))
self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html")
def test_no_location_disabled(self):
"""Behavior is correct if --no-location switch isn't specified."""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_location=False
)
self.assertTrue(os.path.exists(self.PO_FILE))
# #16903 -- Standard comment with source file relative path should be
# present
self.assertLocationCommentPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
def test_location_comments_for_templatized_files(self):
"""
Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123
Refs #21209/#26341.
"""
management.call_command("makemessages", locale=[LOCALE], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE) as fp:
po_contents = fp.read()
self.assertMsgId("#: templates/test.html.py", po_contents)
self.assertLocationCommentNotPresent(self.PO_FILE, None, ".html.py")
self.assertLocationCommentPresent(self.PO_FILE, 5, "templates", "test.html")
def test_add_location_full(self):
"""makemessages --add-location=full"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="full"
)
self.assertTrue(os.path.exists(self.PO_FILE))
# Comment with source file relative path and line number is present.
self.assertLocationCommentPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
def test_add_location_file(self):
"""makemessages --add-location=file"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="file"
)
self.assertTrue(os.path.exists(self.PO_FILE))
# Comment with source file relative path is present.
self.assertLocationCommentPresent(self.PO_FILE, None, "templates", "test.html")
# But it should not contain the line number.
self.assertLocationCommentNotPresent(
self.PO_FILE, "Translatable literal #6b", "templates", "test.html"
)
def test_add_location_never(self):
"""makemessages --add-location=never"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="never"
)
self.assertTrue(os.path.exists(self.PO_FILE))
self.assertLocationCommentNotPresent(self.PO_FILE, None, "test.html")
| LocationCommentsTests |
python | simplejson__simplejson | simplejson/tests/test_raw_json.py | {
"start": 262,
"end": 1062
} | class ____(unittest.TestCase):
def test_normal_str(self):
self.assertNotEqual(json.dumps(dct2), json.dumps(dct3))
def test_raw_json_str(self):
self.assertEqual(json.dumps(dct2), json.dumps(dct4))
self.assertEqual(dct2, json.loads(json.dumps(dct4)))
def test_list(self):
self.assertEqual(
json.dumps([dct2]),
json.dumps([json.RawJSON(json.dumps(dct2))]))
self.assertEqual(
[dct2],
json.loads(json.dumps([json.RawJSON(json.dumps(dct2))])))
def test_direct(self):
self.assertEqual(
json.dumps(dct2),
json.dumps(json.RawJSON(json.dumps(dct2))))
self.assertEqual(
dct2,
json.loads(json.dumps(json.RawJSON(json.dumps(dct2)))))
| TestRawJson |
python | huggingface__transformers | src/transformers/models/data2vec/configuration_data2vec_vision.py | {
"start": 805,
"end": 8671
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Data2VecVisionModel`]. It is used to instantiate
an Data2VecVision model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar configuration to that of the Data2VecVision
[facebook/data2vec-vision-base](https://huggingface.co/facebook/data2vec-vision-base) architecture.
Args:
hidden_size (`int`, *optional*, defaults to 768):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 12):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 12):
Number of attention heads for each attention layer in the Transformer encoder.
intermediate_size (`int`, *optional*, defaults to 3072):
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"` and `"gelu_new"` are supported.
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
The epsilon used by the layer normalization layers.
image_size (`int`, *optional*, defaults to 224):
The size (resolution) of each image.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
use_mask_token (`bool`, *optional*, defaults to `False`):
Whether to use a mask token for masked image modeling.
use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
Whether to use BERT-style absolute position embeddings.
use_relative_position_bias (`bool`, *optional*, defaults to `False`):
Whether to use T5-style relative position embeddings in the self-attention layers.
use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
layer_scale_init_value (`float`, *optional*, defaults to 0.1):
Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
drop_path_rate (`float`, *optional*, defaults to 0.1):
Stochastic depth rate per sample (when applied in the main path of residual layers).
use_mean_pooling (`bool`, *optional*, defaults to `True`):
Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
CLS token, before applying the classification head.
out_indices (`list[int]`, *optional*, defaults to `[3, 5, 7, 11]`):
Indices of the feature maps to use for semantic segmentation.
pool_scales (`tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
Pooling scales used in Pooling Pyramid Module applied on the last feature map.
use_auxiliary_head (`bool`, *optional*, defaults to `True`):
Whether to use an auxiliary head during training.
auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
Weight of the cross-entropy loss of the auxiliary head.
auxiliary_channels (`int`, *optional*, defaults to 256):
Number of channels to use in the auxiliary head.
auxiliary_num_convs (`int`, *optional*, defaults to 1):
Number of convolutional layers to use in the auxiliary head.
auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
Whether to concatenate the output of the auxiliary head with the input before the classification layer.
semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
The index that is ignored by the loss function of the semantic segmentation model.
Example:
```python
>>> from transformers import Data2VecVisionConfig, Data2VecVisionModel
>>> # Initializing a Data2VecVision data2vec_vision-base-patch16-224-in22k style configuration
>>> configuration = Data2VecVisionConfig()
>>> # Initializing a model (with random weights) from the data2vec_vision-base-patch16-224-in22k style configuration
>>> model = Data2VecVisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "data2vec-vision"
def __init__(
self,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.0,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
layer_norm_eps=1e-12,
image_size=224,
patch_size=16,
num_channels=3,
use_mask_token=False,
use_absolute_position_embeddings=False,
use_relative_position_bias=False,
use_shared_relative_position_bias=False,
layer_scale_init_value=0.1,
drop_path_rate=0.1,
use_mean_pooling=True,
out_indices=[3, 5, 7, 11],
pool_scales=[1, 2, 3, 6],
use_auxiliary_head=True,
auxiliary_loss_weight=0.4,
auxiliary_channels=256,
auxiliary_num_convs=1,
auxiliary_concat_input=False,
semantic_loss_ignore_index=255,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.initializer_range = initializer_range
self.layer_norm_eps = layer_norm_eps
self.image_size = image_size
self.patch_size = patch_size
self.num_channels = num_channels
self.use_mask_token = use_mask_token
self.use_absolute_position_embeddings = use_absolute_position_embeddings
self.use_relative_position_bias = use_relative_position_bias
self.use_shared_relative_position_bias = use_shared_relative_position_bias
self.layer_scale_init_value = layer_scale_init_value
self.drop_path_rate = drop_path_rate
self.use_mean_pooling = use_mean_pooling
# decode head attributes (semantic segmentation)
self.out_indices = out_indices
self.pool_scales = pool_scales
# auxiliary head attributes (semantic segmentation)
self.use_auxiliary_head = use_auxiliary_head
self.auxiliary_loss_weight = auxiliary_loss_weight
self.auxiliary_channels = auxiliary_channels
self.auxiliary_num_convs = auxiliary_num_convs
self.auxiliary_concat_input = auxiliary_concat_input
self.semantic_loss_ignore_index = semantic_loss_ignore_index
__all__ = ["Data2VecVisionConfig"]
| Data2VecVisionConfig |
python | Textualize__textual | docs/examples/widgets/list_view.py | {
"start": 107,
"end": 446
} | class ____(App):
CSS_PATH = "list_view.tcss"
def compose(self) -> ComposeResult:
yield ListView(
ListItem(Label("One")),
ListItem(Label("Two")),
ListItem(Label("Three")),
)
yield Footer()
if __name__ == "__main__":
app = ListViewExample()
app.run()
| ListViewExample |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_math_ops_test.py | {
"start": 27693,
"end": 28979
} | class ____(
parameterized.TestCase, test_util.TensorFlowTestCase):
@parameterized.parameters(
itertools.product(
allowed_var_op_input_combinations,
("assign", "assign_add", "assign_sub")))
def testAllowedDtypes(self, v_dtype_and_delta, op):
v_dtype, delta = v_dtype_and_delta
if isinstance(delta, dtypes.DType):
delta = constant_op.constant(1, delta)
elif isinstance(delta, str):
delta = _weak_tensor_from_str(delta)
var = resource_variable_ops.ResourceVariable(10, dtype=v_dtype)
result = getattr(var, op)(delta)
with test_util.device(use_gpu=True):
self.assertEqual(result.dtype, v_dtype)
@parameterized.parameters(
itertools.product(
disallowed_var_op_input_combinations,
("assign", "assign_add", "assign_sub")))
def testDisallowedDtypes(self, v_dtype_and_delta, op):
v_dtype, delta = v_dtype_and_delta
if isinstance(delta, dtypes.DType):
delta = constant_op.constant(1, delta)
elif isinstance(delta, str):
delta = _weak_tensor_from_str(delta)
var = resource_variable_ops.ResourceVariable(10, dtype=v_dtype)
with self.assertRaises(TypeError):
_ = getattr(var, op)(delta)
@test_util.run_all_in_graph_and_eager_modes
| VariableInplaceOpsTest |
python | walkccc__LeetCode | solutions/866. Prime Palindrome/866.py | {
"start": 0,
"end": 687
} | class ____:
def primePalindrome(self, n: int) -> int:
def getPalindromes(n: int) -> int:
length = n // 2
for i in range(10**(length - 1), 10**length):
s = str(i)
for j in range(10):
yield int(s + str(j) + s[::-1])
def isPrime(num: int) -> bool:
return not any(num % i == 0 for i in range(2, int(num**0.5 + 1)))
if n <= 2:
return 2
if n == 3:
return 3
if n <= 5:
return 5
if n <= 7:
return 7
if n <= 11:
return 11
nLength = len(str(n))
while True:
for num in getPalindromes(nLength):
if num >= n and isPrime(num):
return num
nLength += 1
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 53002,
"end": 53647
} | class ____(sgqlc.types.Enum):
"""The possible values for the members can create repositories
setting on an organization.
Enumeration Choices:
* `ALL`: Members will be able to create public and private
repositories.
* `DISABLED`: Members will not be able to create public or private
repositories.
* `INTERNAL`: Members will be able to create only internal
repositories.
* `PRIVATE`: Members will be able to create only private
repositories.
"""
__schema__ = github_schema
__choices__ = ("ALL", "DISABLED", "INTERNAL", "PRIVATE")
| OrganizationMembersCanCreateRepositoriesSettingValue |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 2239,
"end": 2584
} | class ____(BaseEvent):
"""Event emitted when an attachment is skipped."""
page_id: str
attachment_id: str
attachment_name: str
attachment_type: str
attachment_size: int
attachment_link: str
reason: str
@classmethod
def class_name(cls) -> str:
return "AttachmentSkippedEvent"
| AttachmentSkippedEvent |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 14947,
"end": 22637
} | class ____:
"""Some very basic tests."""
def test_table_rows(self, city_data: PrettyTable) -> None:
rows = city_data.rows
assert len(rows) == 7
assert rows[0] == CITY_DATA[0]
def test_add_rows(self, city_data: PrettyTable) -> None:
"""A table created with multiple add_row calls is the same as one created
with a single add_rows
"""
table = PrettyTable(CITY_DATA_HEADER)
table.add_rows(CITY_DATA)
assert str(city_data) == str(table)
table.add_rows([])
assert str(city_data) == str(table)
def _test_no_blank_lines(self, table: PrettyTable) -> None:
string = table.get_string()
lines = string.split("\n")
assert "" not in lines
def _test_all_length_equal(self, table: PrettyTable) -> None:
string = table.get_string()
lines = string.split("\n")
lengths = {len(line) for line in lines}
assert len(lengths) == 1
def test_no_blank_lines(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
self._test_no_blank_lines(city_data)
def test_all_lengths_equal(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_title(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.title = "My table"
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_title(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.title = "My table"
self._test_all_length_equal(city_data)
def test_all_lengths_equal_with_long_title(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length, even with a long title."""
city_data.title = "My table (75 characters wide) " + "=" * 45
self._test_all_length_equal(city_data)
def test_no_blank_lines_without_border(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.border = False
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_without_border(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.border = False
self._test_all_length_equal(city_data)
def test_no_blank_lines_without_header(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.header = False
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_without_header(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.header = False
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_hrules_none(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.hrules = HRuleStyle.NONE
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_hrules_none(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.hrules = HRuleStyle.NONE
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_hrules_all(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.hrules = HRuleStyle.ALL
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_hrules_all(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.hrules = HRuleStyle.ALL
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_style_msword(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.set_style(TableStyle.MSWORD_FRIENDLY)
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_style_msword(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.set_style(TableStyle.MSWORD_FRIENDLY)
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_int_format(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.int_format = "04"
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_int_format(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.int_format = "04"
self._test_all_length_equal(city_data)
def test_no_blank_lines_with_float_format(self, city_data: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
city_data.float_format = "6.2f"
self._test_no_blank_lines(city_data)
def test_all_lengths_equal_with_float_format(self, city_data: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
city_data.float_format = "6.2f"
self._test_all_length_equal(city_data)
def test_no_blank_lines_from_csv(self, city_data_from_csv: PrettyTable) -> None:
"""No table should ever have blank lines in it."""
self._test_no_blank_lines(city_data_from_csv)
def test_all_lengths_equal_from_csv(self, city_data_from_csv: PrettyTable) -> None:
"""All lines in a table should be of the same length."""
self._test_all_length_equal(city_data_from_csv)
def test_no_blank_lines_from_mediawiki(
self, city_data_from_mediawiki: PrettyTable
) -> None:
"""No table should ever have blank lines in it."""
self._test_no_blank_lines(city_data_from_mediawiki)
def test_all_lengths_equal_from_mediawiki(
self, city_data_from_mediawiki: PrettyTable
) -> None:
"""All lines in a table should be of the same length."""
self._test_all_length_equal(city_data_from_mediawiki)
def test_rowcount(self, city_data: PrettyTable) -> None:
assert city_data.rowcount == 7
def test_colcount(self, city_data: PrettyTable) -> None:
assert city_data.colcount == 4
def test_getitem(self, city_data: PrettyTable) -> None:
assert (
city_data[1].get_string()
== """+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Brisbane | 5905 | 1857594 | 1146.4 |
+-----------+------+------------+-----------------+"""
)
def test_invalid_getitem(self, city_data: PrettyTable) -> None:
with pytest.raises(IndexError):
assert city_data[10]
@pytest.mark.usefixtures("init_db")
def test_no_blank_lines_from_db(self, db_cursor: sqlite3.Cursor) -> None:
"""No table should ever have blank lines in it."""
db_cursor.execute("SELECT * FROM cities")
table = from_db_cursor(db_cursor)
assert table is not None
self._test_no_blank_lines(table)
@pytest.mark.usefixtures("init_db")
def test_all_lengths_equal_from_db(self, db_cursor: sqlite3.Cursor) -> None:
"""No table should ever have blank lines in it."""
db_cursor.execute("SELECT * FROM cities")
table = from_db_cursor(db_cursor)
assert table is not None
self._test_all_length_equal(table)
| TestBasic |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 143547,
"end": 144653
} | class ____(multi_rv_frozen):
__class_getitem__ = None
def __init__(self, dim=None, seed=None):
"""Create a frozen SO(N) distribution.
Parameters
----------
dim : scalar
Dimension of matrices
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
If `seed` is None (or `np.random`), the `numpy.random.RandomState`
singleton is used.
If `seed` is an int, a new ``RandomState`` instance is used,
seeded with `seed`.
If `seed` is already a ``Generator`` or ``RandomState`` instance
then that instance is used.
Examples
--------
>>> from scipy.stats import special_ortho_group
>>> g = special_ortho_group(5)
>>> x = g.rvs()
""" # numpy/numpydoc#87 # noqa: E501
self._dist = special_ortho_group_gen(seed)
self.dim = self._dist._process_parameters(dim)
def rvs(self, size=1, random_state=None):
return self._dist.rvs(self.dim, size, random_state)
| special_ortho_group_frozen |
python | great-expectations__great_expectations | great_expectations/metrics/column/sample_values.py | {
"start": 152,
"end": 215
} | class ____(MetricResult[list[Any]]): ...
| ColumnSampleValuesResult |
python | django__django | django/contrib/sites/middleware.py | {
"start": 96,
"end": 309
} | class ____(MiddlewareMixin):
"""
Middleware that sets `site` attribute to request object.
"""
def process_request(self, request):
request.site = get_current_site(request)
| CurrentSiteMiddleware |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/config/models.py | {
"start": 2400,
"end": 2660
} | class ____(BaseModel, extra="forbid"):
locations: list[Location] = Field(description="List of code locations")
def load_dagster_cloud_yaml(text) -> DagsterCloudYaml:
return DagsterCloudYaml.model_validate(yaml.safe_load(text))
| ProcessedDagsterCloudConfig |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 14962,
"end": 15033
} | class ____(scale_color_gradient2):
pass
@alias
| scale_colour_gradient2 |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 937,
"end": 1026
} | class ____(BaseModel):
type: Literal["refusal.done"]
refusal: str
| RefusalDoneEvent |
python | numba__numba | numba/cuda/tests/nocuda/test_dummyarray.py | {
"start": 6201,
"end": 10761
} | class ____(unittest.TestCase):
def test_reshape_2d2d(self):
nparr = np.empty((4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(5, 4)
got = arr.reshape(5, 4)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_2d1d(self):
nparr = np.empty((4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(5 * 4)
got = arr.reshape(5 * 4)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_3d3d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(5, 3, 4)
got = arr.reshape(5, 3, 4)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_3d2d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(3 * 4, 5)
got = arr.reshape(3 * 4, 5)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_3d1d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(3 * 4 * 5)
got = arr.reshape(3 * 4 * 5)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer2d2d(self):
nparr = np.empty((4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(-1, 4)
got = arr.reshape(-1, 4)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer2d1d(self):
nparr = np.empty((4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(-1)
got = arr.reshape(-1)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer3d3d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(5, -1, 4)
got = arr.reshape(5, -1, 4)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer3d2d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(3, -1)
got = arr.reshape(3, -1)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer3d1d(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(-1)
got = arr.reshape(-1)[0]
self.assertEqual(got.shape, expect.shape)
self.assertEqual(got.strides, expect.strides)
def test_reshape_infer_two_unknowns(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
with self.assertRaises(ValueError) as raises:
arr.reshape(-1, -1, 3)
self.assertIn('can only specify one unknown dimension',
str(raises.exception))
def test_reshape_infer_invalid_shape(self):
nparr = np.empty((3, 4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
with self.assertRaises(ValueError) as raises:
arr.reshape(-1, 7)
expected_message = 'cannot infer valid shape for unknown dimension'
self.assertIn(expected_message, str(raises.exception))
@skip_on_cudasim("Tests internals of the CUDA driver device array")
| TestReshape |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 683969,
"end": 713534
} | class ____(
FieldChannelMixin, core.FieldOrDatumDefWithConditionMarkPropFieldDefnumber
):
r"""
StrokeOpacity schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggregateOp`, Literal['average', 'count', 'distinct', 'max', 'mean', 'median', 'min', 'missing', 'product', 'q1', 'q3', 'ci0', 'ci1', 'stderr', 'stdev', 'stdevp', 'sum', 'valid', 'values', 'variance', 'variancep', 'exponential', 'exponentialb']
Aggregation function for the field (e.g., ``"mean"``, ``"sum"``, ``"median"``,
``"min"``, ``"max"``, ``"count"``).
**Default value:** ``undefined`` (None)
**See also:** `aggregate <https://vega.github.io/vega-lite/docs/aggregate.html>`__
documentation.
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
bin : bool, dict, :class:`BinParams`, None
A flag for binning a ``quantitative`` field, `an object defining binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__, or indicating
that the data for ``x`` or ``y`` channel are binned before they are imported into
Vega-Lite (``"binned"``).
* If ``true``, default `binning parameters
<https://vega.github.io/vega-lite/docs/bin.html#bin-parameters>`__ will be
applied.
* If ``"binned"``, this indicates that the data for the ``x`` (or ``y``) channel are
already binned. You can map the bin-start field to ``x`` (or ``y``) and the
bin-end field to ``x2`` (or ``y2``). The scale and axis will be formatted similar
to binning in Vega-Lite. To adjust the axis ticks based on the bin step, you can
also set the axis's `tickMinStep
<https://vega.github.io/vega-lite/docs/axis.html#ticks>`__ property.
**Default value:** ``false``
**See also:** `bin <https://vega.github.io/vega-lite/docs/bin.html>`__
documentation.
condition : dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalParameterValueDefnumberExprRef`, :class:`ConditionalPredicateValueDefnumberExprRef`, Sequence[dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalParameterValueDefnumberExprRef`, :class:`ConditionalPredicateValueDefnumberExprRef`]
One or more value definition(s) with `a parameter or a test predicate
<https://vega.github.io/vega-lite/docs/condition.html>`__.
**Note:** A field definition's ``condition`` property can only contain `conditional
value definitions <https://vega.github.io/vega-lite/docs/condition.html#value>`__
since Vega-Lite only allows at most one encoded field per encoding channel.
field : str, dict, :class:`Field`, :class:`FieldName`, :class:`RepeatRef`
**Required.** A string defining the name of the field from which to pull a data
value or an object defining iterated values from the `repeat
<https://vega.github.io/vega-lite/docs/repeat.html>`__ operator.
**See also:** `field <https://vega.github.io/vega-lite/docs/field.html>`__
documentation.
**Notes:** 1) Dots (``.``) and brackets (``[`` and ``]``) can be used to access
nested objects (e.g., ``"field": "foo.bar"`` and ``"field": "foo['bar']"``). If
field names contain dots or brackets but are not nested, you can use ``\\`` to
escape dots and brackets (e.g., ``"a\\.b"`` and ``"a\\[0\\]"``). See more details
about escaping in the `field documentation
<https://vega.github.io/vega-lite/docs/field.html>`__. 2) ``field`` is not required
if ``aggregate`` is ``count``.
legend : dict, :class:`Legend`, None
An object defining properties of the legend. If ``null``, the legend for the
encoding channel will be removed.
**Default value:** If undefined, default `legend properties
<https://vega.github.io/vega-lite/docs/legend.html>`__ are applied.
**See also:** `legend <https://vega.github.io/vega-lite/docs/legend.html>`__
documentation.
scale : dict, :class:`Scale`, None
An object defining properties of the channel's scale, which is the function that
transforms values in the data domain (numbers, dates, strings, etc) to visual values
(pixels, colors, sizes) of the encoding channels.
If ``null``, the scale will be `disabled and the data value will be directly encoded
<https://vega.github.io/vega-lite/docs/scale.html#disable>`__.
**Default value:** If undefined, default `scale properties
<https://vega.github.io/vega-lite/docs/scale.html>`__ are applied.
**See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__
documentation.
sort : dict, :class:`Sort`, Sequence[str], Sequence[bool], Sequence[float], :class:`SortArray`, :class:`SortOrder`, :class:`AllSortString`, :class:`SortByChannel`, :class:`SortByEncoding`, :class:`EncodingSortField`, :class:`SortByChannelDesc`, Sequence[dict, :class:`DateTime`], Literal['-x', '-y', '-color', '-fill', '-stroke', '-strokeWidth', '-size', '-shape', '-fillOpacity', '-strokeOpacity', '-opacity', '-text', 'ascending', 'descending', 'x', 'y', 'color', 'fill', 'stroke', 'strokeWidth', 'size', 'shape', 'fillOpacity', 'strokeOpacity', 'opacity', 'text'], None
Sort order for the encoded field.
For continuous fields (quantitative or temporal), ``sort`` can be either
``"ascending"`` or ``"descending"``.
For discrete fields, ``sort`` can be one of the following:
* ``"ascending"`` or ``"descending"`` -- for sorting by the values' natural order in
JavaScript.
* `A string indicating an encoding channel name to sort by
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__ (e.g.,
``"x"`` or ``"y"``) with an optional minus prefix for descending sort (e.g.,
``"-x"`` to sort by x-field, descending). This channel string is short-form of `a
sort-by-encoding definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-by-encoding>`__. For
example, ``"sort": "-x"`` is equivalent to ``"sort": {"encoding": "x", "order":
"descending"}``.
* `A sort field definition
<https://vega.github.io/vega-lite/docs/sort.html#sort-field>`__ for sorting by
another field.
* `An array specifying the field values in preferred order
<https://vega.github.io/vega-lite/docs/sort.html#sort-array>`__. In this case, the
sort order will obey the values in the array, followed by any unspecified values
in their original order. For discrete time field, values in the sort array can be
`date-time definition objects
<https://vega.github.io/vega-lite/docs/datetime.html>`__. In addition, for time
units ``"month"`` and ``"day"``, the values can be the month or day names (case
insensitive) or their 3-letter initials (e.g., ``"Mon"``, ``"Tue"``).
* ``null`` indicating no sort.
**Default value:** ``"ascending"``
**Note:** ``null`` and sorting by another channel is not supported for ``row`` and
``column``.
**See also:** `sort <https://vega.github.io/vega-lite/docs/sort.html>`__
documentation.
timeUnit : dict, :class:`TimeUnit`, :class:`MultiTimeUnit`, :class:`BinnedTimeUnit`, :class:`SingleTimeUnit`, :class:`TimeUnitParams`, :class:`UtcMultiTimeUnit`, :class:`UtcSingleTimeUnit`, :class:`LocalMultiTimeUnit`, :class:`LocalSingleTimeUnit`, Literal['binnedyear', 'binnedyearquarter', 'binnedyearquartermonth', 'binnedyearmonth', 'binnedyearmonthdate', 'binnedyearmonthdatehours', 'binnedyearmonthdatehoursminutes', 'binnedyearmonthdatehoursminutesseconds', 'binnedyearweek', 'binnedyearweekday', 'binnedyearweekdayhours', 'binnedyearweekdayhoursminutes', 'binnedyearweekdayhoursminutesseconds', 'binnedyeardayofyear', 'binnedutcyear', 'binnedutcyearquarter', 'binnedutcyearquartermonth', 'binnedutcyearmonth', 'binnedutcyearmonthdate', 'binnedutcyearmonthdatehours', 'binnedutcyearmonthdatehoursminutes', 'binnedutcyearmonthdatehoursminutesseconds', 'binnedutcyearweek', 'binnedutcyearweekday', 'binnedutcyearweekdayhours', 'binnedutcyearweekdayhoursminutes', 'binnedutcyearweekdayhoursminutesseconds', 'binnedutcyeardayofyear', 'utcyear', 'utcquarter', 'utcmonth', 'utcweek', 'utcday', 'utcdayofyear', 'utcdate', 'utchours', 'utcminutes', 'utcseconds', 'utcmilliseconds', 'year', 'quarter', 'month', 'week', 'day', 'dayofyear', 'date', 'hours', 'minutes', 'seconds', 'milliseconds', 'utcyearquarter', 'utcyearquartermonth', 'utcyearmonth', 'utcyearmonthdate', 'utcyearmonthdatehours', 'utcyearmonthdatehoursminutes', 'utcyearmonthdatehoursminutesseconds', 'utcyearweek', 'utcyearweekday', 'utcyearweekdayhours', 'utcyearweekdayhoursminutes', 'utcyearweekdayhoursminutesseconds', 'utcyeardayofyear', 'utcquartermonth', 'utcmonthdate', 'utcmonthdatehours', 'utcmonthdatehoursminutes', 'utcmonthdatehoursminutesseconds', 'utcweekday', 'utcweekdayhours', 'utcweekdayhoursminutes', 'utcweekdayhoursminutesseconds', 'utcdayhours', 'utcdayhoursminutes', 'utcdayhoursminutesseconds', 'utchoursminutes', 'utchoursminutesseconds', 'utcminutesseconds', 'utcsecondsmilliseconds', 'yearquarter', 'yearquartermonth', 'yearmonth', 'yearmonthdate', 'yearmonthdatehours', 'yearmonthdatehoursminutes', 'yearmonthdatehoursminutesseconds', 'yearweek', 'yearweekday', 'yearweekdayhours', 'yearweekdayhoursminutes', 'yearweekdayhoursminutesseconds', 'yeardayofyear', 'quartermonth', 'monthdate', 'monthdatehours', 'monthdatehoursminutes', 'monthdatehoursminutesseconds', 'weekday', 'weekdayhours', 'weekdayhoursminutes', 'weekdayhoursminutesseconds', 'dayhours', 'dayhoursminutes', 'dayhoursminutesseconds', 'hoursminutes', 'hoursminutesseconds', 'minutesseconds', 'secondsmilliseconds']
Time unit (e.g., ``year``, ``yearmonth``, ``month``, ``hours``) for a temporal
field. or `a temporal field that gets casted as ordinal
<https://vega.github.io/vega-lite/docs/type.html#cast>`__.
**Default value:** ``undefined`` (None)
**See also:** `timeUnit <https://vega.github.io/vega-lite/docs/timeunit.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`StandardType`, Literal['quantitative', 'ordinal', 'temporal', 'nominal']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "strokeOpacity"
@overload
def aggregate(self, _: NonArgAggregateOp_T, /) -> StrokeOpacity: ...
@overload
def aggregate(
self, *, argmax: Optional[str | SchemaBase] = Undefined
) -> StrokeOpacity: ...
@overload
def aggregate(
self, *, argmin: Optional[str | SchemaBase] = Undefined
) -> StrokeOpacity: ...
@overload
def bandPosition(self, _: float, /) -> StrokeOpacity: ...
@overload
def bin(self, _: bool | Bin | None, /) -> StrokeOpacity: ...
@overload
def bin(
self,
*,
anchor: Optional[float] = Undefined,
base: Optional[float] = Undefined,
binned: Optional[bool] = Undefined,
divide: Optional[Sequence[float]] = Undefined,
extent: Optional[Parameter | SchemaBase | Sequence[float] | Map] = Undefined,
maxbins: Optional[float] = Undefined,
minstep: Optional[float] = Undefined,
nice: Optional[bool] = Undefined,
step: Optional[float] = Undefined,
steps: Optional[Sequence[float]] = Undefined,
) -> StrokeOpacity: ...
@overload
def condition(
self,
*,
test: Optional[str | SchemaBase | Map] = Undefined,
value: Optional[float | Parameter | SchemaBase | Map] = Undefined,
) -> StrokeOpacity: ...
@overload
def condition(
self,
*,
empty: Optional[bool] = Undefined,
param: Optional[str | SchemaBase] = Undefined,
value: Optional[float | Parameter | SchemaBase | Map] = Undefined,
) -> StrokeOpacity: ...
@overload
def condition(
self, _: list[core.ConditionalValueDefnumberExprRef], /
) -> StrokeOpacity: ...
@overload
def field(self, _: str | RepeatRef, /) -> StrokeOpacity: ...
@overload
def field(
self,
*,
repeat: Optional[Literal["row", "column", "repeat", "layer"]] = Undefined,
) -> StrokeOpacity: ...
@overload
def legend(self, _: Legend | None, /) -> StrokeOpacity: ...
@overload
def legend(
self,
*,
aria: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
clipHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
columnPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
columns: Optional[float | Parameter | SchemaBase | Map] = Undefined,
cornerRadius: Optional[float | Parameter | SchemaBase | Map] = Undefined,
description: Optional[str | Parameter | SchemaBase | Map] = Undefined,
direction: Optional[SchemaBase | Orientation_T] = Undefined,
fillColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
format: Optional[str | SchemaBase | Map] = Undefined,
formatType: Optional[str] = Undefined,
gradientLength: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientStrokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
gradientStrokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gradientThickness: Optional[float | Parameter | SchemaBase | Map] = Undefined,
gridAlign: Optional[Parameter | SchemaBase | Map | LayoutAlign_T] = Undefined,
labelAlign: Optional[Parameter | SchemaBase | Map | Align_T] = Undefined,
labelBaseline: Optional[
Parameter | SchemaBase | Map | TextBaseline_T
] = Undefined,
labelColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
labelExpr: Optional[str] = Undefined,
labelFont: Optional[str | Parameter | SchemaBase | Map] = Undefined,
labelFontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelFontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
labelFontWeight: Optional[
Parameter | SchemaBase | Map | FontWeight_T
] = Undefined,
labelLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelOverlap: Optional[
bool | Parameter | SchemaBase | Literal["greedy", "parity"] | Map
] = Undefined,
labelPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
labelSeparation: Optional[float | Parameter | SchemaBase | Map] = Undefined,
legendX: Optional[float | Parameter | SchemaBase | Map] = Undefined,
legendY: Optional[float | Parameter | SchemaBase | Map] = Undefined,
offset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
orient: Optional[SchemaBase | LegendOrient_T] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
rowPadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
strokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolDash: Optional[
Parameter | SchemaBase | Sequence[float] | Map
] = Undefined,
symbolDashOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolFillColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolOffset: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolStrokeColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
symbolStrokeWidth: Optional[float | Parameter | SchemaBase | Map] = Undefined,
symbolType: Optional[str | Parameter | SchemaBase | Map] = Undefined,
tickCount: Optional[
float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
tickMinStep: Optional[float | Parameter | SchemaBase | Map] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
titleAlign: Optional[Parameter | SchemaBase | Map | Align_T] = Undefined,
titleAnchor: Optional[Parameter | SchemaBase | Map | TitleAnchor_T] = Undefined,
titleBaseline: Optional[
Parameter | SchemaBase | Map | TextBaseline_T
] = Undefined,
titleColor: Optional[
str | Parameter | SchemaBase | Map | ColorName_T | None
] = Undefined,
titleFont: Optional[str | Parameter | SchemaBase | Map] = Undefined,
titleFontSize: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleFontStyle: Optional[str | Parameter | SchemaBase | Map] = Undefined,
titleFontWeight: Optional[
Parameter | SchemaBase | Map | FontWeight_T
] = Undefined,
titleLimit: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleLineHeight: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleOpacity: Optional[float | Parameter | SchemaBase | Map] = Undefined,
titleOrient: Optional[Parameter | SchemaBase | Map | Orient_T] = Undefined,
titlePadding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
type: Optional[Literal["symbol", "gradient"]] = Undefined,
values: Optional[
Parameter
| SchemaBase
| Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[Temporal | SchemaBase | Map]
| Map
] = Undefined,
zindex: Optional[float] = Undefined,
) -> StrokeOpacity: ...
@overload
def scale(self, _: Scale | None, /) -> StrokeOpacity: ...
@overload
def scale(
self,
*,
align: Optional[float | Parameter | SchemaBase | Map] = Undefined,
base: Optional[float | Parameter | SchemaBase | Map] = Undefined,
bins: Optional[SchemaBase | Sequence[float] | Map] = Undefined,
clamp: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
constant: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domain: Optional[
Parameter
| SchemaBase
| Literal["unaggregated"]
| Sequence[
str | bool | float | Temporal | Parameter | SchemaBase | Map | None
]
| Map
] = Undefined,
domainMax: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainMid: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domainMin: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainRaw: Optional[Parameter | SchemaBase | Map] = Undefined,
exponent: Optional[float | Parameter | SchemaBase | Map] = Undefined,
interpolate: Optional[
Parameter | SchemaBase | Map | ScaleInterpolateEnum_T
] = Undefined,
nice: Optional[
bool | float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingInner: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingOuter: Optional[float | Parameter | SchemaBase | Map] = Undefined,
range: Optional[
SchemaBase
| Sequence[str | float | Parameter | SchemaBase | Sequence[float] | Map]
| Map
| RangeEnum_T
] = Undefined,
rangeMax: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
rangeMin: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
reverse: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
round: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
scheme: Optional[Parameter | SchemaBase | Map | ColorScheme_T] = Undefined,
type: Optional[SchemaBase | ScaleType_T] = Undefined,
zero: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
) -> StrokeOpacity: ...
@overload
def sort(
self,
_: Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[DateTime | Temporal]
| AllSortString_T
| None,
/,
) -> StrokeOpacity: ...
@overload
def sort(
self,
*,
field: Optional[str | SchemaBase | Map] = Undefined,
op: Optional[SchemaBase | NonArgAggregateOp_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> StrokeOpacity: ...
@overload
def sort(
self,
*,
encoding: Optional[SchemaBase | SortByChannel_T] = Undefined,
order: Optional[SchemaBase | SortOrder_T | None] = Undefined,
) -> StrokeOpacity: ...
@overload
def timeUnit(
self,
_: TimeUnitParams | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T,
/,
) -> StrokeOpacity: ...
@overload
def timeUnit(
self,
*,
binned: Optional[bool] = Undefined,
maxbins: Optional[float] = Undefined,
step: Optional[float] = Undefined,
unit: Optional[SchemaBase | MultiTimeUnit_T | SingleTimeUnit_T] = Undefined,
utc: Optional[bool] = Undefined,
) -> StrokeOpacity: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> StrokeOpacity: ...
@overload
def type(self, _: StandardType_T, /) -> StrokeOpacity: ...
def __init__(
self,
shorthand: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined,
aggregate: Optional[SchemaBase | Map | NonArgAggregateOp_T] = Undefined,
bandPosition: Optional[float] = Undefined,
bin: Optional[bool | SchemaBase | Map | None] = Undefined,
condition: Optional[SchemaBase | Sequence[SchemaBase | Map] | Map] = Undefined,
field: Optional[str | SchemaBase | Map] = Undefined,
legend: Optional[SchemaBase | Map | None] = Undefined,
scale: Optional[SchemaBase | Map | None] = Undefined,
sort: Optional[
SchemaBase
| Sequence[str]
| Sequence[bool]
| Sequence[float]
| Sequence[Temporal | SchemaBase | Map]
| Map
| AllSortString_T
| None
] = Undefined,
timeUnit: Optional[
SchemaBase | Map | MultiTimeUnit_T | BinnedTimeUnit_T | SingleTimeUnit_T
] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | StandardType_T] = Undefined,
**kwds,
):
super().__init__(
shorthand=shorthand,
aggregate=aggregate,
bandPosition=bandPosition,
bin=bin,
condition=condition,
field=field,
legend=legend,
scale=scale,
sort=sort,
timeUnit=timeUnit,
title=title,
type=type,
**kwds,
)
@with_property_setters
| StrokeOpacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.