language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 110304,
"end": 110732
} | class ____(FunctorchHigherOrderVariable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def call_function(
self, tx, args: list[VariableTracker], kwargs: dict[str, VariableTracker]
) -> VariableTracker:
ctx_manager_vt = super().call_function(tx, args, kwargs)
return RepararametrizeModuleContextVariable(ctx_manager_vt, args[0])
| ReparametrizeModuleCallVariable |
python | celery__celery | t/unit/worker/test_request.py | {
"start": 45923,
"end": 52401
} | class ____(RequestCase):
def setup_method(self):
self.task = Mock(name='task')
self.pool = Mock(name='pool')
self.eventer = Mock(name='eventer')
super().setup_method()
def create_request_cls(self, **kwargs):
return create_request_cls(
Request, self.task, self.pool, 'foo', self.eventer, app=self.app,
**kwargs
)
def zRequest(self, Request=None, revoked_tasks=None, ref=None, **kwargs):
return self.xRequest(
Request=Request or self.create_request_cls(
ref=ref,
revoked_tasks=revoked_tasks,
),
**kwargs)
def test_on_success(self):
self.zRequest(id=uuid()).on_success((False, 'hey', 3.1222))
def test_on_success__SystemExit(self,
errors=(SystemExit, KeyboardInterrupt)):
for exc in errors:
einfo = None
try:
raise exc()
except exc:
einfo = ExceptionInfo()
with pytest.raises(exc):
self.zRequest(id=uuid()).on_success((True, einfo, 1.0))
def test_on_success__calls_failure(self):
job = self.zRequest(id=uuid())
einfo = Mock(name='einfo')
job.on_failure = Mock(name='on_failure')
job.on_success((True, einfo, 1.0))
job.on_failure.assert_called_with(einfo, return_ok=True)
def test_on_success__acks_late_enabled(self):
self.task.acks_late = True
job = self.zRequest(id=uuid())
job.acknowledge = Mock(name='ack')
job.on_success((False, 'foo', 1.0))
job.acknowledge.assert_called_with()
def test_on_success__acks_late_disabled(self):
self.task.acks_late = False
job = self.zRequest(id=uuid())
job.acknowledge = Mock(name='ack')
job.on_success((False, 'foo', 1.0))
job.acknowledge.assert_not_called()
def test_on_success__no_events(self):
self.eventer = None
job = self.zRequest(id=uuid())
job.send_event = Mock(name='send_event')
job.on_success((False, 'foo', 1.0))
job.send_event.assert_not_called()
def test_on_success__with_events(self):
job = self.zRequest(id=uuid())
job.send_event = Mock(name='send_event')
job.on_success((False, 'foo', 1.0))
job.send_event.assert_called_with(
'task-succeeded', result='foo', runtime=1.0,
)
def test_execute_using_pool__revoked(self):
tid = uuid()
job = self.zRequest(id=tid, revoked_tasks={tid})
job.revoked = Mock()
job.revoked.return_value = True
with pytest.raises(TaskRevokedError):
job.execute_using_pool(self.pool)
def test_execute_using_pool__expired(self):
tid = uuid()
job = self.zRequest(id=tid, revoked_tasks=set())
job.expires = 1232133
job.revoked = Mock()
job.revoked.return_value = True
with pytest.raises(TaskRevokedError):
job.execute_using_pool(self.pool)
def test_execute_using_pool(self):
weakref_ref = Mock(name='weakref.ref')
job = self.zRequest(id=uuid(), revoked_tasks=set(), ref=weakref_ref)
job.execute_using_pool(self.pool)
self.pool.apply_async.assert_called_with(
trace_task_ret,
args=(job.type, job.id, job.request_dict, job.body,
job.content_type, job.content_encoding),
accept_callback=job.on_accepted,
timeout_callback=job.on_timeout,
callback=job.on_success,
error_callback=job.on_failure,
soft_timeout=self.task.soft_time_limit,
timeout=self.task.time_limit,
correlation_id=job.id,
)
assert job._apply_result
weakref_ref.assert_called_with(self.pool.apply_async())
assert job._apply_result is weakref_ref()
def test_execute_using_pool_with_use_fast_trace_task(self):
self.app.use_fast_trace_task = True
weakref_ref = Mock(name='weakref.ref')
job = self.zRequest(id=uuid(), revoked_tasks=set(), ref=weakref_ref)
job.execute_using_pool(self.pool)
self.pool.apply_async.assert_called_with(
fast_trace_task,
args=(job.type, job.id, job.request_dict, job.body,
job.content_type, job.content_encoding),
accept_callback=job.on_accepted,
timeout_callback=job.on_timeout,
callback=job.on_success,
error_callback=job.on_failure,
soft_timeout=self.task.soft_time_limit,
timeout=self.task.time_limit,
correlation_id=job.id,
)
assert job._apply_result
weakref_ref.assert_called_with(self.pool.apply_async())
assert job._apply_result is weakref_ref()
def test_execute_using_pool_with_none_timelimit_header(self):
weakref_ref = Mock(name='weakref.ref')
job = self.zRequest(id=uuid(),
revoked_tasks=set(),
ref=weakref_ref,
headers={'timelimit': None})
job.execute_using_pool(self.pool)
self.pool.apply_async.assert_called_with(
trace_task_ret,
args=(job.type, job.id, job.request_dict, job.body,
job.content_type, job.content_encoding),
accept_callback=job.on_accepted,
timeout_callback=job.on_timeout,
callback=job.on_success,
error_callback=job.on_failure,
soft_timeout=self.task.soft_time_limit,
timeout=self.task.time_limit,
correlation_id=job.id,
)
assert job._apply_result
weakref_ref.assert_called_with(self.pool.apply_async())
assert job._apply_result is weakref_ref()
def test_execute_using_pool__defaults_of_hybrid_to_proto2(self):
weakref_ref = Mock(name='weakref.ref')
headers = strategy.hybrid_to_proto2(Mock(headers=None), {'id': uuid(),
'task': self.mytask.name})[
1]
job = self.zRequest(revoked_tasks=set(), ref=weakref_ref, **headers)
job.execute_using_pool(self.pool)
assert job._apply_result
weakref_ref.assert_called_with(self.pool.apply_async())
assert job._apply_result is weakref_ref()
| test_create_request_class |
python | huggingface__transformers | src/transformers/modeling_outputs.py | {
"start": 8767,
"end": 10833
} | class ____(ModelOutput):
"""
Base class for model's outputs, with potential hidden states and attentions.
Args:
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
sequence_length)`.
Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
weighted average in the cross-attention heads.
"""
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
cross_attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
| BaseModelOutputWithCrossAttentions |
python | dagster-io__dagster | python_modules/libraries/dagster-pandas/dagster_pandas/constraints.py | {
"start": 465,
"end": 2802
} | class ____(Exception):
"""This class defines the response generated when a pandas DF fails validation -- it can be used to generate either a
failed typecheck or an exception.
Args:
constraint_name (str): the name of the violated constraint
constraint_description (Optional[str]): the description of the violated constraint
expectation (Optional[Union[dict,list, str, set]]): what result was expected -- typically a jsonlike, though it can be a string
offending (Optional[Union[dict,list, str, set]]): which pieces of the dataframe violated the expectation, typically list or string
actual (Optional[Union[dict,list, str, set]]): what those pieces of the dataframe actually were -- typically a jsonlike
"""
def __init__(
self,
constraint_name,
constraint_description="",
expectation=None,
offending=None,
actual=None,
):
self.constraint_name = constraint_name
self.constraint_description = constraint_description
self.expectation = check.opt_inst_param(expectation, "expectation", (dict, list, str, set))
self.offending = check.opt_inst_param(offending, "offending", (dict, list, str, set))
self.actual = check.opt_inst_param(actual, "actual", (dict, list, str, set))
super().__init__(
f"Violated {constraint_name} - {constraint_description}, {expectation} was/were expected, but we received {offending} which was/were {actual}"
)
def normalize_metadata_json_value(self, val):
if isinstance(val, set):
return list(val)
else:
return val
def convert_to_metadata(self):
return {
CONSTRAINT_METADATA_KEY: {
"constraint_name": self.constraint_name,
"constraint_description": self.constraint_description,
"expected": self.normalize_metadata_json_value(self.expectation),
"offending": self.normalize_metadata_json_value(self.offending),
"actual": self.normalize_metadata_json_value(self.actual),
},
}
def return_as_typecheck(self):
return TypeCheck(
success=False, description=self.args[0], metadata=self.convert_to_metadata()
)
| ConstraintWithMetadataException |
python | huggingface__transformers | src/transformers/quantizers/quantizer_awq.py | {
"start": 1040,
"end": 7401
} | class ____(HfQuantizer):
"""
4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://huggingface.co/papers/2306.00978)
"""
# AWQ requires data calibration - we support only inference
requires_calibration = True
required_packages = ["awq", "accelerate"]
def __init__(self, quantization_config, **kwargs):
super().__init__(quantization_config, **kwargs)
def validate_environment(self, device_map, **kwargs):
if not is_auto_awq_available():
raise ImportError("Loading an AWQ quantized model requires auto-awq library (`pip install autoawq`)")
if not is_accelerate_available():
raise ImportError("Loading an AWQ quantized model requires accelerate (`pip install accelerate`)")
if (
self.quantization_config.version == AWQLinearVersion.GEMM
and not torch.cuda.is_available()
and not torch.xpu.is_available()
):
logger.warning_once("No CUDA or XPU found, consider switching to the IPEX version for CPU-only execution.")
self.quantization_config.version = AWQLinearVersion.IPEX
if self.quantization_config.version == AWQLinearVersion.IPEX:
if version.parse(importlib.metadata.version("autoawq")) < version.parse("0.2.6"):
raise RuntimeError(
"To use IPEX backend, you need autoawq>0.2.6. Please install the latest version or from source."
)
if device_map is None:
logger.warning_once(
"You have loaded an AWQ model without setting device_map, please set 'cpu' or 'xpu' or 'auto'"
)
elif isinstance(device_map, dict) and "disk" in device_map.values():
raise ValueError(
"You are attempting to load an IPEX version AWQ model with a device_map that contains disk device."
" This is not supported. Please make sure only cpu and xpu in the device_map."
)
else:
if not torch.cuda.is_available() and not torch.xpu.is_available():
raise RuntimeError(
"GPU is required to run AWQ quantized model. You can use IPEX version AWQ if you have an Intel CPU"
)
if device_map is None:
logger.warning_once(
"You have loaded an AWQ model on CPU and have a CUDA/XPU device available, make sure to set "
"your model on a GPU device in order to run your model."
)
elif device_map is not None:
if isinstance(device_map, dict) and any(
forbidden in device_map.values() for forbidden in ("cpu", torch.device("cpu"), "disk")
):
raise ValueError(
"You are attempting to load an AWQ model with a device_map that contains a CPU or disk device."
" This is not supported. Please remove the CPU or disk device from the device_map."
)
def update_dtype(self, dtype):
if dtype is None:
dtype = torch.float16
logger.info("Loading the model in `torch.float16`. To overwrite it, set `dtype` manually.")
elif dtype == torch.bfloat16 and (torch.cuda.is_available() or torch.xpu.is_available()):
logger.warning(
"`torch.bfloat16` is not supported for AWQ CUDA/XPU kernels yet. Casting to `torch.float16`."
)
dtype = torch.float16
elif dtype != torch.float16 and (torch.cuda.is_available() or torch.xpu.is_available()):
logger.warning("We suggest you to set `dtype=torch.float16` for better efficiency on CUDA/XPU with AWQ.")
return dtype
def _process_model_before_weight_loading(
self, model: "PreTrainedModel", keep_in_fp32_modules: list[str] | None = None, **kwargs
):
from ..integrations import replace_quantization_scales, replace_with_awq_linear
self.modules_to_not_convert = self.get_modules_to_not_convert(
model, self.quantization_config.modules_to_not_convert, keep_in_fp32_modules, add_default_skips=True
)
model, has_been_replaced = replace_with_awq_linear(
model, quantization_config=self.quantization_config, modules_to_not_convert=self.modules_to_not_convert
)
model = replace_quantization_scales(model, model.config.model_type)
if not has_been_replaced:
logger.warning(
"You are loading an AWQ model but no linear modules were found in your model."
" Please double check your model architecture, or submit an issue on github if you think this is a bug."
)
def _process_model_after_weight_loading(self, model, **kwargs):
if self.quantization_config.do_fuse:
from ..integrations import fuse_awq_modules
model = fuse_awq_modules(model, self.quantization_config)
model._awq_is_fused = True # TODO: consider storing this flag in model.config instead
if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
from ..integrations import post_init_awq_exllama_modules
model = post_init_awq_exllama_modules(model, self.quantization_config.exllama_config)
if self.quantization_config.version == AWQLinearVersion.IPEX:
from ..integrations import post_init_awq_ipex_modules
model = post_init_awq_ipex_modules(model)
def is_serializable(self, safe_serialization=None):
# AWQ through auto-awq has been always serializable, except if the model is fused.
if self.quantization_config.do_fuse:
logger.warning("You cannot save an AWQ model that uses fused modules!")
return False
if self.quantization_config.version == AWQLinearVersion.EXLLAMA:
logger.warning("You cannot save an AWQ model that uses Exllama backend!")
return False
return True
@property
def is_trainable(self):
# AWQ supports PEFT fine-tuning from version 0.2.0
MIN_AWQ_VERSION_FOR_PEFT = "0.2.0"
return version.parse(importlib.metadata.version("autoawq")) >= version.parse(MIN_AWQ_VERSION_FOR_PEFT)
| AwqQuantizer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self9.py | {
"start": 207,
"end": 618
} | class ____(ParentA):
b: int
@classmethod
def method1(cls) -> None:
reveal_type(cls.a, expected_text="list[Self@ChildA]")
reveal_type(cls.a[0], expected_text="Self@ChildA")
print(cls.a[0].b)
def method2(self) -> None:
reveal_type(self.a, expected_text="list[Self@ChildA]")
reveal_type(self.a[0], expected_text="Self@ChildA")
print(self.a[0].b)
| ChildA |
python | pytorch__pytorch | torchgen/dest/lazy_ir.py | {
"start": 12516,
"end": 14749
} | class ____(GenLazyIR):
def lowering_function(self, schema: LazyIrSchema) -> str:
signature = """
torch::lazy::TSOpVector Lower(
std::shared_ptr<torch::jit::GraphFunction> function,
torch::lazy::TSLoweringContext* loctx) const override"""
if schema.properties.LowerDeclOnly:
return f"{signature};"
elif schema.properties.Lower:
return f"""{signature} {{
{ts_lowering_body(schema)}
}}
"""
else:
return ""
def create_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
signature = f"static NodePtr Create({node_ctor_args})"
if schema.properties.CreateFnDeclOnly:
return f"{signature};"
elif not schema.properties.CreateFn:
return ""
return f"""{signature} {{
return ReuseOrMakeNode<{schema.node_name}>(data);
}}"""
def can_be_reused_function(self, schema: LazyIrSchema, node_ctor_args: str) -> str:
signature = f"bool CanBeReused({node_ctor_args}) const"
if schema.properties.CanBeReusedDeclOnly:
return f"{signature};"
elif not schema.properties.CanBeReused:
return ""
value_comparison = []
for arg in itertools.chain(schema.positional_values, schema.keyword_values):
if isinstance(arg.lazy_type, OptionalCType):
value_comparison.append(
f"nullable_operand(i++) == {arg.name}.value_or(kNullValue)"
)
else:
value_comparison.append(f"operand(i++) == {arg.name}")
for arg in itertools.chain(schema.positional_scalars, schema.keyword_scalars):
if isinstance(arg.lazy_type, OptionalCType):
value_comparison.append(
f"((!this->{arg.name}&&!{arg.name}) || (this->{arg.name}&&{arg.name} && *(this->{arg.name}) == *{arg.name}))"
)
else:
value_comparison.append(f"this->{arg.name} == {arg.name}")
value_comparison_str = " &&\n ".join(value_comparison)
return f"""{signature} {{
size_t i = 0;
return ({value_comparison_str});
}}"""
@dataclass(frozen=True)
| GenTSLazyIR |
python | gevent__gevent | src/gevent/libuv/watcher.py | {
"start": 28530,
"end": 28626
} | class ____(_base.CheckMixin, watcher):
_watcher_callback_name = '_gevent_check_callback0'
| check |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_subprojects.py | {
"start": 253,
"end": 10346
} | class ____(TestCase):
def setUp(self):
self.user = fixture.get(User)
self.project = fixture.get(Project, users=[self.user])
self.subproject = fixture.get(Project, users=[self.user])
self.project.add_subproject(self.subproject, "subproject")
self.relation = self.subproject.superprojects.first()
def test_empty_child(self):
user = fixture.get(User)
project = fixture.get(Project, slug="mainproject")
form = ProjectRelationshipForm(
{},
project=project,
user=user,
)
form.full_clean()
self.assertEqual(len(form.errors["child"]), 1)
self.assertRegex(
form.errors["child"][0],
r"This field is required.",
)
def test_nonexistent_child(self):
user = fixture.get(User)
project = fixture.get(Project, slug="mainproject")
self.assertFalse(Project.objects.filter(pk=9999).exists())
form = ProjectRelationshipForm(
{"child": 9999},
project=project,
user=user,
)
form.full_clean()
self.assertEqual(len(form.errors["child"]), 1)
self.assertRegex(
form.errors["child"][0],
r"Select a valid choice.",
)
def test_adding_subproject_fails_when_user_is_not_admin(self):
user = fixture.get(User)
project = fixture.get(Project, slug="mainproject")
project.users.add(user)
subproject = fixture.get(Project, slug="subproject")
self.assertQuerySetEqual(
Project.objects.for_admin_user(user),
[project],
transform=lambda n: n,
ordered=False,
)
form = ProjectRelationshipForm(
{"child": subproject.pk},
project=project,
user=user,
)
form.full_clean()
self.assertEqual(len(form.errors["child"]), 1)
self.assertRegex(
form.errors["child"][0],
r"Select a valid choice.",
)
self.assertEqual(
[proj_id for (proj_id, _) in form.fields["child"].choices],
[""],
)
def test_adding_subproject_passes_when_user_is_admin(self):
user = fixture.get(User)
project = fixture.get(Project, slug="mainproject")
project.users.add(user)
subproject = fixture.get(Project, slug="subproject")
subproject.users.add(user)
self.assertQuerySetEqual(
Project.objects.for_admin_user(user),
[project, subproject],
transform=lambda n: n,
ordered=False,
)
form = ProjectRelationshipForm(
{"child": subproject.pk},
project=project,
user=user,
)
form.full_clean()
self.assertTrue(form.is_valid())
form.save()
self.assertEqual(
[r.child for r in project.subprojects.all()],
[subproject],
)
def test_subproject_form_cant_create_sub_sub_project(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
subsubproject = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship,
parent=project,
child=subproject,
)
self.assertQuerySetEqual(
Project.objects.for_admin_user(user),
[project, subproject, subsubproject],
transform=lambda n: n,
ordered=False,
)
form = ProjectRelationshipForm(
{"child": subsubproject.pk},
project=subproject,
user=user,
)
# The subsubproject is valid here, as far as the child check is
# concerned, but the parent check should fail.
self.assertEqual(
[proj_id for (proj_id, _) in form.fields["child"].choices],
["", subsubproject.pk],
)
form.full_clean()
self.assertEqual(len(form.errors["parent"]), 1)
self.assertRegex(
form.errors["parent"][0],
r"Subproject nesting is not supported",
)
def test_excludes_existing_subprojects(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship,
parent=project,
child=subproject,
)
self.assertQuerySetEqual(
Project.objects.for_admin_user(user),
[project, subproject],
transform=lambda n: n,
ordered=False,
)
form = ProjectRelationshipForm(
{"child": subproject.pk},
project=project,
user=user,
)
self.assertEqual(
[proj_id for (proj_id, _) in form.fields["child"].choices],
[""],
)
def test_subproject_cant_be_subproject(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
another_project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship,
parent=project,
child=subproject,
)
form = ProjectRelationshipForm(
{"child": subproject.pk},
project=project,
user=user,
)
self.assertFalse(form.is_valid())
self.assertRegex(
form.errors["child"][0],
"Select a valid choice",
)
form = ProjectRelationshipForm(
{"child": subproject.pk},
project=another_project,
user=user,
)
self.assertFalse(form.is_valid())
self.assertRegex(
form.errors["child"][0],
"Select a valid choice",
)
def test_superproject_cant_be_subproject(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
another_project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship,
parent=project,
child=subproject,
)
form = ProjectRelationshipForm(
{"child": project.pk},
project=another_project,
user=user,
)
self.assertFalse(form.is_valid())
self.assertRegex(
form.errors["child"][0],
"Select a valid choice",
)
def test_exclude_self_project_as_subproject(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
form = ProjectRelationshipForm(
{"child": project.pk},
project=project,
user=user,
)
self.assertFalse(form.is_valid())
self.assertIn(
"Select a valid choice",
form.errors["child"][0],
)
self.assertNotIn(
project.id,
[proj_id for (proj_id, __) in form.fields["child"].choices],
)
def test_alias_already_exists_for_a_project(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
subproject_2 = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship, parent=project, child=subproject, alias="subproject"
)
form = ProjectRelationshipForm(
{"child": subproject_2.id, "alias": "subproject"},
project=project,
user=user,
)
self.assertFalse(form.is_valid())
error_msg = "A subproject with this alias already exists"
self.assertDictEqual(form.errors, {"alias": [error_msg]})
def test_edit_only_lists_instance_project_in_child_choices(self):
user = fixture.get(User)
project = fixture.get(Project, users=[user])
subproject = fixture.get(Project, users=[user])
relation = fixture.get(
ProjectRelationship, parent=project, child=subproject, alias="subproject"
)
form = ProjectRelationshipForm(
instance=relation,
project=project,
user=user,
)
self.assertEqual(
[proj_id for (proj_id, __) in form.fields["child"].choices],
["", relation.child.id],
)
def test_change_alias(self):
subproject_2 = fixture.get(Project, users=[self.user])
self.project.add_subproject(subproject_2, "another-subproject")
relation = subproject_2.superprojects.first()
# Change alias to an existing alias
form = ProjectRelationshipForm(
{"child": subproject_2.id, "alias": "subproject"},
instance=relation,
project=self.project,
user=self.user,
)
self.assertFalse(form.is_valid())
error_msg = "A subproject with this alias already exists"
self.assertDictEqual(form.errors, {"alias": [error_msg]})
# Change alias to a new alias
form = ProjectRelationshipForm(
{"child": subproject_2.id, "alias": "other-subproject"},
instance=relation,
project=self.project,
user=self.user,
)
self.assertTrue(form.is_valid())
form.save()
relation.refresh_from_db()
self.assertEqual(relation.alias, "other-subproject")
def test_change_alias_to_same_alias(self):
form = ProjectRelationshipForm(
{"child": self.subproject.id, "alias": "subproject"},
instance=self.relation,
project=self.project,
user=self.user,
)
self.assertTrue(form.is_valid())
form.save()
self.relation.refresh_from_db()
self.assertEqual(self.relation.alias, "subproject")
| SubprojectFormTests |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 16335,
"end": 17195
} | class ____(Node):
__slots__ = ('loc', 'name', 'value',)
_fields = ('name', 'value',)
def __init__(self, name, value, loc=None):
self.loc = loc
self.name = name
self.value = value
def __eq__(self, other):
return (
self is other or (
isinstance(other, ObjectField) and
# self.loc == other.loc and
self.name == other.name and
self.value == other.value
)
)
def __repr__(self):
return ('ObjectField('
'name={self.name!r}'
', value={self.value!r}'
')').format(self=self)
def __copy__(self):
return type(self)(
self.name,
self.value,
self.loc
)
def __hash__(self):
return id(self)
| ObjectField |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/atrous_convolution_test.py | {
"start": 2171,
"end": 11413
} | class ____(test.TestCase):
@contextlib.contextmanager
def _delay_checks(self):
"""Context manager for combining checks depending on tensor evaluations.
Each call to Session.run has some overhead, and this overhead can easily
account for the majority of the time spent in tests that call Session.run
(or Tensor.eval) many times.
This context manager provides a mechanism for registering callback functions
and associated tensors. When the context is exited, all of the tensors
associated with all of the registrations are evaluated with a single call to
Session.run, and then each registered callback function is called with the
values of its associated tensors.
Yields:
A function `add_check(check, *args, **kwargs)` where `check` is the
callback function to be invoked, and `*args` and `**kwargs` specify the
associated Tensors. When in EAGER mode, check is executed in add_check,
otherwise, it's delayed after the context.
"""
checks = []
def add_check(check, *args, **kwargs):
if context.executing_eagerly():
args_val, kwargs_val = self.evaluate([args, kwargs])
check(*args_val, **kwargs_val)
else:
checks.append((check, args, kwargs))
yield add_check
if not context.executing_eagerly():
all_values = self.evaluate([[args, kwargs] for _, args, kwargs in checks])
for (check, _, _), (args, kwargs) in zip(checks, all_values):
check(*args, **kwargs)
def _test_atrous_convolution(self, add_check, input_shape, filter_shape,
dilation_rate, **kwargs):
filters = np.arange(
np.prod(filter_shape), dtype=np.float32).reshape(filter_shape)
filters_upsampled = upsample_filters(filters, dilation_rate)
x = np.arange(np.prod(input_shape), dtype=np.float32).reshape(input_shape)
y1 = nn_ops.convolution(
input=x, filter=filters, dilation_rate=dilation_rate, **kwargs)
y2 = nn_ops.convolution(input=x, filter=filters_upsampled, **kwargs)
def check(y1_eval, y2_eval):
self.assertAllClose(y1_eval, y2_eval, rtol=1e-2, atol=1e-2)
add_check(check, y1, y2)
@test_util.run_v1_only("b/120545219")
def test_unknown_spatial_dims_for_channel_last_format(self):
x = array_ops.placeholder(dtypes.float32, [1, None, None, 10])
w = array_ops.zeros([3, 3, 10, 20])
y = nn_ops.convolution(
x, w, "VALID", dilation_rate=[2, 2], data_format="NHWC")
self.assertEqual(y.shape.as_list(), [1, None, None, 20])
@test_util.run_v1_only("b/120545219")
def test_unknown_spatial_dims_for_channel_first_format(self):
x = array_ops.placeholder(dtypes.float32, [1, 10, None, None])
w = array_ops.zeros([3, 3, 10, 20])
y = nn_ops.convolution(
x, w, "VALID", dilation_rate=[2, 2], data_format="NCHW")
self.assertEqual(y.shape.as_list(), [1, 20, None, None])
@test_util.run_in_graph_and_eager_modes
def testAtrousConvolution2D(self):
with self._delay_checks() as add_check:
for padding in ["SAME", "VALID"]:
for height, width in [[9, 9], [9, 10]]:
for kernel_height, kernel_width in [[1, 1], [2, 2], [2, 3]]:
for dilation_rate in [[1, 1], [3, 2], [2, 1]]:
self._test_atrous_convolution(
add_check=add_check,
input_shape=[2, height, width, 2],
filter_shape=[kernel_height, kernel_width, 2, 2],
padding=padding,
dilation_rate=dilation_rate,
)
@test_util.run_in_graph_and_eager_modes
def testAtrousConvolution3D(self):
with self._delay_checks() as add_check:
for padding in ["SAME", "VALID"]:
for depth, height, width in [[9, 9, 10], [9, 10, 9]]:
for kernel_depth, kernel_height, kernel_width in [[3, 3,
3], [3, 2, 2],
[2, 1, 3]]:
for dilation_rate in [[1, 1, 1], [3, 3, 3], [3, 2, 3], [3, 1, 2]]:
self._test_atrous_convolution(
add_check=add_check,
input_shape=[2, depth, height, width, 2],
filter_shape=[
kernel_depth, kernel_height, kernel_width, 2, 2
],
padding=padding,
dilation_rate=dilation_rate,
)
@test_util.run_in_graph_and_eager_modes
def testAtrousConvolution1D(self):
with self._delay_checks() as add_check:
for padding in ["SAME", "VALID"]:
for width in [9, 10]:
for kernel_width in range(1, 4):
for rate in range(1, 4):
self._test_atrous_convolution(
add_check=add_check,
input_shape=[2, width, 2],
filter_shape=[kernel_width, 2, 2],
padding=padding,
dilation_rate=[rate],
)
@test_util.run_in_graph_and_eager_modes
def testAtrousConvolutionNC(self):
if test.is_gpu_available(cuda_only=True):
# "NCW" and "NCHW" formats are currently supported only on CUDA.
with test_util.device(use_gpu=True):
with self._delay_checks() as add_check:
for padding in ["SAME", "VALID"]:
self._test_atrous_convolution(
add_check=add_check,
input_shape=[2, 2, 9],
padding=padding,
filter_shape=[3, 2, 2],
dilation_rate=[2],
data_format="NCW",
)
self._test_atrous_convolution(
add_check=add_check,
input_shape=[2, 2, 9, 5],
padding=padding,
filter_shape=[3, 3, 2, 2],
dilation_rate=[2, 1],
data_format="NCHW",
)
@test_util.run_in_graph_and_eager_modes
def testAtrousSequence(self):
"""Tests optimization of sequence of atrous convolutions.
See the documentation of with_space_to_batch.
"""
with self._delay_checks() as add_check:
for padding in ["SAME", "VALID"]:
for height in range(15, 17):
for width in range(15, 17):
x_shape = [3, height, width, 2]
x = np.random.random_sample(x_shape).astype(np.float32)
kernel_sizes = [1, 3] if padding == "SAME" else range(1, 3)
for kernel in kernel_sizes:
f_shape = [kernel, kernel, 2, 2]
f1 = 1e-2 * np.random.random_sample(f_shape).astype(np.float32)
f2 = 1e-2 * np.random.random_sample(f_shape).astype(np.float32)
def combined_op(converted_input, num_spatial_dims, padding_arg): # pylint: disable=unused-argument
# pylint: disable=cell-var-from-loop
result = nn_ops.convolution(
input=converted_input, filter=f1, padding=padding)
result = nn_ops.convolution(
input=result, filter=f2, padding=padding)
# pylint: enable=cell-var-from-loop
return result
for rate_height in range(2, 4):
for rate_width in range(2, 4):
dilation_rate = [rate_height, rate_width]
y1 = nn_ops.convolution(
input=x,
filter=f1,
padding=padding,
dilation_rate=dilation_rate)
y1 = nn_ops.convolution(
input=y1,
filter=f2,
padding=padding,
dilation_rate=dilation_rate)
y2 = nn_ops.with_space_to_batch(
input=x,
dilation_rate=dilation_rate,
op=combined_op,
padding="VALID")
def check(y1_eval, y2_eval):
self.assertAllClose(y1_eval, y2_eval, rtol=1e-2, atol=1e-2)
add_check(check, y1, y2)
def _test_gradient(self, x_shape, f_shape, dilation_rate, padding):
x_val = np.random.random_sample(x_shape).astype(np.float32)
f_val = np.random.random_sample(f_shape).astype(np.float32)
x = constant_op.constant(x_val, name="x", dtype=dtypes.float32)
f = constant_op.constant(f_val, name="f", dtype=dtypes.float32)
output = nn_ops.convolution(
input=x, filter=f, dilation_rate=dilation_rate, padding=padding)
y_shape = output.get_shape().as_list()
err = gradient_checker.compute_gradient_error([x, f], [x_shape, f_shape],
output, y_shape)
err_tolerance = 1e-2
self.assertLess(err, err_tolerance)
@test_util.run_v1_only("b/120545219")
def testGradient(self):
with self.cached_session():
for padding in ["SAME", "VALID"]:
for rate_width in range(1, 3):
for rate_height in range(1, 3):
self._test_gradient(
x_shape=[2, 5, 6, 2],
f_shape=[3, 3, 2, 2],
dilation_rate=[rate_height, rate_width],
padding=padding)
if __name__ == "__main__":
test.main()
| AtrousConvolutionTest |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 26665,
"end": 27667
} | class ____(AbstractTemplate):
def _unify_minmax(self, tys):
for ty in tys:
if not isinstance(ty, (types.Number, types.NPDatetime, types.NPTimedelta)):
return
return self.context.unify_types(*tys)
def generic(self, args, kws):
"""
Resolve a min() or max() call.
"""
assert not kws
if not args:
return
if len(args) == 1:
# max(arg) only supported if arg is an iterable
if isinstance(args[0], types.BaseTuple):
tys = list(args[0])
if not tys:
raise errors.TypingError("%s() argument is an empty tuple"
% (self.key.__name__,))
else:
return
else:
# max(*args)
tys = args
retty = self._unify_minmax(tys)
if retty is not None:
return signature(retty, *args)
@infer_global(max)
| MinMaxBase |
python | walkccc__LeetCode | solutions/2479. Maximum XOR of Two Non-Overlapping Subtrees/2479.py | {
"start": 94,
"end": 854
} | class ____:
def __init__(self, maxBit: int):
self.maxBit = maxBit
self.root = TrieNode()
def insert(self, num: int) -> None:
node = self.root
for i in range(self.maxBit, -1, -1):
bit = num >> i & 1
if not node.children[bit]:
node.children[bit] = TrieNode()
node = node.children[bit]
def getMaxXor(self, num: int) -> int:
maxXor = 0
node = self.root
for i in range(self.maxBit, -1, -1):
bit = num >> i & 1
toggleBit = bit ^ 1
if node.children[toggleBit]:
maxXor = maxXor | 1 << i
node = node.children[toggleBit]
elif node.children[bit]:
node = node.children[bit]
else: # There's nothing in the Bit Trie.
return 0
return maxXor
| BitTrie |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 8189,
"end": 10133
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.static_encodings'
# XXX webtest actually runs response.decode_content() and so we can't
# use it to test gzip- or deflate-encoded responses to see if they
# were transferred correctly
def _getResponse(self, *args, **kwargs):
from pyramid.request import Request
req = Request.blank(*args, **kwargs)
return req.get_response(self.app)
def test_no_accept(self):
res = self._getResponse('/static/encoded.html')
self.assertEqual(res.headers['Vary'], 'Accept-Encoding')
self.assertNotIn('Content-Encoding', res.headers)
_assertBody(
res.body, os.path.join(here, 'fixtures/static/encoded.html')
)
def test_unsupported_accept(self):
res = self._getResponse(
'/static/encoded.html',
headers={'Accept-Encoding': 'br, foo, bar'},
)
self.assertEqual(res.headers['Vary'], 'Accept-Encoding')
self.assertNotIn('Content-Encoding', res.headers)
_assertBody(
res.body, os.path.join(here, 'fixtures/static/encoded.html')
)
def test_accept_gzip(self):
res = self._getResponse(
'/static/encoded.html',
headers={'Accept-Encoding': 'br, foo, gzip'},
)
self.assertEqual(res.headers['Vary'], 'Accept-Encoding')
self.assertEqual(res.headers['Content-Encoding'], 'gzip')
_assertBody(
res.body, os.path.join(here, 'fixtures/static/encoded.html.gz')
)
def test_accept_gzip_returns_identity(self):
res = self._getResponse(
'/static/index.html', headers={'Accept-Encoding': 'gzip'}
)
self.assertNotIn('Vary', res.headers)
self.assertNotIn('Content-Encoding', res.headers)
_assertBody(res.body, os.path.join(here, 'fixtures/static/index.html'))
| TestStaticAppWithEncodings |
python | walkccc__LeetCode | solutions/2302. Count Subarrays With Score Less Than K/2302.py | {
"start": 0,
"end": 280
} | class ____:
def countSubarrays(self, nums: list[int], k: int) -> int:
ans = 0
summ = 0
l = 0
for r, num in enumerate(nums):
summ += num
while summ * (r - l + 1) >= k:
summ -= nums[l]
l += 1
ans += r - l + 1
return ans
| Solution |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_select_column_values_to_be_unique_within_record.py | {
"start": 2256,
"end": 14806
} | class ____(MulticolumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectSelectColumnValuesToBeUniqueWithinRecord is a \
Multicolumn Map Expectation.
Multicolumn Map Expectations are evaluated for a set of columns and ask a yes/no question about the row-wise relationship between those columns.
Based on the result, they then calculate the percentage of rows that gave a positive answer.
If the percentage is high enough, the Expectation considers that data valid.
Args:
column_list (tuple or list): {COLUMN_LIST_DESCRIPTION}
Other Parameters:
ignore_row_if (str): \
"all_values_are_missing", "any_value_is_missing", "never" \
{IGNORE_ROW_IF_DESCRIPTION} Default "never".
mostly (None or a float between 0 and 1): \
{MOSTLY_DESCRIPTION} \
For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly). Default 1.
result_format (str or None): \
Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \
For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format).
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions).
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without \
modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta).
severity (str or None): \
{FAILURE_SEVERITY_DESCRIPTION} \
For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity).
Returns:
An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result)
Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta.
Supported Data Sources:
[{SUPPORTED_DATA_SOURCES[0]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[1]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[2]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[3]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[4]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[5]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[6]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[7]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[8]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[9]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[10]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[11]}](https://docs.greatexpectations.io/docs/application_integration_support/)
[{SUPPORTED_DATA_SOURCES[12]}](https://docs.greatexpectations.io/docs/application_integration_support/)
Data Quality Issues:
{DATA_QUALITY_ISSUES[0]}
For example:
::
A B C
1 1 2 Fail
1 2 3 Pass
8 2 7 Pass
1 2 3 Pass
4 4 4 Fail
Example Data:
test test2 test3
0 1 1 2
1 1 2 3
2 8 2 7
Code Examples:
Passing Case:
Input:
ExpectSelectColumnValuesToBeUniqueWithinRecord(
column_list=["test", "test3"],
)
Output:
{{
"exception_info": {{
"raised_exception": false,
"exception_traceback": null,
"exception_message": null
}},
"result": {{
"element_count": 3,
"unexpected_count": 0,
"unexpected_percent": 0.0,
"partial_unexpected_list": [],
"missing_count": 0,
"missing_percent": 0.0,
"unexpected_percent_total": 0.0,
"unexpected_percent_nonmissing": 0.0
}},
"meta": {{}},
"success": true
}}
Failing Case:
Input:
ExpectSelectColumnValuesToBeUniqueWithinRecord(
column_list=["test", "test2", "test3"],
)
Output:
{{
"exception_info": {{
"raised_exception": false,
"exception_traceback": null,
"exception_message": null
}},
"result": {{
"element_count": 3,
"unexpected_count": 1,
"unexpected_percent": 33.33333333333333,
"partial_unexpected_list": [
{{
"test": 1,
"test2": 1,
"test3": 2
}}
],
"missing_count": 0,
"missing_percent": 0.0,
"unexpected_percent_total": 33.33333333333333,
"unexpected_percent_nonmissing": 33.33333333333333
}},
"meta": {{}},
"success": false
}}
""" # noqa: E501 # FIXME CoP
column_list: Sequence[str] = pydantic.Field(description=COLUMN_LIST_DESCRIPTION)
ignore_row_if: Union[str, SuiteParameterDict] = pydantic.Field(
default="all_values_are_missing", description=IGNORE_ROW_IF_DESCRIPTION
)
library_metadata: ClassVar[Dict[str, Union[str, list, bool]]] = {
"maturity": "production",
"tags": [
"core expectation",
"multi-column expectation",
],
"contributors": [
"@great_expectations",
],
"requirements": [],
"has_full_test_suite": True,
"manually_reviewed_code": True,
}
_library_metadata = library_metadata
map_metric = "select_column_values.unique.within_record"
args_keys = ("column_list",)
class Config:
title = "Expect select column values to be unique within record"
@staticmethod
def schema_extra(
schema: Dict[str, Any], model: Type[ExpectSelectColumnValuesToBeUniqueWithinRecord]
) -> None:
MulticolumnMapExpectation.Config.schema_extra(schema, model)
schema["properties"]["metadata"]["properties"].update(
{
"data_quality_issues": {
"title": "Data Quality Issues",
"type": "array",
"const": DATA_QUALITY_ISSUES,
},
"library_metadata": {
"title": "Library Metadata",
"type": "object",
"const": model._library_metadata,
},
"short_description": {
"title": "Short Description",
"type": "string",
"const": EXPECTATION_SHORT_DESCRIPTION,
},
"supported_data_sources": {
"title": "Supported Data Sources",
"type": "array",
"const": SUPPORTED_DATA_SOURCES,
},
}
)
@classmethod
def _prescriptive_template(
cls,
renderer_configuration: RendererConfiguration,
) -> RendererConfiguration:
add_param_args: AddParamArgs = (
("column_list", RendererValueType.ARRAY),
("mostly", RendererValueType.NUMBER),
("ignore_row_if", RendererValueType.STRING),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
if params.mostly and params.mostly.value < 1.0:
renderer_configuration = cls._add_mostly_pct_param(
renderer_configuration=renderer_configuration
)
template_str = (
"Values must be unique across columns, at least $mostly_pct % of the time: "
)
else:
template_str = "Values must always be unique across columns: "
if params.column_list:
array_param_name = "column_list"
param_prefix = "column_list_"
renderer_configuration = cls._add_array_params(
array_param_name=array_param_name,
param_prefix=param_prefix,
renderer_configuration=renderer_configuration,
)
template_str += cls._get_array_string(
array_param_name=array_param_name,
param_prefix=param_prefix,
renderer_configuration=renderer_configuration,
)
renderer_configuration.template_str = template_str
return renderer_configuration
@classmethod
@renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE)
@render_suite_parameter_string
def _prescriptive_renderer(
cls,
configuration: Optional[ExpectationConfiguration] = None,
result: Optional[ExpectationValidationResult] = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
):
runtime_configuration = runtime_configuration or {}
_ = runtime_configuration.get("include_column_name") is not False
styling = runtime_configuration.get("styling")
params = substitute_none_for_missing(
configuration.kwargs,
[
"column_list",
"ignore_row_if",
"row_condition",
"condition_parser",
"mostly",
],
)
if params["mostly"] is not None:
if isinstance(params["mostly"], (int, float)) and params["mostly"] < 1.0:
params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True)
# params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP
template_str = (
"Values must be unique across columns, at least $mostly_pct % of the time: "
)
else:
template_str = "Values must always be unique across columns: "
for idx in range(len(params["column_list"]) - 1):
template_str += f"$column_list_{idx!s}, "
params[f"column_list_{idx!s}"] = params["column_list"][idx]
last_idx = len(params["column_list"]) - 1
template_str += f"$column_list_{last_idx!s}"
params[f"column_list_{last_idx!s}"] = params["column_list"][last_idx]
if params["row_condition"] is not None:
conditional_template_str = parse_row_condition_string(params["row_condition"])
template_str, styling = _style_row_condition(
conditional_template_str,
template_str[0].lower() + template_str[1:],
params,
styling,
)
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": params,
"styling": styling,
},
}
)
]
| ExpectSelectColumnValuesToBeUniqueWithinRecord |
python | huggingface__transformers | src/transformers/models/sam3_video/processing_sam3_video.py | {
"start": 1057,
"end": 18809
} | class ____(ProcessorMixin):
r"""
Constructs a SAM3 processor which wraps a SAM3 image processor and an 2D points & Bounding boxes processor into a
single processor.
[`Sam3Processor`] offers all the functionalities of [`Sam3ImageProcessor`] and [`Sam3VideoProcessor`]. See the docstring of
[`~Sam3ImageProcessor.__call__`] and [`~Sam3VideoProcessor.__call__`] for more information.
Args:
image_processor (`Sam3ImageProcessorFast`):
An instance of [`Sam3ImageProcessorFast`].
video_processor (`Sam2VideoVideoProcessor`):
An instance of [`Sam2VideoVideoProcessor`].
tokenizer ([`CLIPTokenizer`, `CLIPTokenizerFast`]):
An instance of [`PreTrainedTokenizer`, `PreTrainedTokenizerFast`]. The tokenizer is a required input.
target_size (`int`, *optional*):
The target size (target_size, target_size) to which the image will be resized.
"""
def __init__(
self,
image_processor,
video_processor,
tokenizer,
target_size: Optional[int] = None,
**kwargs,
):
super().__init__(image_processor, video_processor, tokenizer, **kwargs)
self.target_size = target_size if target_size is not None else self.image_processor.size["height"]
def __call__(
self,
images: Optional[ImageInput] = None,
segmentation_maps: Optional[ImageInput] = None,
original_sizes: Optional[Union[list[list[float]], torch.Tensor]] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
**kwargs,
) -> BatchEncoding:
r"""
This method uses [`Sam3VideoImageProcessorFast.__call__`] method to prepare image(s) for the model.
Args:
images (`ImageInput`, *optional*):
The image(s) to process.
segmentation_maps (`ImageInput`, *optional*):
The segmentation maps to process (optional, for image processor).
original_sizes (`list[list[float]]`, `torch.Tensor`, *optional*):
The original sizes of the images. Only used when images is not provided.
return_tensors (`str` or `TensorType`, *optional*):
The type of tensors to return.
**kwargs:
Additional keyword arguments to pass to the image processor.
Returns:
A [`BatchEncoding`] with the following fields:
- `pixel_values` (`torch.Tensor`): The processed image(s).
- `original_sizes` (`list[list[float]]`): The original sizes of the images.
- `labels` (`torch.Tensor`, *optional*): The processed segmentation maps (if provided).
"""
if images is not None:
encoding_image_processor = self.image_processor(
images,
segmentation_maps=segmentation_maps,
return_tensors=return_tensors,
**kwargs,
)
elif original_sizes is not None:
if isinstance(original_sizes, torch.Tensor):
original_sizes = original_sizes.cpu().tolist()
encoding_image_processor = BatchEncoding({"original_sizes": original_sizes}, tensor_type=return_tensors)
else:
raise ValueError("Either images or original_sizes must be provided")
original_sizes = encoding_image_processor["original_sizes"]
# Check original_sizes is of length 1 or len(images)
if images is not None and len(original_sizes) != 1 and len(original_sizes) != len(images):
raise ValueError(
"original_sizes must be of length 1 or len(images). If you are passing a single image, you must pass a single original_size."
)
return encoding_image_processor
def add_text_prompt(self, inference_session: Sam3VideoInferenceSession, text: Union[str, list[str]]):
"""
Add text prompt(s) to the inference session.
Args:
inference_session (`Sam3VideoInferenceSession`): The inference session.
text (`str` or `list[str]`): The text prompt(s) to add.
Returns:
`Sam3VideoInferenceSession`: The inference session with the added text prompt(s).
"""
if isinstance(text, str):
text = [text]
prompt_ids = []
for prompt_text in text:
# Add prompt and get its ID (reuses existing if duplicate)
prompt_id = inference_session.add_prompt(prompt_text)
# Only encode if this is a new prompt (not already in prompt_input_ids)
if prompt_id not in inference_session.prompt_input_ids:
encoded_text = self.tokenizer(
prompt_text, return_tensors="pt", padding="max_length", max_length=32
).to(inference_session.inference_device)
inference_session.prompt_input_ids[prompt_id] = encoded_text.input_ids
inference_session.prompt_attention_masks[prompt_id] = encoded_text.attention_mask
prompt_ids.append(prompt_id)
return inference_session
def init_video_session(
self,
video: Optional[VideoInput] = None,
inference_device: Union[str, "torch.device"] = "cpu",
inference_state_device: Optional[Union[str, "torch.device"]] = None,
processing_device: Optional[Union[str, "torch.device"]] = None,
video_storage_device: Optional[Union[str, "torch.device"]] = None,
max_vision_features_cache_size: int = 1,
dtype: torch.dtype = torch.float32,
):
"""
Initializes a video session for inference.
If a video is provided (async inference), the video will be processed and stored on the `video_storage_device`.
Args:
video (`VideoInput`, *optional*):
The video to process. No need to provide when streaming.
inference_device (`str` or `torch.device`, *optional*, defaults to "cpu"):
The device to use for inference.
inference_state_device (`str` or `torch.device`, *optional*):
The device to store the inference state on.
processing_device (`str` or `torch.device`, *optional*):
The device to use for video processing.
video_storage_device (`str` or `torch.device`, *optional*):
The device to store the processed video frames on.
max_vision_features_cache_size (`int`, *optional*, defaults to 1):
The maximum number of vision features to cache.
dtype (`torch.dtype`, *optional*, defaults to `torch.float32`):
The torch dtype to use for the whole session.
"""
video_storage_device = video_storage_device if video_storage_device is not None else inference_device
inference_state_device = inference_state_device if inference_state_device is not None else inference_device
processing_device = processing_device if processing_device is not None else inference_device
pixel_values_video = None
video_height = None
video_width = None
if video is not None:
processed_video = self.video_processor(videos=video, device=processing_device, return_tensors="pt")
pixel_values_video = processed_video.pixel_values_videos[0]
video_height = processed_video.original_sizes[0][0]
video_width = processed_video.original_sizes[0][1]
inference_session = Sam3VideoInferenceSession(
video=pixel_values_video,
video_height=video_height,
video_width=video_width,
inference_device=inference_device,
video_storage_device=video_storage_device,
inference_state_device=inference_state_device,
dtype=dtype,
max_vision_features_cache_size=max_vision_features_cache_size,
)
return inference_session
def _apply_non_overlapping_constraints(self, pred_masks):
"""
Apply non-overlapping constraints to the object scores in pred_masks. Here we
keep only the highest scoring object at each spatial location in pred_masks.
"""
batch_size = pred_masks.size(0)
if batch_size == 1:
return pred_masks
device = pred_masks.device
# "max_obj_inds": object index of the object with the highest score at each location
max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
# "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
keep = max_obj_inds == batch_obj_inds
# suppress overlapping regions' scores below -10.0 so that the foreground regions
# don't overlap (here sigmoid(-10.0)=4.5398e-05)
pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
return pred_masks
def _apply_object_wise_non_overlapping_constraints(
self,
pred_masks,
obj_scores,
background_value=-10.0,
prompt_ids=None,
):
"""
Applies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region).
Constraints are enforced independently for each prompt group when `prompt_ids` are provided.
"""
if prompt_ids is None:
return self._apply_object_wise_non_overlapping_constraints_impl(pred_masks, obj_scores, background_value)
if len(prompt_ids) != pred_masks.size(0):
raise ValueError("prompt_ids must have the same length as pred_masks")
pred_masks_grouped = pred_masks.clone()
prompt_ids_tensor = torch.tensor(prompt_ids, device=pred_masks.device, dtype=torch.long)
for prompt_id in prompt_ids_tensor.unique(sorted=True):
indices = torch.nonzero(prompt_ids_tensor == prompt_id, as_tuple=True)[0]
if indices.numel() == 0:
continue
prompt_masks = self._apply_object_wise_non_overlapping_constraints_impl(
pred_masks_grouped[indices],
obj_scores[indices],
background_value,
)
pred_masks_grouped[indices] = prompt_masks.to(pred_masks_grouped.dtype)
return pred_masks_grouped
def _apply_object_wise_non_overlapping_constraints_impl(self, pred_masks, obj_scores, background_value=-10.0):
pred_masks_single_score = torch.where(pred_masks > 0, obj_scores[..., None, None], background_value)
pixel_level_non_overlapping_masks = self._apply_non_overlapping_constraints(pred_masks_single_score)
pred_masks = torch.where(
pixel_level_non_overlapping_masks > 0,
pred_masks,
torch.clamp(pred_masks, max=background_value),
)
return pred_masks.to(pred_masks_single_score.dtype)
def postprocess_outputs(
self,
inference_session,
model_outputs,
original_sizes: Optional[Union[list[list[float]], torch.Tensor]] = None,
):
"""
Post-process model outputs to get final masks, boxes, and scores.
Args:
inference_session (`Sam3VideoInferenceSession`):
The inference session object.
model_outputs (`Sam3VideoSegmentationOutput`):
The raw model output from `Sam3VideoModel.forward()`.
original_sizes (`list[list[float]]` or `torch.Tensor`, *optional*):
Optional original frame sizes [height, width]. Required for streaming inference
when video_height/video_width are not set in the session.
Returns:
`dict`: A dictionary containing the following keys:
- **object_ids** (`torch.Tensor` of shape `(num_objects,)`): Object IDs for each detected object.
- **scores** (`torch.Tensor` of shape `(num_objects,)`): Detection scores for each object.
- **boxes** (`torch.Tensor` of shape `(num_objects, 4)`): Bounding boxes in XYXY format
(top_left_x, top_left_y, bottom_right_x, bottom_right_y).
- **masks** (`torch.Tensor` of shape `(num_objects, height, width)`): Binary segmentation masks
for each object at the original video resolution.
- **prompt_to_obj_ids** (`dict[str, list[int]]`): Mapping from prompt text to list of
object IDs detected by that prompt.
"""
obj_id_to_mask = model_outputs["obj_id_to_mask"] # low res masks (1, H_low, W_low)
curr_obj_ids = sorted(obj_id_to_mask.keys())
# Get video dimensions - use original_sizes for streaming inference if session doesn't have them
if inference_session.video_height is not None and inference_session.video_width is not None:
H_video, W_video = inference_session.video_height, inference_session.video_width
elif original_sizes is not None:
if isinstance(original_sizes, torch.Tensor):
original_sizes = original_sizes.cpu().tolist()
# original_sizes is a list of [height, width] pairs, take the first one
if isinstance(original_sizes[0], list):
H_video, W_video = int(original_sizes[0][0]), int(original_sizes[0][1])
else:
H_video, W_video = int(original_sizes[0]), int(original_sizes[1])
else:
raise ValueError(
"Either inference_session.video_height/video_width must be set, "
"or original_sizes must be provided for streaming inference."
)
if len(curr_obj_ids) == 0:
out_obj_ids = torch.zeros(0, dtype=torch.int64)
out_probs = torch.zeros(0, dtype=torch.float32)
out_binary_masks = torch.zeros(0, H_video, W_video, dtype=torch.bool)
out_boxes_xyxy = torch.zeros(0, 4, dtype=torch.float32)
else:
out_obj_ids = torch.tensor(curr_obj_ids, dtype=torch.int64)
out_probs = torch.tensor([model_outputs["obj_id_to_score"][obj_id] for obj_id in curr_obj_ids])
out_tracker_probs = torch.tensor(
[model_outputs["obj_id_to_tracker_score"].get(obj_id, 0.0) for obj_id in curr_obj_ids]
)
# Interpolate low-res masks to video resolution
low_res_masks = torch.cat([obj_id_to_mask[obj_id] for obj_id in curr_obj_ids], dim=0) # (N, H_low, W_low)
# Add channel dimension for interpolation: (N, H, W) -> (N, 1, H, W)
out_binary_masks = torch.nn.functional.interpolate(
low_res_masks.unsqueeze(1),
size=(H_video, W_video),
mode="bilinear",
align_corners=False,
).squeeze(1) # (N, H_video, W_video)
out_binary_masks = out_binary_masks > 0
assert out_binary_masks.dtype == torch.bool
keep = out_binary_masks.any(dim=(1, 2)).cpu() # remove masks with 0 areas
# hide outputs for those object IDs in `obj_ids_to_hide`
obj_ids_to_hide = []
if model_outputs["suppressed_obj_ids"] is not None:
obj_ids_to_hide.extend(list(model_outputs["suppressed_obj_ids"]))
if len(inference_session.hotstart_removed_obj_ids) > 0:
obj_ids_to_hide.extend(list(inference_session.hotstart_removed_obj_ids))
if len(obj_ids_to_hide) > 0:
obj_ids_to_hide_t = torch.tensor(obj_ids_to_hide, dtype=torch.int64)
keep &= ~torch.isin(out_obj_ids, obj_ids_to_hide_t)
# slice those valid entries from the original outputs
keep_idx = torch.nonzero(keep, as_tuple=True)[0]
keep_idx_gpu = keep_idx.pin_memory().to(device=out_binary_masks.device, non_blocking=True)
out_obj_ids = torch.index_select(out_obj_ids, 0, keep_idx)
out_probs = torch.index_select(out_probs, 0, keep_idx)
out_tracker_probs = torch.index_select(out_tracker_probs, 0, keep_idx)
out_binary_masks = torch.index_select(out_binary_masks, 0, keep_idx_gpu)
out_boxes_xyxy = masks_to_boxes(out_binary_masks)
# Apply non-overlapping constraints on the existing masklets.
# Constraints are enforced independently per prompt group.
if out_binary_masks.shape[0] > 1:
assert len(out_binary_masks) == len(out_tracker_probs)
prompt_ids_filtered = [
inference_session.obj_id_to_prompt_id[int(obj_id)] for obj_id in out_obj_ids.tolist()
]
out_binary_masks = (
self._apply_object_wise_non_overlapping_constraints(
out_binary_masks.unsqueeze(1),
out_tracker_probs.unsqueeze(1).to(out_binary_masks.device),
background_value=0,
prompt_ids=prompt_ids_filtered,
).squeeze(1)
) > 0
# Build prompt_to_obj_ids mapping: group object IDs by their associated prompt text.
prompt_to_obj_ids = {}
for obj_id in out_obj_ids.tolist():
prompt_id = inference_session.obj_id_to_prompt_id[obj_id]
prompt_text = inference_session.prompts[prompt_id]
prompt_to_obj_ids.setdefault(prompt_text, []).append(obj_id)
outputs = {
"object_ids": out_obj_ids,
"scores": out_probs,
"boxes": out_boxes_xyxy,
"masks": out_binary_masks,
"prompt_to_obj_ids": prompt_to_obj_ids,
}
return outputs
__all__ = ["Sam3VideoProcessor"]
| Sam3VideoProcessor |
python | openai__openai-python | src/openai/types/graders/text_similarity_grader_param.py | {
"start": 225,
"end": 1045
} | class ____(TypedDict, total=False):
evaluation_metric: Required[
Literal[
"cosine",
"fuzzy_match",
"bleu",
"gleu",
"meteor",
"rouge_1",
"rouge_2",
"rouge_3",
"rouge_4",
"rouge_5",
"rouge_l",
]
]
"""The evaluation metric to use.
One of `cosine`, `fuzzy_match`, `bleu`, `gleu`, `meteor`, `rouge_1`, `rouge_2`,
`rouge_3`, `rouge_4`, `rouge_5`, or `rouge_l`.
"""
input: Required[str]
"""The text being graded."""
name: Required[str]
"""The name of the grader."""
reference: Required[str]
"""The text being graded against."""
type: Required[Literal["text_similarity"]]
"""The type of grader."""
| TextSimilarityGraderParam |
python | pyca__cryptography | tests/utils.py | {
"start": 30796,
"end": 32183
} | class ____:
def __init__(self, testfiledata, testgroup, testcase):
self.testfiledata = testfiledata
self.testgroup = testgroup
self.testcase = testcase
def __repr__(self):
return "<WycheproofTest({!r}, {!r}, {!r}, tcId={})>".format(
self.testfiledata,
self.testgroup,
self.testcase,
self.testcase["tcId"],
)
@property
def valid(self) -> bool:
return self.testcase["result"] == "valid"
@property
def acceptable(self) -> bool:
return self.testcase["result"] == "acceptable"
@property
def invalid(self) -> bool:
return self.testcase["result"] == "invalid"
def has_flag(self, flag: str) -> bool:
return flag in self.testcase["flags"]
def cache_value_to_group(self, cache_key: str, func):
cache_val = self.testgroup.get(cache_key)
if cache_val is not None:
return cache_val
self.testgroup[cache_key] = cache_val = func()
return cache_val
def load_wycheproof_tests(wycheproof, test_file, subdir):
path = os.path.join(wycheproof, subdir, test_file)
with open(path) as f:
data = json.load(f)
for group in data.pop("testGroups"):
cases = group.pop("tests")
for c in cases:
yield WycheproofTest(data, group, c)
| WycheproofTest |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 82786,
"end": 83706
} | class ____:
# Base halide target to use for CPU devices
cpu_target = "host"
# Base halide target to use for CUDA devices
gpu_target = "host-cuda"
# Halide autoscheduler to use, choices are:
# "Anderson2021" (gpu-only), "Li2018", "Adams2019" (cpu-only), or "Mullapudi2016" (cpu-only)
scheduler_cuda: Literal["Anderson2021", "Li2018", "Adams2019", "Mullapudi2016"] = (
"Anderson2021"
)
scheduler_cpu: Literal["Anderson2021", "Li2018", "Adams2019", "Mullapudi2016"] = (
"Adams2019"
)
# Controls `no_asserts` flag passed to Halide target (warning: can false positive)
asserts = False
# Controls `debug` flag passed to Halide target
debug = False
# Enable (or fallback on) scan kernels such as cumsum
# Halide autoschedulers struggle with these kernels
scan_kernels = False
# create a directory containing lots of debug information
| halide |
python | scrapy__scrapy | scrapy/core/http2/agent.py | {
"start": 4087,
"end": 5570
} | class ____:
def __init__(
self,
reactor: ReactorBase,
pool: H2ConnectionPool,
context_factory: BrowserLikePolicyForHTTPS = BrowserLikePolicyForHTTPS(),
connect_timeout: float | None = None,
bind_address: bytes | None = None,
) -> None:
self._reactor = reactor
self._pool = pool
self._context_factory = AcceptableProtocolsContextFactory(
context_factory, acceptable_protocols=[b"h2"]
)
self.endpoint_factory = _StandardEndpointFactory(
self._reactor, self._context_factory, connect_timeout, bind_address
)
def get_endpoint(self, uri: URI) -> HostnameEndpoint:
return self.endpoint_factory.endpointForURI(uri)
def get_key(self, uri: URI) -> ConnectionKeyT:
"""
Arguments:
uri - URI obtained directly from request URL
"""
return uri.scheme, uri.host, uri.port
def request(self, request: Request, spider: Spider) -> Deferred[Response]:
uri = URI.fromBytes(bytes(request.url, encoding="utf-8"))
try:
endpoint = self.get_endpoint(uri)
except SchemeNotSupported:
return defer.fail(Failure())
key = self.get_key(uri)
d: Deferred[H2ClientProtocol] = self._pool.get_connection(key, uri, endpoint)
d2: Deferred[Response] = d.addCallback(
lambda conn: conn.request(request, spider)
)
return d2
| H2Agent |
python | walkccc__LeetCode | solutions/2284. Sender With Largest Word Count/2284.py | {
"start": 0,
"end": 563
} | class ____:
def largestWordCount(self, messages: list[str], senders: list[str]) -> str:
n = len(messages)
ans = ''
maxWordsSent = 0
count = collections.Counter() # [sender, # Words sent]
for message, sender in zip(messages, senders):
wordsCount = message.count(' ') + 1
count[sender] += wordsCount
numWordsSent = count[sender]
if numWordsSent > maxWordsSent:
ans = sender
maxWordsSent = numWordsSent
elif numWordsSent == maxWordsSent and sender > ans:
ans = sender
return ans
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-tableau/dagster_tableau/resources.py | {
"start": 18464,
"end": 19329
} | class ____(BaseTableauClient):
"""Represents a client for Tableau Cloud and provides utilities
to interact with the Tableau API.
"""
def __init__(
self,
connected_app_client_id: str,
connected_app_secret_id: str,
connected_app_secret_value: str,
username: str,
site_name: str,
pod_name: str,
):
self.pod_name = pod_name
super().__init__(
connected_app_client_id=connected_app_client_id,
connected_app_secret_id=connected_app_secret_id,
connected_app_secret_value=connected_app_secret_value,
username=username,
site_name=site_name,
)
@property
def base_url(self) -> str:
"""Base URL for Tableau Cloud."""
return f"https://{self.pod_name}.online.tableau.com"
@beta
| TableauCloudClient |
python | pytorch__pytorch | torch/_inductor/cache.py | {
"start": 14046,
"end": 14823
} | class ____(OnDiskCache[Key, Value]):
"""
Inductor-specific on-disk cache implementation.
Uses a custom base directory for Inductor cache files.
"""
def __init__(self: Self) -> None:
"""
Initialize an inductor on-disk cache instance.
Sets the cache directory name to "inductor_on_disk_cache".
"""
super().__init__("inductor_on_disk_cache")
@cached_property
def base_dir(self: Self) -> Path:
"""
Get the base directory for the Inductor cache.
Returns:
Path: The base directory path for Inductor cache files.
"""
from torch._inductor.runtime.runtime_utils import default_cache_dir
return Path(default_cache_dir(), "cache", self.name)
| InductorOnDiskCache |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 4803,
"end": 4912
} | class ____(UrlError):
code = 'url.scheme'
msg_template = 'invalid or missing URL scheme'
| UrlSchemeError |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 144563,
"end": 145369
} | class ____(OutputSpec):
# This is janky, I figured out what fields to populate by just running
# the model I was interested in and adding properties/methods as needed.
# This doesn't inherit from Layout because Layout assumes you have stuff
# like sizes, but I don't really have anything here.
#
# If you have an ir.Node with NoneLayout, you probably need to setup
# dependencies manually in scheduler
device: Optional[torch.device]
size: list[int] = dataclasses.field(default_factory=lambda: [0])
stride: list[int] = dataclasses.field(default_factory=lambda: [0])
def storage_size(self) -> int:
return 0
def as_fixed(self) -> OutputSpec:
return self
def get_device(self) -> Optional[torch.device]:
return self.device
| NoneLayout |
python | FactoryBoy__factory_boy | tests/test_helpers.py | {
"start": 108,
"end": 1980
} | class ____(unittest.TestCase):
"""Tests for the 'factory.debug()' helper."""
def test_default_logger(self):
stream1 = io.StringIO()
stream2 = io.StringIO()
logger = logging.getLogger('factory.test')
h = logging.StreamHandler(stream1)
h.setLevel(logging.INFO)
logger.addHandler(h)
# Non-debug: no text gets out
logger.debug("Test")
self.assertEqual('', stream1.getvalue())
with helpers.debug(stream=stream2):
# Debug: text goes to new stream only
logger.debug("Test2")
self.assertEqual('', stream1.getvalue())
self.assertEqual("Test2\n", stream2.getvalue())
def test_alternate_logger(self):
stream1 = io.StringIO()
stream2 = io.StringIO()
l1 = logging.getLogger('factory.test')
l2 = logging.getLogger('factory.foo')
h = logging.StreamHandler(stream1)
h.setLevel(logging.DEBUG)
l2.addHandler(h)
# Non-debug: no text gets out
l1.debug("Test")
self.assertEqual('', stream1.getvalue())
l2.debug("Test")
self.assertEqual('', stream1.getvalue())
with helpers.debug('factory.test', stream=stream2):
# Debug: text goes to new stream only
l1.debug("Test2")
l2.debug("Test3")
self.assertEqual("", stream1.getvalue())
self.assertEqual("Test2\n", stream2.getvalue())
def test_restores_logging_on_error(self):
class MyException(Exception):
pass
stream = io.StringIO()
try:
with helpers.debug(stream=stream):
raise MyException
except MyException:
logger = logging.getLogger('factory')
self.assertEqual(logger.level, logging.NOTSET)
self.assertEqual(logger.handlers, [])
| DebugTest |
python | Textualize__textual | src/textual/css/tokenizer.py | {
"start": 2994,
"end": 3114
} | class ____(TokenError):
"""Indicates that the text being tokenized ended prematurely."""
@rich.repr.auto
| UnexpectedEnd |
python | tensorflow__tensorflow | tensorflow/python/keras/saving/saved_model/serialized_attributes.py | {
"start": 12096,
"end": 12538
} | class ____(SerializedAttributes.with_attributes(
'ModelAttributes',
copy_from=[LayerAttributes])):
"""Model checkpointable objects + functions that are saved to the SavedModel.
List of all attributes:
All attributes from LayerAttributes (including CommonEndpoints)
"""
# TODO(kathywu): Add attributes `compile_losses` and `compile_metrics`, which
# list all losses and metrics defined by `model.compile`.
| ModelAttributes |
python | python-visualization__folium | folium/map.py | {
"start": 15681,
"end": 18804
} | class ____(MacroElement):
"""Create a Popup instance that can be linked to a Layer.
Parameters
----------
html: string or Element
Content of the Popup.
parse_html: bool, default False
True if the popup is a template that needs to the rendered first.
max_width: int for pixels or text for percentages, default '100%'
The maximal width of the popup.
show: bool, default False
True renders the popup open on page load.
sticky: bool, default False
True prevents map and other popup clicks from closing.
lazy: bool, default False
True only loads the Popup content when clicking on the Marker.
"""
_template = Template(
"""
var {{this.get_name()}} = L.popup({{ this.options|tojavascript }});
{% for name, element in this.html._children.items() %}
{% if this.lazy %}
{{ this._parent.get_name() }}.once('click', function() {
{{ this.get_name() }}.setContent($(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0]);
});
{% else %}
var {{ name }} = $(`{{ element.render(**kwargs).replace('\\n',' ') }}`)[0];
{{ this.get_name() }}.setContent({{ name }});
{% endif %}
{% endfor %}
{{ this._parent.get_name() }}.bindPopup({{ this.get_name() }})
{% if this.show %}.openPopup(){% endif %};
{% for name, element in this.script._children.items() %}
{{element.render()}}
{% endfor %}
"""
) # noqa
def __init__(
self,
html: Union[str, Element, None] = None,
parse_html: bool = False,
max_width: Union[str, int] = "100%",
show: bool = False,
sticky: bool = False,
lazy: bool = False,
**kwargs: TypeJsonValue,
):
super().__init__()
self._name = "Popup"
self.header = Element()
self.html = Element()
self.script = Element()
self.header._parent = self
self.html._parent = self
self.script._parent = self
script = not parse_html
if isinstance(html, Element):
self.html.add_child(html)
elif isinstance(html, str):
html = escape_backticks(html)
self.html.add_child(Html(html, script=script))
self.show = show
self.lazy = lazy
self.options = remove_empty(
max_width=max_width,
autoClose=False if show or sticky else None,
closeOnClick=False if sticky else None,
**kwargs,
)
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
for name, child in self._children.items():
child.render(**kwargs)
figure = self.get_root()
assert isinstance(
figure, Figure
), "You cannot render this Element if it is not in a Figure."
figure.script.add_child(
Element(self._template.render(this=self, kwargs=kwargs)),
name=self.get_name(),
)
| Popup |
python | scrapy__scrapy | scrapy/extensions/corestats.py | {
"start": 430,
"end": 2248
} | class ____:
def __init__(self, stats: StatsCollector):
self.stats: StatsCollector = stats
self.start_time: datetime | None = None
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
assert crawler.stats
o = cls(crawler.stats)
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
crawler.signals.connect(o.spider_closed, signal=signals.spider_closed)
crawler.signals.connect(o.item_scraped, signal=signals.item_scraped)
crawler.signals.connect(o.item_dropped, signal=signals.item_dropped)
crawler.signals.connect(o.response_received, signal=signals.response_received)
return o
def spider_opened(self, spider: Spider) -> None:
self.start_time = datetime.now(tz=timezone.utc)
self.stats.set_value("start_time", self.start_time)
def spider_closed(self, spider: Spider, reason: str) -> None:
assert self.start_time is not None
finish_time = datetime.now(tz=timezone.utc)
elapsed_time = finish_time - self.start_time
elapsed_time_seconds = elapsed_time.total_seconds()
self.stats.set_value("elapsed_time_seconds", elapsed_time_seconds)
self.stats.set_value("finish_time", finish_time)
self.stats.set_value("finish_reason", reason)
def item_scraped(self, item: Any, spider: Spider) -> None:
self.stats.inc_value("item_scraped_count")
def response_received(self, spider: Spider) -> None:
self.stats.inc_value("response_received_count")
def item_dropped(self, item: Any, spider: Spider, exception: BaseException) -> None:
reason = exception.__class__.__name__
self.stats.inc_value("item_dropped_count")
self.stats.inc_value(f"item_dropped_reasons_count/{reason}")
| CoreStats |
python | astropy__astropy | astropy/io/ascii/__init__.py | {
"start": 1341,
"end": 1930
} | class ____(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.io.ascii`.
"""
guess_limit_lines = _config.ConfigItem(
10000,
"When guessing the format of a table, this is the number of lines that "
"will be used for initial guessing. If the reading succeeds based on this "
"number of lines, then reading the full table will be attempted. If the reading "
"based on the subset of lines fails, the format will no longer be considered. "
"This can be set to `None` to disable the limit",
)
conf = Conf()
| Conf |
python | agronholm__apscheduler | src/apscheduler/abc.py | {
"start": 1621,
"end": 2565
} | class ____(metaclass=ABCMeta):
"""Interface for classes that implement (de)serialization."""
__slots__ = ()
@abstractmethod
def serialize(self, obj: object) -> bytes:
"""
Turn the given object into a bytestring.
Must handle the serialization of at least any JSON type, plus the following:
* ``datetime.date`` (using :meth:`datetime.date.isoformat`)
* ``datetime.timedelta`` (using :meth:`datetime.timedelta.total_seconds`)
* ``datetime.tzinfo`` (by extracting the time zone name)
:return: a bytestring that can be later restored using :meth:`deserialize`
"""
@abstractmethod
def deserialize(self, serialized: bytes) -> Any:
"""
Restore a previously serialized object from bytestring
:param serialized: a bytestring previously received from :meth:`serialize`
:return: a copy of the original object
"""
| Serializer |
python | pyca__cryptography | src/cryptography/hazmat/decrepit/ciphers/algorithms.py | {
"start": 1097,
"end": 1387
} | class ____(BlockCipherAlgorithm):
name = "Blowfish"
block_size = 64
key_sizes = frozenset(range(32, 449, 8))
def __init__(self, key: bytes):
self.key = _verify_key_size(self, key)
@property
def key_size(self) -> int:
return len(self.key) * 8
| Blowfish |
python | matplotlib__matplotlib | galleries/examples/user_interfaces/embedding_in_wx3_sgskip.py | {
"start": 2837,
"end": 4490
} | class ____(wx.App):
def OnInit(self):
xrcfile = cbook.get_sample_data('embedding_in_wx3.xrc',
asfileobj=False)
print('loading', xrcfile)
self.res = xrc.XmlResource(xrcfile)
# main frame and panel ---------
self.frame = self.res.LoadFrame(None, "MainFrame")
self.panel = xrc.XRCCTRL(self.frame, "MainPanel")
# matplotlib panel -------------
# container for matplotlib panel (I like to make a container
# panel for our panel so I know where it'll go when in XRCed.)
plot_container = xrc.XRCCTRL(self.frame, "plot_container_panel")
sizer = wx.BoxSizer(wx.VERTICAL)
# matplotlib panel itself
self.plotpanel = PlotPanel(plot_container)
self.plotpanel.init_plot_data()
# wx boilerplate
sizer.Add(self.plotpanel, 1, wx.EXPAND)
plot_container.SetSizer(sizer)
# whiz button ------------------
whiz_button = xrc.XRCCTRL(self.frame, "whiz_button")
whiz_button.Bind(wx.EVT_BUTTON, self.plotpanel.OnWhiz)
# bang button ------------------
bang_button = xrc.XRCCTRL(self.frame, "bang_button")
bang_button.Bind(wx.EVT_BUTTON, self.OnBang)
# final setup ------------------
self.frame.Show()
self.SetTopWindow(self.frame)
return True
def OnBang(self, event):
bang_count = xrc.XRCCTRL(self.frame, "bang_count")
bangs = bang_count.GetValue()
bangs = int(bangs) + 1
bang_count.SetValue(str(bangs))
if __name__ == '__main__':
app = MyApp()
app.MainLoop()
| MyApp |
python | pallets__click | tests/test_options.py | {
"start": 57046,
"end": 57141
} | class ____(enum.Flag):
RED = enum.auto()
GREEN = enum.auto()
BLUE = enum.auto()
| Color |
python | milvus-io__pymilvus | pymilvus/client/abstract.py | {
"start": 7480,
"end": 11160
} | class ____:
def __init__(self, raw: Any):
self._raw = raw
self.collection_name = None
self.description = None
self.params = {}
self.fields = []
self.struct_array_fields = []
self.functions = []
self.statistics = {}
self.auto_id = False # auto_id is not in collection level any more later
self.aliases = []
self.collection_id = 0
self.consistency_level = DEFAULT_CONSISTENCY_LEVEL # by default
self.properties = {}
self.num_shards = 0
self.num_partitions = 0
self.enable_dynamic_field = False
self.created_timestamp = 0
self.update_timestamp = 0
if self._raw:
self.__pack(self._raw)
def __pack(self, raw: Any):
self.collection_name = raw.schema.name
self.description = raw.schema.description
self.aliases = list(raw.aliases)
self.collection_id = raw.collectionID
self.num_shards = raw.shards_num
self.num_partitions = raw.num_partitions
self.created_timestamp = raw.created_timestamp
self.update_timestamp = raw.update_timestamp
# keep compatible with older Milvus
try:
self.consistency_level = raw.consistency_level
except Exception:
self.consistency_level = DEFAULT_CONSISTENCY_LEVEL
try:
self.enable_dynamic_field = raw.schema.enable_dynamic_field
except Exception:
self.enable_dynamic_field = False
# TODO: extra_params here
# for kv in raw.extra_params:
self.fields = [FieldSchema(f) for f in raw.schema.fields]
self.struct_array_fields = [
StructArrayFieldSchema(f) for f in raw.schema.struct_array_fields
]
self.functions = [FunctionSchema(f) for f in raw.schema.functions]
function_output_field_names = [f for fn in self.functions for f in fn.output_field_names]
for field in self.fields:
if field.name in function_output_field_names:
field.is_function_output = True
# for s in raw.statistics:
for p in raw.properties:
self.properties[p.key] = p.value
@classmethod
def _rewrite_schema_dict(cls, schema_dict: Dict):
fields = schema_dict.get("fields", [])
if not fields:
return
for field_dict in fields:
if field_dict.get("auto_id", None) is not None:
schema_dict["auto_id"] = field_dict["auto_id"]
return
def dict(self):
if not self._raw:
return {}
_dict = {
"collection_name": self.collection_name,
"auto_id": self.auto_id,
"num_shards": self.num_shards,
"description": self.description,
"fields": [f.dict() for f in self.fields],
"struct_array_fields": [f.dict() for f in self.struct_array_fields],
"functions": [f.dict() for f in self.functions],
"aliases": self.aliases,
"collection_id": self.collection_id,
"consistency_level": self.consistency_level,
"properties": self.properties,
"num_partitions": self.num_partitions,
"enable_dynamic_field": self.enable_dynamic_field,
}
if self.created_timestamp != 0:
_dict["created_timestamp"] = self.created_timestamp
if self.update_timestamp != 0:
_dict["update_timestamp"] = self.update_timestamp
self._rewrite_schema_dict(_dict)
return _dict
def __str__(self):
return self.dict().__str__()
| CollectionSchema |
python | PrefectHQ__prefect | tests/test_serializers.py | {
"start": 1493,
"end": 3558
} | class ____:
@pytest.fixture(autouse=True)
def restore_dispatch_registry(self):
# Clears serializers defined in tests below to prevent warnings on collision
before = get_registry_for_type(Serializer).copy()
yield
registry = get_registry_for_type(Serializer)
registry.clear()
registry.update(before)
def test_serializers_do_not_allow_extra_fields(self):
class Foo(Serializer):
type: str = "foo"
def dumps(self, obj):
pass
def loads(self, obj):
pass
with pytest.raises(ValidationError):
Foo(x="test")
def test_serializers_can_be_created_by_dict(self):
class Foo(BaseModel):
serializer: Serializer
class Bar(Serializer):
type: str = "bar"
def dumps(self, obj):
pass
def loads(self, obj):
pass
model = Foo(serializer={"type": "bar"})
assert isinstance(model.serializer, Bar)
def test_serializers_can_be_created_by_object(self):
class Foo(BaseModel):
serializer: Serializer
class Bar(Serializer):
type: str = "bar"
def dumps(self, obj):
pass
def loads(self, obj):
pass
model = Foo(serializer=Bar())
assert isinstance(model.serializer, Bar)
def test_serializers_can_be_created_by_type_string(self):
class Foo(BaseModel):
serializer: Serializer
@field_validator("serializer", mode="before")
def cast_type_to_dict(cls, value):
if isinstance(value, str):
return {"type": value}
return value
class Bar(Serializer):
type: str = "bar"
def dumps(self, obj):
pass
def loads(self, obj):
pass
model = Foo(serializer="bar")
assert isinstance(model.serializer, Bar)
| TestBaseSerializer |
python | dask__distributed | distributed/shuffle/_scheduler_plugin.py | {
"start": 1058,
"end": 23114
} | class ____(SchedulerPlugin):
"""
Shuffle plugin for the scheduler
This coordinates the individual worker plugins to ensure correctness
and collects heartbeat messages for the dashboard.
See Also
--------
ShuffleWorkerPlugin
"""
scheduler: Scheduler
active_shuffles: dict[ShuffleId, SchedulerShuffleState]
heartbeats: defaultdict[ShuffleId, dict]
_shuffles: defaultdict[ShuffleId, set[SchedulerShuffleState]]
_archived_by_stimulus: defaultdict[str, set[SchedulerShuffleState]]
_shift_counter: itertools.count[int]
def __init__(self, scheduler: Scheduler):
self.scheduler = scheduler
self.scheduler.handlers.update(
{
"shuffle_barrier": self.barrier,
"shuffle_get": self.get,
"shuffle_get_or_create": self.get_or_create,
"shuffle_restrict_task": self.restrict_task,
}
)
self.heartbeats = defaultdict(lambda: defaultdict(dict))
self.active_shuffles = {}
self.scheduler.add_plugin(self, name="shuffle")
self._shuffles = defaultdict(set)
self._archived_by_stimulus = defaultdict(set)
self._shift_counter = itertools.count()
async def start(self, scheduler: Scheduler) -> None:
worker_plugin = ShuffleWorkerPlugin()
await self.scheduler.register_worker_plugin(
None, dumps(worker_plugin), name="shuffle", idempotent=False
)
def shuffle_ids(self) -> set[ShuffleId]:
return set(self.active_shuffles)
async def barrier(self, id: ShuffleId, run_id: int, consistent: bool) -> None:
shuffle = self.active_shuffles[id]
if shuffle.run_id != run_id:
raise ValueError(f"{run_id=} does not match {shuffle}")
if not consistent:
logger.warning(
"Shuffle %s restarted due to data inconsistency during barrier",
shuffle.id,
)
return self._restart_shuffle(
shuffle.id,
self.scheduler,
stimulus_id=f"p2p-barrier-inconsistent-{time()}",
)
msg = {"op": "shuffle_inputs_done", "shuffle_id": id, "run_id": run_id}
workers = list(shuffle.participating_workers)
no_progress = 0
while workers:
res = await self.scheduler.broadcast(
msg=msg,
workers=workers,
on_error="return",
)
before = len(workers)
workers = []
for w, r in res.items():
if r is None:
continue
if isinstance(r, OSError):
workers.append(w)
else:
raise RuntimeError(
f"Unexpected error encountered during P2P barrier: {r!r}"
)
workers = [w for w, r in res.items() if r is not None]
if workers:
logger.warning(
"Failure during broadcast of %s, retrying.",
shuffle.id,
)
if any(w not in self.scheduler.workers for w in workers):
if not shuffle.archived:
# If the shuffle is not yet archived, this could mean that the barrier task fails
# before the P2P restarting mechanism can kick in.
raise P2PIllegalStateError(
"Expected shuffle to be archived if participating worker is not known by scheduler"
)
raise RuntimeError(
f"Worker {workers} left during shuffle {shuffle}"
)
await asyncio.sleep(0.1)
if len(workers) == before:
no_progress += 1
if no_progress >= 3:
raise RuntimeError(
f"""Broadcast not making progress for {shuffle}.
Aborting. This is possibly due to overloaded
workers. Increasing config
`distributed.comm.timeouts.connect` timeout may
help."""
)
def restrict_task(
self, id: ShuffleId, run_id: int, key: Key, worker: str
) -> OKMessage | ErrorMessage:
try:
shuffle = self.active_shuffles[id]
if shuffle.run_id > run_id:
raise P2PConsistencyError(
f"Request stale, expected {run_id=} for {shuffle}"
)
elif shuffle.run_id < run_id:
raise P2PConsistencyError(
f"Request invalid, expected {run_id=} for {shuffle}"
)
ts = self.scheduler.tasks[key]
self._set_restriction(ts, worker)
return {"status": "OK"}
except P2PConsistencyError as e:
return error_message(e)
def heartbeat(self, ws: WorkerState, data: dict) -> None:
for shuffle_id, d in data.items():
if shuffle_id in self.shuffle_ids():
self.heartbeats[shuffle_id][ws.address].update(d)
def get(self, id: ShuffleId, worker: str) -> RunSpecMessage | ErrorMessage:
try:
try:
run_spec = self._get(id, worker)
return {"status": "OK", "run_spec": ToPickle(run_spec)}
except KeyError as e:
raise P2PConsistencyError(
f"No active shuffle with {id=!r} found"
) from e
except P2PConsistencyError as e:
return error_message(e)
def _get(self, id: ShuffleId, worker: str) -> ShuffleRunSpec:
if worker not in self.scheduler.workers:
# This should never happen
raise P2PConsistencyError(
f"Scheduler is unaware of this worker {worker!r}"
) # pragma: nocover
state = self.active_shuffles[id]
state.participating_workers.add(worker)
return state.run_spec
def _retrieve_spec(self, shuffle_id: ShuffleId) -> ShuffleSpec:
barrier_task_spec = self.scheduler.tasks[barrier_key(shuffle_id)].run_spec
assert isinstance(barrier_task_spec, P2PBarrierTask)
return barrier_task_spec.spec
def _create(self, shuffle_id: ShuffleId, key: Key, worker: str) -> ShuffleRunSpec:
# FIXME: The current implementation relies on the barrier task to be
# known by its name. If the name has been mangled, we cannot guarantee
# that the shuffle works as intended and should fail instead.
self._raise_if_barrier_unknown(shuffle_id)
self._raise_if_task_not_processing(key)
spec = self._retrieve_spec(shuffle_id)
worker_for = self._calculate_worker_for(spec)
self._ensure_output_tasks_are_non_rootish(spec)
state = spec.create_new_run(
worker_for=worker_for, span_id=self.scheduler.tasks[key].group.span_id
)
self.active_shuffles[shuffle_id] = state
self._shuffles[shuffle_id].add(state)
state.participating_workers.add(worker)
logger.warning(
"Shuffle %s initialized by task %r executed on worker %s",
shuffle_id,
key,
worker,
)
return state.run_spec
def get_or_create(
self,
shuffle_id: ShuffleId,
key: Key,
worker: str,
) -> RunSpecMessage | ErrorMessage:
try:
run_spec = self._get(shuffle_id, worker)
except P2PConsistencyError as e:
return error_message(e)
except KeyError:
try:
run_spec = self._create(shuffle_id, key, worker)
except P2PConsistencyError as e:
return error_message(e)
return {"status": "OK", "run_spec": ToPickle(run_spec)}
def _raise_if_barrier_unknown(self, id: ShuffleId) -> None:
key = barrier_key(id)
try:
self.scheduler.tasks[key]
except KeyError:
raise P2PConsistencyError(
f"Barrier task with key {key!r} does not exist. This may be caused by "
"task fusion during graph generation. Please let us know that you ran "
"into this by leaving a comment at distributed#7816."
)
def _raise_if_task_not_processing(self, key: Key) -> None:
task = self.scheduler.tasks[key]
if task.state != "processing":
raise P2PConsistencyError(
f"Expected {task} to be processing, is {task.state}."
)
def _calculate_worker_for(self, spec: ShuffleSpec) -> dict[Any, str]:
"""Pin the outputs of a P2P shuffle to specific workers.
The P2P implementation of a hash join combines the loading of shuffled output
partitions for the left and right side with the actual merge operation into a
single output task. As a consequence, we need to make sure that shuffles with
shared output tasks align on the output mapping.
Parameters
----------
id: ID of the shuffle to pin
output_partitions: Output partition IDs to pin
pick: Function that picks a worker given a partition ID and sequence of worker
.. note:
This function assumes that the barrier task and the output tasks share
the same worker restrictions.
"""
existing: dict[Any, str] = {}
shuffle_id = spec.id
barrier = self.scheduler.tasks[barrier_key(shuffle_id)]
if barrier.worker_restrictions:
workers = list(barrier.worker_restrictions)
else:
workers = list(self.scheduler.workers)
# Ensure homogeneous cluster utilization when there are multiple small,
# independent shuffles going on at the same time, e.g. due to partial rechunking
shift_by = next(self._shift_counter) % len(workers)
workers = workers[shift_by:] + workers[:shift_by]
# Check if this shuffle shares output tasks with a different shuffle that has
# already been initialized and needs to be taken into account when
# mapping output partitions to workers.
# Naively, you could delete this whole paragraph and just call
# spec.pick_worker; it would return two identical sets of results on both calls
# of this method... until the set of available workers changes between the two
# calls, which would cause misaligned shuffle outputs and a deadlock.
seen = {barrier}
for dependent in barrier.dependents:
for possible_barrier in dependent.dependencies:
if possible_barrier in seen:
continue
seen.add(possible_barrier)
if not (other_barrier_key := id_from_key(possible_barrier.key)):
continue
if not (shuffle := self.active_shuffles.get(other_barrier_key)):
continue
current_worker_for = shuffle.run_spec.worker_for
# This is a fail-safe for future three-ways merges. At the moment there
# should only ever be at most one other shuffle that shares output
# tasks, so existing will always be empty.
if existing: # pragma: nocover
for shared_key in existing.keys() & current_worker_for.keys():
if existing[shared_key] != current_worker_for[shared_key]:
raise P2PIllegalStateError(
f"Failed to initialize shuffle {spec.id} because "
"it cannot align output partition mappings between "
f"existing shuffles {seen}. "
f"Mismatch encountered for output partition {shared_key!r}: "
f"{existing[shared_key]} != {current_worker_for[shared_key]}."
)
existing.update(current_worker_for)
worker_for = {}
for partition in spec.output_partitions:
if (worker := existing.get(partition, None)) is None:
worker = spec.pick_worker(partition, workers)
worker_for[partition] = worker
return worker_for
def _ensure_output_tasks_are_non_rootish(self, spec: ShuffleSpec) -> None:
"""Output tasks are created without worker restrictions and run once with the
only purpose of setting the worker restriction and then raising Reschedule, and
then running again properly on the correct worker. It would be non-trivial to
set the worker restriction before they're first run due to potential task
fusion.
Most times, this lack of initial restrictions would cause output tasks to be
labelled as rootish on their first (very fast) run, which in turn would break
the design assumption that the worker-side queue of rootish tasks will last long
enough to cover the round-trip to the scheduler to receive more tasks, which in
turn would cause a measurable slowdown on the overall runtime of the shuffle
operation.
This method ensures that, given M output tasks and N workers, each worker-side
queue is pre-loaded with M/N output tasks which can be flushed very fast as
they all raise Reschedule() in quick succession.
See Also
--------
ShuffleRun._ensure_output_worker
"""
barrier = self.scheduler.tasks[barrier_key(spec.id)]
for dependent in barrier.dependents:
dependent._queueable = False
@log_errors()
def _set_restriction(self, ts: TaskState, worker: str) -> None:
if ts.annotations and "shuffle_original_restrictions" in ts.annotations:
# This may occur if multiple barriers share the same output task,
# e.g. in a hash join.
return
if ts.annotations is None:
ts.annotations = dict()
ts.annotations["shuffle_original_restrictions"] = (
ts.worker_restrictions.copy()
if ts.worker_restrictions is not None
else None
)
self.scheduler.set_restrictions({ts.key: {worker}})
@log_errors()
def _unset_restriction(self, ts: TaskState) -> None:
# shuffle_original_restrictions is only set if the task was first scheduled
# on the wrong worker
if (
ts.annotations is None
or "shuffle_original_restrictions" not in ts.annotations
):
return
original_restrictions = ts.annotations.pop("shuffle_original_restrictions")
self.scheduler.set_restrictions({ts.key: original_restrictions})
def _restart_recommendations(self, id: ShuffleId) -> Recs:
barrier_task = self.scheduler.tasks[barrier_key(id)]
recs: Recs = {}
for dt in barrier_task.dependents:
if dt.state == "erred":
return {}
recs.update({dt.key: "released"})
if barrier_task.state == "erred":
# This should never happen, a dependent of the barrier should already
# be `erred`
raise P2PIllegalStateError(
f"Expected dependents of {barrier_task=} to be 'erred' if "
"the barrier is."
) # pragma: no cover
recs.update({barrier_task.key: "released"})
for dt in barrier_task.dependencies:
if dt.state == "erred":
# This should never happen, a dependent of the barrier should already
# be `erred`
raise P2PIllegalStateError(
f"Expected barrier and its dependents to be "
f"'erred' if the barrier's dependency {dt} is."
) # pragma: no cover
recs.update({dt.key: "released"})
return recs
def _restart_shuffle(
self, id: ShuffleId, scheduler: Scheduler, *, stimulus_id: str
) -> None:
recs = self._restart_recommendations(id)
self.scheduler.transitions(recs, stimulus_id=stimulus_id)
self.scheduler.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)
logger.warning("Shuffle %s restarted due to stimulus '%s", id, stimulus_id)
def remove_worker(
self, scheduler: Scheduler, worker: str, *, stimulus_id: str, **kwargs: Any
) -> None:
"""Restart all active shuffles when a participating worker leaves the cluster.
.. note::
Due to the order of operations in :meth:`~Scheduler.remove_worker`, the
shuffle may have already been archived by
:meth:`~ShuffleSchedulerPlugin.transition`. In this case, the
``stimulus_id`` is used as a transaction identifier and all archived shuffles
with a matching `stimulus_id` are restarted.
"""
# If processing the transactions causes a task to get released, this
# removes the shuffle from self.active_shuffles. Therefore, we must iterate
# over a copy.
for shuffle_id, shuffle in self.active_shuffles.copy().items():
if worker not in shuffle.participating_workers:
continue
logger.debug(
"Worker %s removed during active shuffle %s due to stimulus '%s'",
worker,
shuffle_id,
stimulus_id,
)
exception = P2PConsistencyError(
f"Worker {worker} left during active {shuffle}"
)
self._fail_on_workers(shuffle, str(exception))
self._clean_on_scheduler(shuffle_id, stimulus_id)
for shuffle in self._archived_by_stimulus.get(stimulus_id, set()):
self._restart_shuffle(shuffle.id, scheduler, stimulus_id=stimulus_id)
def transition(
self,
key: Key,
start: TaskStateState,
finish: TaskStateState,
*args: Any,
stimulus_id: str,
**kwargs: Any,
) -> None:
"""Clean up scheduler and worker state once a shuffle becomes inactive."""
if finish not in ("released", "erred", "forgotten"):
return
if finish == "erred":
ts = self.scheduler.tasks[key]
for active_shuffle in self.active_shuffles.values():
# Log once per active shuffle
if active_shuffle._failed:
continue
# Log IFF a P2P task is the root cause
if ts.exception_blame != ts:
continue
barrier = self.scheduler.tasks[barrier_key(active_shuffle.id)]
if (
ts == barrier
or ts in barrier.dependents
or ts in barrier.dependencies
):
active_shuffle._failed = True
self.scheduler.log_event(
"p2p",
{
"action": "p2p-failed",
"shuffle": active_shuffle.id,
"stimulus": stimulus_id,
},
)
return
shuffle_id = id_from_key(key)
if not shuffle_id:
return
if shuffle := self.active_shuffles.get(shuffle_id):
self._fail_on_workers(shuffle, message=f"{shuffle} forgotten")
self._clean_on_scheduler(shuffle_id, stimulus_id=stimulus_id)
logger.debug(
"Shuffle %s forgotten because task %r transitioned to %s due to "
"stimulus '%s'",
shuffle_id,
key,
finish,
stimulus_id,
)
if finish == "forgotten":
shuffles = self._shuffles.pop(shuffle_id, set())
for shuffle in shuffles:
if shuffle._archived_by:
archived = self._archived_by_stimulus[shuffle._archived_by]
archived.remove(shuffle)
if not archived:
del self._archived_by_stimulus[shuffle._archived_by]
def valid_workers_downscaling(
self, scheduler: Scheduler, workers: list[WorkerState]
) -> list[WorkerState]:
all_participating_workers = set()
for shuffle in self.active_shuffles.values():
all_participating_workers.update(shuffle.participating_workers)
return [w for w in workers if w.address not in all_participating_workers]
def _fail_on_workers(self, shuffle: SchedulerShuffleState, message: str) -> None:
worker_msgs = {
worker: [
{
"op": "shuffle-fail",
"shuffle_id": shuffle.id,
"run_id": shuffle.run_id,
"message": message,
}
]
for worker in shuffle.participating_workers
}
self.scheduler.send_all({}, worker_msgs)
def _clean_on_scheduler(self, id: ShuffleId, stimulus_id: str) -> None:
shuffle = self.active_shuffles.pop(id)
logger.warning("Shuffle %s deactivated due to stimulus '%s'", id, stimulus_id)
if not shuffle._archived_by:
shuffle._archived_by = stimulus_id
self._archived_by_stimulus[stimulus_id].add(shuffle)
with contextlib.suppress(KeyError):
del self.heartbeats[id]
barrier_task = self.scheduler.tasks[barrier_key(id)]
for dt in barrier_task.dependents:
self._unset_restriction(dt)
def restart(self, scheduler: Scheduler) -> None:
self.active_shuffles.clear()
self.heartbeats.clear()
self._shuffles.clear()
self._archived_by_stimulus.clear()
| ShuffleSchedulerPlugin |
python | urllib3__urllib3 | test/with_dummyserver/test_proxy_poolmanager.py | {
"start": 1571,
"end": 27215
} | class ____(HypercornDummyProxyTestCase):
@classmethod
def setup_class(cls) -> None:
super().setup_class()
cls.http_url = f"http://{cls.http_host}:{int(cls.http_port)}"
cls.http_url_alt = f"http://{cls.http_host_alt}:{int(cls.http_port)}"
cls.https_url = f"https://{cls.https_host}:{int(cls.https_port)}"
cls.https_url_alt = f"https://{cls.https_host_alt}:{int(cls.https_port)}"
cls.https_url_fqdn = f"https://{cls.https_host}.:{int(cls.https_port)}"
cls.proxy_url = f"http://{cls.proxy_host}:{int(cls.proxy_port)}"
cls.https_proxy_url = f"https://{cls.proxy_host}:{int(cls.https_proxy_port)}"
# Generate another CA to test verification failure
cls.certs_dir = tempfile.mkdtemp()
bad_ca = trustme.CA()
cls.bad_ca_path = os.path.join(cls.certs_dir, "ca_bad.pem")
bad_ca.cert_pem.write_to_path(cls.bad_ca_path)
@classmethod
def teardown_class(cls) -> None:
super().teardown_class()
shutil.rmtree(cls.certs_dir)
def test_basic_proxy(self) -> None:
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
r = http.request("GET", f"{self.http_url}/")
assert r.status == 200
r = http.request("GET", f"{self.https_url}/")
assert r.status == 200
def test_https_proxy(self) -> None:
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https:
r = https.request("GET", f"{self.https_url}/")
assert r.status == 200
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
def test_is_verified_http_proxy_to_http_target(self) -> None:
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
r = http.request("GET", f"{self.http_url}/")
assert r.status == 200
assert_is_verified(http, proxy=False, target=False)
def test_is_verified_http_proxy_to_https_target(self) -> None:
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
r = http.request("GET", f"{self.https_url}/")
assert r.status == 200
assert_is_verified(http, proxy=False, target=True)
def test_is_verified_https_proxy_to_http_target(self) -> None:
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https:
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
assert_is_verified(https, proxy=True, target=False)
def test_is_verified_https_proxy_to_https_target(self) -> None:
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https:
r = https.request("GET", f"{self.https_url}/")
assert r.status == 200
assert_is_verified(https, proxy=True, target=True)
def test_http_and_https_kwarg_ca_cert_data_proxy(self) -> None:
with open(DEFAULT_CA) as pem_file:
pem_file_data = pem_file.read()
with proxy_from_url(self.https_proxy_url, ca_cert_data=pem_file_data) as https:
r = https.request("GET", f"{self.https_url}/")
assert r.status == 200
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
def test_https_proxy_with_proxy_ssl_context(self) -> None:
proxy_ssl_context = create_urllib3_context()
proxy_ssl_context.load_verify_locations(DEFAULT_CA)
with proxy_from_url(
self.https_proxy_url,
proxy_ssl_context=proxy_ssl_context,
ca_certs=DEFAULT_CA,
) as https:
r = https.request("GET", f"{self.https_url}/")
assert r.status == 200
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
@withPyOpenSSL
def test_https_proxy_pyopenssl_not_supported(self) -> None:
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https:
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
with pytest.raises(
ProxySchemeUnsupported, match="isn't available on non-native SSLContext"
):
https.request("GET", f"{self.https_url}/")
def test_https_proxy_forwarding_for_https(self) -> None:
with proxy_from_url(
self.https_proxy_url,
ca_certs=DEFAULT_CA,
use_forwarding_for_https=True,
) as https:
r = https.request("GET", f"{self.http_url}/")
assert r.status == 200
r = https.request("GET", f"{self.https_url}/")
assert r.status == 200
def test_nagle_proxy(self) -> None:
"""Test that proxy connections do not have TCP_NODELAY turned on"""
with ProxyManager(self.proxy_url) as http:
hc2 = http.connection_from_host(self.http_host, self.http_port)
conn = hc2._get_conn()
try:
hc2._make_request(conn, "GET", f"{self.http_url}/")
tcp_nodelay_setting = conn.sock.getsockopt( # type: ignore[attr-defined]
socket.IPPROTO_TCP, socket.TCP_NODELAY
)
assert tcp_nodelay_setting == 0, (
"Expected TCP_NODELAY for proxies to be set "
"to zero, instead was %s" % tcp_nodelay_setting
)
finally:
conn.close()
@pytest.mark.parametrize("proxy_scheme", ["http", "https"])
@pytest.mark.parametrize("target_scheme", ["http", "https"])
def test_proxy_conn_fail_from_dns(
self, proxy_scheme: str, target_scheme: str
) -> None:
host, port = get_unreachable_address()
with proxy_from_url(
f"{proxy_scheme}://{host}:{port}/", retries=1, timeout=LONG_TIMEOUT
) as http:
if target_scheme == "https":
target_url = self.https_url
else:
target_url = self.http_url
with pytest.raises(MaxRetryError) as e:
http.request("GET", f"{target_url}/")
assert isinstance(e.value.reason, ProxyError)
assert isinstance(
e.value.reason.original_error, urllib3.exceptions.NameResolutionError
)
def test_oldapi(self) -> None:
with ProxyManager(
connection_from_url(self.proxy_url), ca_certs=DEFAULT_CA # type: ignore[arg-type]
) as http:
r = http.request("GET", f"{self.http_url}/")
assert r.status == 200
r = http.request("GET", f"{self.https_url}/")
assert r.status == 200
@resolvesLocalhostFQDN()
def test_proxy_https_fqdn(self) -> None:
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
r = http.request("GET", f"{self.https_url_fqdn}/")
assert r.status == 200
def test_proxy_verified(self) -> None:
with proxy_from_url(
self.proxy_url, cert_reqs="REQUIRED", ca_certs=self.bad_ca_path
) as http:
with http._new_pool(
"https", self.https_host, self.https_port
) as https_pool:
with pytest.raises(MaxRetryError) as e:
https_pool.request("GET", "/", retries=0)
assert isinstance(e.value.reason, SSLError)
assert (
"certificate verify failed" in str(e.value.reason)
# PyPy is more specific
or "self signed certificate in certificate chain" in str(e.value.reason)
), f"Expected 'certificate verify failed', instead got: {e.value.reason!r}"
http = proxy_from_url(
self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA
)
with http._new_pool(
"https", self.https_host, self.https_port
) as https_pool2:
with contextlib.closing(https_pool._new_conn()) as conn:
assert conn.__class__ == VerifiedHTTPSConnection
https_pool2.request(
"GET", "/"
) # Should succeed without exceptions.
http = proxy_from_url(
self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA
)
with http._new_pool(
"https", "127.0.0.1", self.https_port
) as https_fail_pool:
with pytest.raises(
MaxRetryError, match="doesn't match|IP address mismatch"
) as e:
https_fail_pool.request("GET", "/", retries=0)
assert isinstance(e.value.reason, SSLError)
def test_redirect(self) -> None:
with proxy_from_url(self.proxy_url) as http:
r = http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": f"{self.http_url}/"},
redirect=False,
)
assert r.status == 303
r = http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": f"{self.http_url}/"},
)
assert r.status == 200
assert r.data == b"Dummy server!"
def test_cross_host_redirect(self) -> None:
with proxy_from_url(self.proxy_url) as http:
cross_host_location = f"{self.http_url_alt}/echo?a=b"
with pytest.raises(MaxRetryError):
http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": cross_host_location},
retries=0,
)
r = http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": f"{self.http_url_alt}/echo?a=b"},
retries=1,
)
assert isinstance(r, HTTPResponse)
assert r._pool is not None
assert r._pool.host != self.http_host_alt
def test_cross_protocol_redirect(self) -> None:
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http:
cross_protocol_location = f"{self.https_url}/echo?a=b"
with pytest.raises(MaxRetryError):
http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": cross_protocol_location},
retries=0,
)
r = http.request(
"GET",
f"{self.http_url}/redirect",
fields={"target": f"{self.https_url}/echo?a=b"},
retries=1,
)
assert isinstance(r, HTTPResponse)
assert r._pool is not None
assert r._pool.host == self.https_host
def test_headers(self) -> None:
with proxy_from_url(
self.proxy_url,
headers={"Foo": "bar"},
proxy_headers={"Hickory": "dickory"},
ca_certs=DEFAULT_CA,
) as http:
r = http.request_encode_url("GET", f"{self.http_url}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}"
r = http.request_encode_url("GET", f"{self.http_url_alt}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert (
returned_headers.get("Host") == f"{self.http_host_alt}:{self.http_port}"
)
r = http.request_encode_url("GET", f"{self.https_url}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") is None
assert (
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}"
)
r = http.request_encode_body("POST", f"{self.http_url}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}"
r = http.request_encode_url(
"GET", f"{self.http_url}/headers", headers={"Baz": "quux"}
)
returned_headers = r.json()
assert returned_headers.get("Foo") is None
assert returned_headers.get("Baz") == "quux"
assert returned_headers.get("Hickory") == "dickory"
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}"
r = http.request_encode_url(
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"}
)
returned_headers = r.json()
assert returned_headers.get("Foo") is None
assert returned_headers.get("Baz") == "quux"
assert returned_headers.get("Hickory") is None
assert (
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}"
)
r = http.request_encode_body(
"GET", f"{self.http_url}/headers", headers={"Baz": "quux"}
)
returned_headers = r.json()
assert returned_headers.get("Foo") is None
assert returned_headers.get("Baz") == "quux"
assert returned_headers.get("Hickory") == "dickory"
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}"
r = http.request_encode_body(
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"}
)
returned_headers = r.json()
assert returned_headers.get("Foo") is None
assert returned_headers.get("Baz") == "quux"
assert returned_headers.get("Hickory") is None
assert (
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}"
)
def test_https_headers(self) -> None:
with proxy_from_url(
self.https_proxy_url,
headers={"Foo": "bar"},
proxy_headers={"Hickory": "dickory"},
ca_certs=DEFAULT_CA,
) as http:
r = http.request_encode_url("GET", f"{self.http_url}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}"
r = http.request_encode_url("GET", f"{self.http_url_alt}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert (
returned_headers.get("Host") == f"{self.http_host_alt}:{self.http_port}"
)
r = http.request_encode_body(
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"}
)
returned_headers = r.json()
assert returned_headers.get("Foo") is None
assert returned_headers.get("Baz") == "quux"
assert returned_headers.get("Hickory") is None
assert (
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}"
)
def test_https_headers_forwarding_for_https(self) -> None:
with proxy_from_url(
self.https_proxy_url,
headers={"Foo": "bar"},
proxy_headers={"Hickory": "dickory"},
ca_certs=DEFAULT_CA,
use_forwarding_for_https=True,
) as http:
r = http.request_encode_url("GET", f"{self.https_url}/headers")
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Hickory") == "dickory"
assert (
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}"
)
def test_headerdict(self) -> None:
default_headers = HTTPHeaderDict(a="b")
proxy_headers = HTTPHeaderDict()
proxy_headers.add("foo", "bar")
with proxy_from_url(
self.proxy_url, headers=default_headers, proxy_headers=proxy_headers
) as http:
request_headers = HTTPHeaderDict(baz="quux")
r = http.request("GET", f"{self.http_url}/headers", headers=request_headers)
returned_headers = r.json()
assert returned_headers.get("Foo") == "bar"
assert returned_headers.get("Baz") == "quux"
def test_proxy_pooling(self) -> None:
with proxy_from_url(self.proxy_url, cert_reqs="NONE") as http:
for x in range(2):
http.urlopen("GET", self.http_url)
assert len(http.pools) == 1
for x in range(2):
http.urlopen("GET", self.http_url_alt)
assert len(http.pools) == 1
for x in range(2):
with pytest.warns(InsecureRequestWarning):
http.urlopen("GET", self.https_url)
assert len(http.pools) == 2
for x in range(2):
with pytest.warns(InsecureRequestWarning):
http.urlopen("GET", self.https_url_alt)
assert len(http.pools) == 3
def test_proxy_pooling_ext(self) -> None:
with proxy_from_url(self.proxy_url) as http:
hc1 = http.connection_from_url(self.http_url)
hc2 = http.connection_from_host(self.http_host, self.http_port)
hc3 = http.connection_from_url(self.http_url_alt)
hc4 = http.connection_from_host(self.http_host_alt, self.http_port)
assert hc1 == hc2
assert hc2 == hc3
assert hc3 == hc4
sc1 = http.connection_from_url(self.https_url)
sc2 = http.connection_from_host(
self.https_host, self.https_port, scheme="https"
)
sc3 = http.connection_from_url(self.https_url_alt)
sc4 = http.connection_from_host(
self.https_host_alt, self.https_port, scheme="https"
)
assert sc1 == sc2
assert sc2 != sc3
assert sc3 == sc4
@requires_network()
@pytest.mark.parametrize(
["proxy_scheme", "target_scheme", "use_forwarding_for_https"],
[
("http", "http", False),
("https", "http", False),
# 'use_forwarding_for_https' is only valid for HTTPS+HTTPS.
("https", "https", True),
],
)
def test_forwarding_proxy_request_timeout(
self, proxy_scheme: str, target_scheme: str, use_forwarding_for_https: bool
) -> None:
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url
target_url = f"{target_scheme}://{TARPIT_HOST}"
with proxy_from_url(
proxy_url,
ca_certs=DEFAULT_CA,
use_forwarding_for_https=use_forwarding_for_https,
) as proxy:
with pytest.raises(MaxRetryError) as e:
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT)
proxy.request("GET", target_url, timeout=timeout)
# We sent the request to the proxy but didn't get any response
# so we're not sure if that's being caused by the proxy or the
# target so we put the blame on the target.
assert isinstance(e.value.reason, ReadTimeoutError)
@requires_network()
@pytest.mark.parametrize(
["proxy_scheme", "target_scheme"], [("http", "https"), ("https", "https")]
)
def test_tunneling_proxy_request_timeout(
self, proxy_scheme: str, target_scheme: str
) -> None:
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url
target_url = f"{target_scheme}://{TARPIT_HOST}"
with proxy_from_url(
proxy_url,
ca_certs=DEFAULT_CA,
) as proxy:
with pytest.raises(MaxRetryError) as e:
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT)
proxy.request("GET", target_url, timeout=timeout)
assert isinstance(e.value.reason, ReadTimeoutError)
@requires_network()
@pytest.mark.parametrize(
["proxy_scheme", "target_scheme", "use_forwarding_for_https"],
[
("http", "http", False),
("https", "http", False),
# 'use_forwarding_for_https' is only valid for HTTPS+HTTPS.
("https", "https", True),
],
)
def test_forwarding_proxy_connect_timeout(
self, proxy_scheme: str, target_scheme: str, use_forwarding_for_https: bool
) -> None:
proxy_url = f"{proxy_scheme}://{TARPIT_HOST}"
target_url = self.https_url if target_scheme == "https" else self.http_url
with proxy_from_url(
proxy_url,
ca_certs=DEFAULT_CA,
timeout=SHORT_TIMEOUT,
use_forwarding_for_https=use_forwarding_for_https,
) as proxy:
with pytest.raises(MaxRetryError) as e:
proxy.request("GET", target_url)
assert isinstance(e.value.reason, ProxyError)
assert isinstance(e.value.reason.original_error, ConnectTimeoutError)
@requires_network()
@pytest.mark.parametrize(
["proxy_scheme", "target_scheme"], [("http", "https"), ("https", "https")]
)
def test_tunneling_proxy_connect_timeout(
self, proxy_scheme: str, target_scheme: str
) -> None:
proxy_url = f"{proxy_scheme}://{TARPIT_HOST}"
target_url = self.https_url if target_scheme == "https" else self.http_url
with proxy_from_url(
proxy_url, ca_certs=DEFAULT_CA, timeout=SHORT_TIMEOUT
) as proxy:
with pytest.raises(MaxRetryError) as e:
proxy.request("GET", target_url)
assert isinstance(e.value.reason, ProxyError)
assert isinstance(e.value.reason.original_error, ConnectTimeoutError)
@requires_network()
@pytest.mark.parametrize(
["target_scheme", "use_forwarding_for_https"],
[
("http", False),
("https", False),
("https", True),
],
)
def test_https_proxy_tls_error(
self, target_scheme: str, use_forwarding_for_https: str
) -> None:
target_url = self.https_url if target_scheme == "https" else self.http_url
proxy_ctx = ssl.create_default_context()
with proxy_from_url(
self.https_proxy_url,
proxy_ssl_context=proxy_ctx,
use_forwarding_for_https=use_forwarding_for_https,
) as proxy:
with pytest.raises(MaxRetryError) as e:
proxy.request("GET", target_url)
assert isinstance(e.value.reason, ProxyError)
assert isinstance(e.value.reason.original_error, SSLError)
@requires_network()
@pytest.mark.parametrize(
["proxy_scheme", "use_forwarding_for_https"],
[
("http", False),
("https", False),
("https", True),
],
)
def test_proxy_https_target_tls_error(
self, proxy_scheme: str, use_forwarding_for_https: str
) -> None:
if proxy_scheme == "https" and use_forwarding_for_https:
pytest.skip("Test is expected to fail due to urllib3/urllib3#2577")
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url
proxy_ctx = ssl.create_default_context()
proxy_ctx.load_verify_locations(DEFAULT_CA)
ctx = ssl.create_default_context()
with proxy_from_url(
proxy_url,
proxy_ssl_context=proxy_ctx,
ssl_context=ctx,
use_forwarding_for_https=use_forwarding_for_https,
) as proxy:
with pytest.raises(MaxRetryError) as e:
proxy.request("GET", self.https_url)
assert isinstance(e.value.reason, SSLError)
def test_scheme_host_case_insensitive(self) -> None:
"""Assert that upper-case schemes and hosts are normalized."""
with proxy_from_url(self.proxy_url.upper(), ca_certs=DEFAULT_CA) as http:
r = http.request("GET", f"{self.http_url.upper()}/")
assert r.status == 200
r = http.request("GET", f"{self.https_url.upper()}/")
assert r.status == 200
@pytest.mark.parametrize(
"url, error_msg",
[
(
"127.0.0.1",
"Proxy URL had no scheme, should start with http:// or https://",
),
(
"localhost:8080",
"Proxy URL had no scheme, should start with http:// or https://",
),
(
"ftp://google.com",
"Proxy URL had unsupported scheme ftp, should use http:// or https://",
),
],
)
def test_invalid_schema(self, url: str, error_msg: str) -> None:
with pytest.raises(ProxySchemeUnknown, match=error_msg):
proxy_from_url(url)
@pytest.mark.skipif(not HAS_IPV6, reason="Only runs on IPv6 systems")
| TestHTTPProxyManager |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py | {
"start": 89569,
"end": 90866
} | class ____(GeneratedAirbyteDestination):
@public
def __init__(
self,
name: str,
keyspace: str,
username: str,
password: str,
address: str,
port: int,
replication: Optional[int] = None,
):
"""Airbyte Destination for Scylla.
Documentation can be found at https://docs.airbyte.com/integrations/destinations/scylla
Args:
name (str): The name of the destination.
keyspace (str): Default Scylla keyspace to create data in.
username (str): Username to use to access Scylla.
password (str): Password associated with Scylla.
address (str): Address to connect to.
port (int): Port of Scylla.
replication (Optional[int]): Indicates to how many nodes the data should be replicated to.
"""
self.keyspace = check.str_param(keyspace, "keyspace")
self.username = check.str_param(username, "username")
self.password = check.str_param(password, "password")
self.address = check.str_param(address, "address")
self.port = check.int_param(port, "port")
self.replication = check.opt_int_param(replication, "replication")
super().__init__("Scylla", name)
| ScyllaDestination |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/sources.py | {
"start": 2139,
"end": 28364
} | class ____:
"""
Contains methods to interact with data sources from the gx context
This contains a collection of dynamically generated datasource factory methods in the format
`.add_<TYPE_NAME>()`.
It also contains general data source manipulation methods such as `all()`, `get()` and
`delete()`.
"""
# A dict-like two way mapping between previously registered `Datasource` or `DataAsset` types
# and a simplified name for those types.
type_lookup: ClassVar = TypeLookup()
__crud_registry: ClassVar[Dict[str, CrudMethodInfoFn]] = {}
_data_context: GXDataContext
def __init__(self, data_context: GXDataContext):
self._data_context = data_context
@classmethod
def register_datasource(cls, ds_type: Type[Datasource]) -> None:
"""
Add/Register a datasource. This registers all the crud datasource methods:
add_<datasource>, delete_<datasource>, update_<datasource>, add_or_update_<datasource>
and all related `Datasource`, `DataAsset` and `ExecutionEngine` types.
Creates mapping table between the `DataSource`/`DataAsset` classes and their
declared `type` string.
Example
-------
An `.add_pandas_filesystem()` pandas_filesystem factory method will be added to `context.data_sources`.
>>> class PandasFilesystemDatasource(_PandasFilePathDatasource):
>>> type: str = 'pandas_filesystem'
>>> asset_types = [FileAsset]
>>> execution_engine: PandasExecutionEngine
""" # noqa: E501 # FIXME CoP
# TODO: check that the name is a valid python identifier (and maybe that it is snake_case?)
ds_type_name = _get_field_details(ds_type, "type").default_value
if not ds_type_name:
raise TypeRegistrationError( # noqa: TRY003 # FIXME CoP
f"`{ds_type.__name__}` is missing a `type` attribute with an assigned string value"
)
# rollback type registrations if exception occurs
with (
cls.type_lookup.transaction() as ds_type_lookup,
ds_type._type_lookup.transaction() as asset_type_lookup,
):
cls._register_assets(ds_type, asset_type_lookup=asset_type_lookup)
cls._register_datasource(
ds_type,
ds_type_name=ds_type_name,
datasource_type_lookup=ds_type_lookup,
)
@classmethod
def _register_datasource(
cls,
ds_type: Type[Datasource],
ds_type_name: str,
datasource_type_lookup: TypeLookup,
) -> str:
"""
Register the `Datasource` class and add a factory method for the class on `sources`.
The method name is pulled from the `Datasource.type` attribute.
"""
if ds_type in datasource_type_lookup:
raise TypeRegistrationError( # noqa: TRY003 # FIXME CoP
f"'{ds_type_name}' is already a registered typed and there can only be 1 type "
"for a given name."
)
datasource_type_lookup[ds_type] = ds_type_name
logger.debug(f"'{ds_type_name}' added to `type_lookup`")
cls._register_add_datasource(ds_type, ds_type_name)
cls._register_update_datasource(ds_type, ds_type_name)
cls._register_add_or_update_datasource(ds_type, ds_type_name)
cls._register_delete_datasource(ds_type, ds_type_name)
return ds_type_name
@classmethod
def _register_add_datasource(cls, ds_type: Type[Datasource], ds_type_name: str):
method_name = f"add_{ds_type_name}"
def crud_method_info() -> tuple[CrudMethodType, Type[Datasource]]:
return CrudMethodType.ADD, ds_type
cls._register_crud_method(method_name, cls.__doc__, crud_method_info)
@classmethod
def _register_update_datasource(cls, ds_type: Type[Datasource], ds_type_name: str):
method_name = f"update_{ds_type_name}"
def crud_method_info() -> tuple[CrudMethodType, Type[Datasource]]:
return CrudMethodType.UPDATE, ds_type
cls._register_crud_method(
method_name, f"Updates a {ds_type_name} data source.", crud_method_info
)
@classmethod
def _register_add_or_update_datasource(cls, ds_type: Type[Datasource], ds_type_name: str):
method_name = f"add_or_update_{ds_type_name}"
def crud_method_info() -> tuple[CrudMethodType, Type[Datasource]]:
return CrudMethodType.ADD_OR_UPDATE, ds_type
cls._register_crud_method(
method_name,
f"Adds or updates a {ds_type_name} data source.",
crud_method_info,
)
@classmethod
def _register_delete_datasource(cls, ds_type: Type[Datasource], ds_type_name: str):
method_name = f"delete_{ds_type_name}"
def crud_method_info() -> tuple[CrudMethodType, Type[Datasource]]:
return CrudMethodType.DELETE, ds_type
cls._register_crud_method(
method_name, f"Deletes a {ds_type_name} data source.", crud_method_info
)
@classmethod
def _register_crud_method(
cls,
crud_fn_name: str,
crud_fn_doc: str | None,
crud_method_info: CrudMethodInfoFn,
):
# We set the name and doc and the crud_method_info because that will be used as a proxy
# for the real crud method so we can call public_api to generate docs for these dynamically
# generated methods.
crud_method_info.__name__ = crud_fn_name
crud_method_info.__doc__ = crud_fn_doc
if crud_fn_name in cls.__crud_registry:
raise TypeRegistrationError( # noqa: TRY003 # FIXME CoP
f"'`sources.{crud_fn_name}()` already exists",
)
logger.debug(f"Registering data_context.source.{crud_fn_name}()")
public_api(crud_method_info)
cls.__crud_registry[crud_fn_name] = crud_method_info
@classmethod
def _register_assets(cls, ds_type: Type[Datasource], asset_type_lookup: TypeLookup):
asset_types: Sequence[Type[DataAsset]] = ds_type.asset_types
if not asset_types:
logger.warning(
f"No `{ds_type.__name__}.asset_types` have be declared for the `Datasource`"
)
for t in asset_types:
if t.__name__.startswith("_"):
logger.debug(
f"{t} is private, assuming not intended as a public concrete type. Skipping registration" # noqa: E501 # FIXME CoP
)
continue
try:
asset_type_name = _get_field_details(t, "type").default_value
if asset_type_name is None:
raise TypeError( # noqa: TRY003, TRY301 # FIXME CoP
f"{t.__name__} `type` field must be assigned and cannot be `None`"
)
logger.debug(
f"Registering `{ds_type.__name__}` `DataAsset` `{t.__name__}` as '{asset_type_name}'" # noqa: E501 # FIXME CoP
)
asset_type_lookup[t] = asset_type_name
except (AttributeError, KeyError, TypeError) as bad_field_exc:
raise TypeRegistrationError( # noqa: TRY003 # FIXME CoP
f"No `type` field found for `{ds_type.__name__}.asset_types` -> `{t.__name__}` unable to register asset type", # noqa: E501 # FIXME CoP
) from bad_field_exc
cls._bind_asset_factory_method_if_not_present(ds_type, t, asset_type_name)
@classmethod
def _bind_asset_factory_method_if_not_present(
cls,
ds_type: Type[Datasource],
asset_type: Type[DataAsset],
asset_type_name: str,
):
add_asset_factory_method_name = f"add_{asset_type_name}_asset"
asset_factory_defined: bool = hasattr(ds_type, add_asset_factory_method_name)
if not asset_factory_defined:
logger.debug(
f"No `{add_asset_factory_method_name}()` method found for `{ds_type.__name__}` generating the method..." # noqa: E501 # FIXME CoP
)
def _add_asset_factory(self: Datasource, name: str, **kwargs) -> pydantic.BaseModel:
# if the Datasource uses a data_connector we need to identify the
# asset level attributes needed by the data_connector
# push them to `connect_options` field
if self.data_connector_type:
logger.info(
f"'{self.name}' {type(self).__name__} uses {self.data_connector_type.__name__}" # noqa: E501 # FIXME CoP
)
connect_options = {
k: v
for (k, v) in kwargs.items()
if k in self.data_connector_type.asset_level_option_keys
}
if connect_options:
logger.info(
f"{self.data_connector_type.__name__} connect_options provided -> {list(connect_options.keys())}" # noqa: E501 # FIXME CoP
)
for k in connect_options: # TODO: avoid this extra loop
kwargs.pop(k)
kwargs["connect_options"] = connect_options
# asset_options_type should raise an error if the options are invalid
self.data_connector_type.asset_options_type(**connect_options)
else:
connect_options = {}
asset = asset_type(name=name, **kwargs)
return self._add_asset(asset, connect_options=connect_options)
# attr-defined issue
# https://github.com/python/mypy/issues/12472
_add_asset_factory.__signature__ = _merge_signatures( # type: ignore[attr-defined] # FIXME CoP
_add_asset_factory, asset_type, exclude={"type"}
)
_add_asset_factory.__name__ = add_asset_factory_method_name
setattr(ds_type, add_asset_factory_method_name, _add_asset_factory)
# NOTE: Please review what this looks like in our Public API docs preview before merging
_add_asset_factory.__doc__ = DataSourceManager._build_add_asset_docstring(
asset_type_name
)
# add the public api decorator
public_api(getattr(ds_type, add_asset_factory_method_name))
if getattr(ds_type, "ADD_READER_METHODS", False):
def _read_asset_factory(
self: Datasource, asset_name: str | None = None, **kwargs
) -> Validator:
name = asset_name or DEFAULT_PANDAS_DATA_ASSET_NAME
asset = asset_type(name=name, **kwargs)
self._add_asset(asset)
batch_request = asset.build_batch_request()
# TODO: raise error if `_data_context` not set
return self._data_context.get_validator(batch_request=batch_request) # type: ignore[union-attr] # self._data_context must be set
_read_asset_factory.__signature__ = _merge_signatures( # type: ignore[attr-defined] # FIXME CoP
_read_asset_factory, asset_type, exclude={"type"}
)
read_asset_factory_method_name = f"read_{asset_type_name}"
setattr(ds_type, read_asset_factory_method_name, _read_asset_factory)
else:
logger.debug(
f"`{add_asset_factory_method_name}()` already defined `{ds_type.__name__}`"
)
@staticmethod
def _build_add_asset_docstring(asset_type_name: str) -> str:
article = "an" if asset_type_name[0].lower() in "aeiou" else "a"
return f"""Add {article} {asset_type_name} asset to the datasource."""
@property
def pandas_default(self) -> PandasDatasource:
from great_expectations.datasource.fluent import PandasDatasource
datasources = self.all()
# if a legacy datasource with this name already exists, we try a different name
existing_datasource = datasources.get(DEFAULT_PANDAS_DATASOURCE_NAME)
if not existing_datasource:
return self._data_context.data_sources.add_pandas(name=DEFAULT_PANDAS_DATASOURCE_NAME)
if isinstance(existing_datasource, PandasDatasource):
return existing_datasource
raise DefaultPandasDatasourceError( # noqa: TRY003 # FIXME CoP
"Another non-pandas datasource already exists "
f'with the name: "{DEFAULT_PANDAS_DATASOURCE_NAME}". '
"Please rename this datasources if you wish "
"to use the pandas_default `PandasDatasource`."
)
@property
def factories(self) -> List[str]:
return list(self.__crud_registry.keys())
def _validate_current_datasource_type(
self, name: str, datasource_type: Type[Datasource], raise_if_none: bool = True
) -> None:
try:
current_datasource = self._data_context.data_sources.get(name)
except KeyError as e:
if raise_if_none:
raise ValueError(f"There is no datasource {name} in the data context.") from e # noqa: TRY003 # FIXME CoP
current_datasource = None
if current_datasource and not isinstance(current_datasource, datasource_type):
raise ValueError( # noqa: TRY003 # FIXME CoP
f"Trying to update datasource {name} but it is not the correct type. "
f"Expected {datasource_type.__name__} but got {type(current_datasource).__name__}"
)
def _datasource_passed_in_as_only_argument(
self,
datasource_type: Type[Datasource],
name_or_datasource: Optional[Union[str, Datasource]],
**kwargs,
) -> Optional[Datasource]:
"""Returns a datasource if one is passed in, otherwise None."""
from great_expectations.datasource.fluent.interfaces import Datasource
datasource: Optional[Datasource] = None
if name_or_datasource and isinstance(name_or_datasource, Datasource):
if len(kwargs) != 0:
raise ValueError( # noqa: TRY003 # FIXME CoP
f"The datasource must be the sole argument. We also received: {kwargs}"
)
datasource = name_or_datasource
elif name_or_datasource is None and "datasource" in kwargs:
if len(kwargs) != 1:
raise ValueError(f"The datasource must be the sole argument. We received: {kwargs}") # noqa: TRY003 # FIXME CoP
datasource = kwargs["datasource"]
if datasource and not isinstance(datasource, datasource_type):
raise ValueError( # noqa: TRY003 # FIXME CoP
f"Trying to modify datasource {datasource.name} but it is not the correct type. "
f"Expected {datasource_type} but got {type(datasource)}"
)
return datasource
def _datasource_passed_in(
self,
datasource_type: Type[Datasource],
name_or_datasource: Optional[Union[str, Datasource]],
**kwargs,
) -> Optional[Datasource]:
"""Validates the input is a datasource or a set of constructor parameters
The first argument can be a non-keyword argument. If present it is a datasource
or the name. If it is None, we expect to find either datasource or name as a kwarg.
Args:
datasource_type: The expected type of datasource
name_or_datasource: Either the datasource or the name of the datasource.
Returns:
The passed in datasource or None.
Raises:
ValueError: This is raised if a datasource is passed in with additional arguments or
a datasource is not passed in and no name argument is present.
"""
new_datasource = self._datasource_passed_in_as_only_argument(
datasource_type, name_or_datasource, **kwargs
)
if new_datasource:
return new_datasource
if (
name_or_datasource and isinstance(name_or_datasource, str) and "name" not in "kwargs" # noqa: PLR0133 # FIXME CoP
) or (name_or_datasource is None and "name" in kwargs and isinstance(kwargs["name"], str)):
return None
raise ValueError( # noqa: TRY003 # FIXME CoP
"A datasource object or a name string must be present. The datasource or "
"name can be passed in as the first and only positional argument or can be"
"can be passed in as keyword arguments. The arguments we received were: "
f"positional argument: {name_or_datasource}, kwargs: {kwargs}"
)
def create_add_crud_method(
self,
datasource_type: Type[Datasource],
doc_string: str = "",
) -> SourceFactoryFn:
def add_datasource(
name_or_datasource: Optional[Union[str, Datasource]] = None, **kwargs
) -> Datasource:
# Because of the precedence of `or` and `if`, these grouping paranthesis are necessary.
datasource = (
self._datasource_passed_in(datasource_type, name_or_datasource, **kwargs)
) or (
datasource_type(name=name_or_datasource, **kwargs)
if name_or_datasource
else datasource_type(**kwargs)
)
logger.debug(f"Adding {datasource_type} with {datasource.name}")
datasource._data_context = self._data_context
datasource.test_connection()
datasource = self._data_context._add_fluent_datasource(datasource)
return datasource
add_datasource.__doc__ = doc_string
# attr-defined issue https://github.com/python/mypy/issues/12472
add_datasource.__signature__ = _merge_signatures( # type: ignore[attr-defined] # FIXME CoP
add_datasource,
datasource_type,
exclude={"type", "assets"},
return_type=datasource_type,
)
return add_datasource
def create_update_crud_method(
self,
datasource_type: Type[Datasource],
doc_string: str = "",
) -> SourceFactoryFn:
def update_datasource(
name_or_datasource: Optional[Union[str, Datasource]] = None, **kwargs
) -> Datasource:
# circular import
from great_expectations.datasource.fluent.interfaces import Datasource
updated_datasource = (
self._datasource_passed_in(datasource_type, name_or_datasource, **kwargs)
) or (
datasource_type(name=name_or_datasource, **kwargs)
if name_or_datasource
else datasource_type(**kwargs)
)
datasource_name: str = updated_datasource.name
logger.debug(f"Updating {datasource_type} with {datasource_name}")
self._validate_current_datasource_type(
datasource_name,
datasource_type,
)
# preserve any pre-existing id for usage with cloud
id_: uuid.UUID | None = getattr(self.all().get(datasource_name), "id", None)
if id_:
updated_datasource.id = id_
updated_datasource._data_context = self._data_context
updated_datasource.test_connection()
return_obj = self._data_context._update_fluent_datasource(datasource=updated_datasource)
assert isinstance(return_obj, Datasource)
return return_obj
update_datasource.__doc__ = doc_string
# attr-defined issue https://github.com/python/mypy/issues/12472
update_datasource.__signature__ = _merge_signatures( # type: ignore[attr-defined] # FIXME CoP
update_datasource,
datasource_type,
exclude={"type", "assets"},
return_type=datasource_type,
)
return update_datasource
def create_add_or_update_crud_method(
self,
datasource_type: Type[Datasource],
doc_string: str = "",
) -> SourceFactoryFn:
def add_or_update_datasource(
name_or_datasource: Optional[Union[str, Datasource]] = None, **kwargs
) -> Datasource:
# circular import
from great_expectations.datasource.fluent.interfaces import Datasource
new_datasource = (
self._datasource_passed_in(datasource_type, name_or_datasource, **kwargs)
) or (
datasource_type(name=name_or_datasource, **kwargs)
if name_or_datasource
else datasource_type(**kwargs)
)
# if new_datasource is None that means name is defined as name_or_datasource or as a kwarg # noqa: E501 # FIXME CoP
datasource_name: str = new_datasource.name
logger.debug(f"Adding or updating {datasource_type.__name__} with '{datasource_name}'")
self._validate_current_datasource_type(
datasource_name, datasource_type, raise_if_none=False
)
# preserve any pre-existing id for usage with cloud
id_: uuid.UUID | None = getattr(self.all().get(datasource_name), "id", None)
if id_:
new_datasource.id = id_
new_datasource._data_context = self._data_context
new_datasource.test_connection()
if datasource_name in self.all():
return_obj = self._data_context._update_fluent_datasource(datasource=new_datasource)
else:
return_obj = self._data_context._add_fluent_datasource(datasource=new_datasource)
assert isinstance(return_obj, Datasource)
return return_obj
add_or_update_datasource.__doc__ = doc_string
# attr-defined issue https://github.com/python/mypy/issues/12472
add_or_update_datasource.__signature__ = _merge_signatures( # type: ignore[attr-defined] # FIXME CoP
add_or_update_datasource,
datasource_type,
exclude={"type", "assets"},
return_type=datasource_type,
)
return add_or_update_datasource
def create_delete_crud_method(
self,
datasource_type: Type[Datasource],
doc_string: str = "",
) -> Callable[[str], None]:
def delete_datasource(name: str) -> None:
logger.debug(f"Delete {datasource_type} with {name}")
self._validate_current_datasource_type(name, datasource_type)
self._data_context._delete_fluent_datasource(name=name)
self._data_context._save_project_config()
delete_datasource.__doc__ = doc_string
# attr-defined issue https://github.com/python/mypy/issues/12472
delete_datasource.__signature__ = inspect.signature(delete_datasource) # type: ignore[attr-defined] # FIXME CoP
return delete_datasource
@public_api
def delete(self, name: str) -> None:
"""
Deletes a datasource by name.
Args:
name: The name of the given datasource.
"""
self._data_context.delete_datasource(name=name)
@public_api
def all(self) -> DatasourceDict:
"""Get all Datasources."""
return self._data_context._datasources
@public_api
def get(self, name: str) -> Datasource:
"""Get a Datasource from the collection by name.
Parameters:
name: Name of Datasource to get
Raises:
KeyError: when Datasource is not found.
"""
return self.all()[name]
def __getattr__(self, attr_name: str):
try:
crud_method_info = self.__crud_registry[attr_name]
crud_method_type, datasource_type = crud_method_info()
docstring = crud_method_info.__doc__ or ""
if crud_method_type == CrudMethodType.ADD:
return self.create_add_crud_method(datasource_type, docstring)
elif crud_method_type == CrudMethodType.UPDATE:
return self.create_update_crud_method(datasource_type, docstring)
elif crud_method_type == CrudMethodType.ADD_OR_UPDATE:
return self.create_add_or_update_crud_method(datasource_type, docstring)
elif crud_method_type == CrudMethodType.DELETE:
# deprecated-v0.17.2
warnings.warn(
f"`{attr_name}` is deprecated as of v0.17.2 and will be removed in v0.19. Please use `.sources.delete` moving forward.", # noqa: E501 # FIXME CoP
DeprecationWarning,
)
return self.create_delete_crud_method(datasource_type, docstring)
else:
raise TypeRegistrationError( # noqa: TRY003 # FIXME CoP
f"Unknown crud method registered for {attr_name} with type {crud_method_type}"
)
except KeyError as e:
raise AttributeError(f"No crud method '{attr_name}' in {self.factories}") from e # noqa: TRY003 # FIXME CoP
@override
def __dir__(self) -> List[str]:
"""Preserves autocompletion for dynamic attributes."""
return [*self.factories, *super().__dir__()]
def _iter_all_registered_types(
include_datasource: bool = True, include_data_asset: bool = True
) -> Generator[tuple[str, Type[Datasource] | Type[DataAsset]], None, None]:
"""
Iterate through all registered Datasource and DataAsset types.
Returns tuples of the registered type name and the actual type/class.
"""
for ds_name in DataSourceManager.type_lookup.type_names():
ds_type: Type[Datasource] = DataSourceManager.type_lookup[ds_name]
if include_datasource:
yield ds_name, ds_type
if include_data_asset:
for asset_name in ds_type._type_lookup.type_names():
asset_type: Type[DataAsset] = ds_type._type_lookup[asset_name]
yield asset_name, asset_type
| DataSourceManager |
python | spyder-ide__spyder | spyder/api/widgets/comboboxes.py | {
"start": 7868,
"end": 11220
} | class ____(_SpyderComboBoxMixin, QComboBox):
"""Default combobox widget for Spyder."""
def __init__(self, parent=None, items_elide_mode=None):
"""
Default combobox widget for Spyder.
Parameters
----------
parent: QWidget, optional
The combobox parent.
items_elide_mode: Qt.TextElideMode, optional
Elide mode for the combobox items.
"""
QComboBox.__init__(self, parent)
_SpyderComboBoxMixin.__init__(self)
self.is_editable = None
self._is_shown = False
self._is_popup_shown = False
# This is necessary to have more fine-grained control over the style of
# our comboboxes with css, e.g. to add more padding between its items.
# See https://stackoverflow.com/a/33464045/438386 for the details.
self.setItemDelegate(
_SpyderComboBoxDelegate(self, elide_mode=items_elide_mode)
)
def showEvent(self, event):
"""Adjustments when the widget is shown."""
if not self._is_shown:
if not self.isEditable():
self.is_editable = False
self.setLineEdit(_SpyderComboBoxLineEdit(self, editable=False))
# This is necessary to make Qt position the popup widget below
# the combobox for non-editable ones.
# Solution from https://stackoverflow.com/a/45191141/438386
self.setEditable(True)
self.lineEdit().setReadOnly(True)
# Show popup when the lineEdit is clicked, which is the default
# behavior for non-editable comboboxes in Qt.
self.lineEdit().sig_mouse_clicked.connect(self.showPopup)
else:
self.is_editable = True
self._is_shown = True
super().showEvent(event)
def showPopup(self):
"""Adjustments when the popup is shown."""
super().showPopup()
if sys.platform == "darwin":
# Reposition popup to display it in the right place.
# Solution from https://forum.qt.io/post/349517
popup = self.findChild(QFrame)
popup.move(popup.x() - 3, popup.y() + 4)
# Adjust width to match the lineEdit one.
if not self._is_popup_shown:
popup.setFixedWidth(popup.width() + 2)
self._is_popup_shown = True
else:
# Make borders straight to make popup feel as part of the combobox.
# This doesn't work reliably on Mac.
self._css.QComboBox.setValues(
borderBottomLeftRadius="0px",
borderBottomRightRadius="0px",
)
self.setStyleSheet(self._css.toString())
def hidePopup(self):
"""Adjustments when the popup is hidden."""
super().hidePopup()
self.sig_popup_is_hidden.emit()
if not sys.platform == "darwin":
# Make borders rounded when popup is not visible. This doesn't work
# reliably on Mac.
self._css.QComboBox.setValues(
borderBottomLeftRadius=SpyderPalette.SIZE_BORDER_RADIUS,
borderBottomRightRadius=SpyderPalette.SIZE_BORDER_RADIUS,
)
self.setStyleSheet(self._css.toString())
| SpyderComboBox |
python | walkccc__LeetCode | solutions/1258. Synonymous Sentences/1258.py | {
"start": 41,
"end": 686
} | class ____:
def generateSentences(
self,
synonyms: list[list[str]],
text: str,
) -> list[str]:
ans = SortedSet()
graph = collections.defaultdict(list)
q = collections.deque([text])
for s, t in synonyms:
graph[s].append(t)
graph[t].append(s)
while q:
u = q.popleft()
ans.add(u)
words = u.split()
for i, word in enumerate(words):
for synonym in graph[word]:
# Replace words[i] with its synonym.
words[i] = synonym
newText = ' '.join(words)
if newText not in ans:
q.append(newText)
return list(ans)
| Solution |
python | pytorch__pytorch | test/inductor/test_max_autotune.py | {
"start": 109219,
"end": 110956
} | class ____(TestCase):
def check_healthy(self, p: TuningProcess, device: Optional[int] = None):
result = random.random()
bmreq = _TestBenchmarkRequest(result, device=device)
p.put(bmreq.benchmark)
self.assertEqual(p.get(), result)
def test_tuning_subproc_timeout(self):
p = TuningProcess(None)
bmreq = _TestBenchmarkRequest(0, sleep=120)
p.put(bmreq.benchmark)
with self.assertRaises(TimeoutError):
p.get(timeout=1.0)
# Make sure the TuningProcess is still usable after a timeout.
self.check_healthy(p)
p.shutdown()
def test_tuning_subproc_exception(self):
p = TuningProcess(None)
bmreq = _TestBenchmarkRequest(0, exc=RuntimeError("Fail"))
p.put(bmreq.benchmark)
with self.assertRaises(RuntimeError):
p.get()
# Make sure the TuningProcess is still usable after an exception.
self.check_healthy(p)
p.shutdown()
def test_tuning_subproc_crash(self):
p = TuningProcess(None)
bmreq = _TestBenchmarkRequest(0, crash=True)
p.put(bmreq.benchmark)
with self.assertRaises(EOFError):
p.get()
# Make sure the TuningProcess is still usable after a crash.
self.check_healthy(p)
p.shutdown()
def test_tuning_subproc_killed(self):
p = TuningProcess(None)
p.kill()
self.check_healthy(p)
p.shutdown()
def test_visible_devices(self):
device_list = TuningProcessPool.get_device_list()
for device in device_list:
p = TuningProcess(device)
self.check_healthy(p, device=device)
p.shutdown()
| TestTuningProcess |
python | pytorch__pytorch | test/dynamo/test_global.py | {
"start": 242,
"end": 700
} | class ____: # noqa: B903
def __init__(self, x, y):
self.x = x
self.y = y
def Foo():
return Pair(1, 1)
g_counter = 1
g_list = [0, 1, 2]
g_dict = {"a": 0, "b": 1}
g_object = Foo()
g_tensor = torch.zeros(10)
_name: int = 0
def fresh_name() -> str:
"""create a new unique name for a variable: v0, v1, v2"""
global _name
r = f"v{_name}"
_name += 1
return r
def reset_name():
global _name
_name = 0
| Pair |
python | simonw__sqlite-utils | sqlite_utils/db.py | {
"start": 48117,
"end": 53504
} | class ____:
def exists(self) -> bool:
"Does this table or view exist yet?"
return False
def __init__(self, db, name):
self.db = db
self.name = name
def count_where(
self,
where: Optional[str] = None,
where_args: Optional[Union[Iterable, dict]] = None,
) -> int:
"""
Executes ``SELECT count(*) FROM table WHERE ...`` and returns a count.
:param where: SQL where fragment to use, for example ``id > ?``
:param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
parameters, or a dictionary for ``id > :id``
"""
sql = "select count(*) from {}".format(quote_identifier(self.name))
if where is not None:
sql += " where " + where
return self.db.execute(sql, where_args or []).fetchone()[0]
def execute_count(self):
# Backwards compatibility, see https://github.com/simonw/sqlite-utils/issues/305#issuecomment-890713185
return self.count_where()
@property
def count(self) -> int:
"A count of the rows in this table or view."
return self.count_where()
@property
def rows(self) -> Generator[dict, None, None]:
"Iterate over every dictionaries for each row in this table or view."
return self.rows_where()
def rows_where(
self,
where: Optional[str] = None,
where_args: Optional[Union[Iterable, dict]] = None,
order_by: Optional[str] = None,
select: str = "*",
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> Generator[dict, None, None]:
"""
Iterate over every row in this table or view that matches the specified where clause.
Returns each row as a dictionary. See :ref:`python_api_rows` for more details.
:param where: SQL where fragment to use, for example ``id > ?``
:param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
parameters, or a dictionary for ``id > :id``
:param order_by: Column or fragment of SQL to order by
:param select: Comma-separated list of columns to select - defaults to ``*``
:param limit: Integer number of rows to limit to
:param offset: Integer for SQL offset
"""
if not self.exists():
return
sql = "select {} from {}".format(select, quote_identifier(self.name))
if where is not None:
sql += " where " + where
if order_by is not None:
sql += " order by " + order_by
if limit is not None:
sql += " limit {}".format(limit)
if offset is not None:
sql += " offset {}".format(offset)
cursor = self.db.execute(sql, where_args or [])
columns = [c[0] for c in cursor.description]
for row in cursor:
yield dict(zip(columns, row))
def pks_and_rows_where(
self,
where: Optional[str] = None,
where_args: Optional[Union[Iterable, dict]] = None,
order_by: Optional[str] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
) -> Generator[Tuple[Any, Dict], None, None]:
"""
Like ``.rows_where()`` but returns ``(pk, row)`` pairs - ``pk`` can be a single value or tuple.
:param where: SQL where fragment to use, for example ``id > ?``
:param where_args: Parameters to use with that fragment - an iterable for ``id > ?``
parameters, or a dictionary for ``id > :id``
:param order_by: Column or fragment of SQL to order by
:param select: Comma-separated list of columns to select - defaults to ``*``
:param limit: Integer number of rows to limit to
:param offset: Integer for SQL offset
"""
column_names = [column.name for column in self.columns]
pks = [column.name for column in self.columns if column.is_pk]
if not pks:
column_names.insert(0, "rowid")
pks = ["rowid"]
select = ",".join(quote_identifier(column_name) for column_name in column_names)
for row in self.rows_where(
select=select,
where=where,
where_args=where_args,
order_by=order_by,
limit=limit,
offset=offset,
):
row_pk = tuple(row[pk] for pk in pks)
if len(row_pk) == 1:
row_pk = row_pk[0]
yield row_pk, row
@property
def columns(self) -> List["Column"]:
"List of :ref:`Columns <reference_db_other_column>` representing the columns in this table or view."
if not self.exists():
return []
rows = self.db.execute(
"PRAGMA table_info({})".format(quote_identifier(self.name))
).fetchall()
return [Column(*row) for row in rows]
@property
def columns_dict(self) -> Dict[str, Any]:
"``{column_name: python-type}`` dictionary representing columns in this table or view."
return {column.name: column_affinity(column.type) for column in self.columns}
@property
def schema(self) -> str:
"SQL schema for this table or view."
return self.db.execute(
"select sql from sqlite_master where name = ?", (self.name,)
).fetchone()[0]
| Queryable |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/fingerprint_op_test.py | {
"start": 965,
"end": 1590
} | class ____(test.TestCase):
def test_default_values(self):
data = np.arange(10)
data = np.expand_dims(data, axis=0)
fingerprint0 = self.evaluate(array_ops.fingerprint(data))
fingerprint1 = self.evaluate(array_ops.fingerprint(data[:, 1:]))
self.assertEqual(fingerprint0.ndim, 2)
self.assertTupleEqual(fingerprint0.shape, fingerprint1.shape)
self.assertTrue(np.any(fingerprint0 != fingerprint1))
def test_empty(self):
f0 = self.evaluate(array_ops.fingerprint([]))
self.assertEqual(f0.ndim, 2)
self.assertEqual(f0.shape, (0, 8))
if __name__ == "__main__":
test.main()
| FingerprintTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property1.py | {
"start": 1794,
"end": 1914
} | class ____(ClassC):
def method1(self) -> None:
reveal_type(self.prop1, expected_text="type[Self@ClassD]")
| ClassD |
python | explosion__spaCy | spacy/schemas.py | {
"start": 8362,
"end": 9577
} | class ____(BaseModel):
REGEX: Optional[StrictStr] = Field(None, alias="regex")
IN: Optional[List[StrictInt]] = Field(None, alias="in")
NOT_IN: Optional[List[StrictInt]] = Field(None, alias="not_in")
IS_SUBSET: Optional[List[StrictInt]] = Field(None, alias="is_subset")
IS_SUPERSET: Optional[List[StrictInt]] = Field(None, alias="is_superset")
INTERSECTS: Optional[List[StrictInt]] = Field(None, alias="intersects")
EQ: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias="==")
NEQ: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias="!=")
GEQ: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias=">=")
LEQ: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias="<=")
GT: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias=">")
LT: Optional[Union[StrictInt, StrictFloat]] = Field(None, alias="<")
class Config:
extra = "forbid"
allow_population_by_field_name = True # allow alias and field name
@validator("*", pre=True, each_item=True, allow_reuse=True)
def raise_for_none(cls, v):
if v is None:
raise ValueError("None / null is not allowed")
return v
| TokenPatternNumber |
python | ansible__ansible | lib/ansible/_internal/_templating/_lazy_containers.py | {
"start": 2645,
"end": 2844
} | class ____:
"""Intermediate value source for lazy-eligible collection copy operations."""
source: t.Iterable
templar: TemplateEngine
lazy_options: LazyOptions
@t.final
| _LazyValueSource |
python | getsentry__sentry | src/sentry/identity/google/provider.py | {
"start": 571,
"end": 2384
} | class ____(OAuth2Provider):
key = "google"
name = "Google"
oauth_access_token_url = "https://www.googleapis.com/oauth2/v4/token"
oauth_authorize_url = "https://accounts.google.com/o/oauth2/auth"
oauth_scopes = ("email",)
def get_oauth_client_id(self):
return options.get("auth-google.client-id")
def get_oauth_client_secret(self):
return options.get("auth-google.client-secret")
def build_identity(self, state):
data = state.get("data", {})
try:
id_token = data["id_token"]
except KeyError:
raise IdentityNotValid("Missing id_token in OAuth response: %s" % data)
try:
_, payload, _ = map(urlsafe_b64decode, id_token.split(".", 2))
except Exception as exc:
raise IdentityNotValid("Unable to decode id_token: %s" % exc)
try:
user_data = orjson.loads(payload)
except ValueError as exc:
raise IdentityNotValid("Unable to decode id_token payload: %s" % exc)
# XXX(epurkhiser): This is carryover from the AuthProvider version of
# google identity. Because we will have code that handles interop
# between newstyle generic Identity, and oldstyle AuthProviders, we
# have to keep the MigratingIdentityId here.
user_id = MigratingIdentityId(id=user_data["sub"], legacy_id=user_data["email"])
return {
"type": "google",
"id": user_id,
"email": user_data["email"],
"email_verified": user_data["email_verified"],
"name": user_data["email"],
"domain": user_data.get("hd", DEFAULT_GOOGLE_DOMAIN),
"scopes": sorted(self.oauth_scopes),
"data": self.get_oauth_data(data),
}
| GoogleIdentityProvider |
python | optuna__optuna | optuna/_imports.py | {
"start": 335,
"end": 3349
} | class ____:
"""Context manager to defer exceptions from imports.
Catches :exc:`ImportError` and :exc:`SyntaxError`.
If any exception is caught, this class raises an :exc:`ImportError` when being checked.
"""
def __init__(self) -> None:
self._deferred: tuple[Exception, str] | None = None
def __enter__(self) -> "_DeferredImportExceptionContextManager":
"""Enter the context manager.
Returns:
Itself.
"""
return self
def __exit__(
self,
exc_type: type[Exception] | None,
exc_value: Exception | None,
traceback: TracebackType | None,
) -> bool | None:
"""Exit the context manager.
Args:
exc_type:
Raised exception type. :obj:`None` if nothing is raised.
exc_value:
Raised exception object. :obj:`None` if nothing is raised.
traceback:
Associated traceback. :obj:`None` if nothing is raised.
Returns:
:obj:`None` if nothing is deferred, otherwise :obj:`True`.
:obj:`True` will suppress any exceptions avoiding them from propagating.
"""
if isinstance(exc_value, (ImportError, SyntaxError)):
if isinstance(exc_value, ImportError):
message = (
"Tried to import '{}' but failed. Please make sure that the package is "
"installed correctly to use this feature. Actual error: {}."
).format(exc_value.name, exc_value)
elif isinstance(exc_value, SyntaxError):
message = (
"Tried to import a package but failed due to a syntax error in {}. Please "
"make sure that the Python version is correct to use this feature. Actual "
"error: {}."
).format(exc_value.filename, exc_value)
else:
assert False
self._deferred = (exc_value, message)
return True
return None
def is_successful(self) -> bool:
"""Return whether the context manager has caught any exceptions.
Returns:
:obj:`True` if no exceptions are caught, :obj:`False` otherwise.
"""
return self._deferred is None
def check(self) -> None:
"""Check whether the context manager has caught any exceptions.
Raises:
:exc:`ImportError`:
If any exception was caught from the caught exception.
"""
if self._deferred is not None:
exc_value, message = self._deferred
raise ImportError(message) from exc_value
def try_import() -> _DeferredImportExceptionContextManager:
"""Create a context manager that can wrap imports of optional packages to defer exceptions.
Returns:
Deferred import context manager.
"""
return _DeferredImportExceptionContextManager()
| _DeferredImportExceptionContextManager |
python | apache__airflow | providers/opensearch/tests/unit/opensearch/operators/test_opensearch.py | {
"start": 3203,
"end": 4530
} | class ____:
def setup_method(self, dag_setup):
self.dag = dag_setup
self.open_search = OpenSearchAddDocumentOperator(
task_id="test_opensearch_doc_operator",
index_name="test_index",
document={"title": "Monty Python"},
doc_id=1,
)
self.open_search_with_doc_class = OpenSearchAddDocumentOperator(
task_id="test_opensearch_doc_class_operator",
doc_class=FakeDocument(meta={"id": 2}, title="Hamlet", author="Shakespeare", published="1299"),
)
def test_init_with_args(self):
assert self.open_search.task_id == "test_opensearch_doc_operator"
assert self.open_search.opensearch_conn_id == "opensearch_default"
assert self.open_search.index_name == "test_index"
def test_init_with_class(self):
# This operator uses the OpenSearch client method directly, testing here just
# confirming that the object is an instance of the class.
assert isinstance(self.open_search_with_doc_class.doc_class, FakeDocument)
assert self.open_search_with_doc_class.task_id == "test_opensearch_doc_class_operator"
def test_add_document_using_args(self, mock_hook):
result = self.open_search.execute({})
assert result == 1
| TestOpenSearchAddDocumentOperator |
python | google__pytype | pytype/pytd/pytd_utils.py | {
"start": 9959,
"end": 12788
} | class ____(dict):
"""A simple ordered set."""
def __init__(self, iterable=None):
super().__init__((item, None) for item in (iterable or []))
def add(self, item):
self[item] = None
def ASTeq(ast1: pytd.TypeDeclUnit, ast2: pytd.TypeDeclUnit):
# pytd.TypeDeclUnit does equality by ID, so we need a helper in order to do
# by-value equality.
return (
ast1.constants == ast2.constants
and ast1.type_params == ast2.type_params
and ast1.classes == ast2.classes
and ast1.functions == ast2.functions
and ast1.aliases == ast2.aliases
)
def GetTypeParameters(node):
collector = pytd_visitors.CollectTypeParameters()
node.Visit(collector)
return collector.params
def DummyMethod(name, *params):
"""Create a simple method using only "Any"s as types.
Arguments:
name: The name of the method
*params: The parameter names.
Returns:
A pytd.Function.
"""
def make_param(param):
return pytd.Parameter(
param,
type=pytd.AnythingType(),
kind=pytd.ParameterKind.REGULAR,
optional=False,
mutated_type=None,
)
sig = pytd.Signature(
tuple(make_param(param) for param in params),
starargs=None,
starstarargs=None,
return_type=pytd.AnythingType(),
exceptions=(),
template=(),
)
return pytd.Function(
name=name,
signatures=(sig,),
kind=pytd.MethodKind.METHOD,
flags=pytd.MethodFlag.NONE,
)
def MergeBaseClass(cls, base):
"""Merge a base class into a subclass.
Arguments:
cls: The subclass to merge values into. pytd.Class.
base: The superclass whose values will be merged. pytd.Class.
Returns:
a pytd.Class of the two merged classes.
"""
bases = tuple(b for b in cls.bases if b != base)
bases += tuple(b for b in base.bases if b not in bases)
method_names = [m.name for m in cls.methods]
methods = cls.methods + tuple(
m for m in base.methods if m.name not in method_names
)
constant_names = [c.name for c in cls.constants]
constants = cls.constants + tuple(
c for c in base.constants if c.name not in constant_names
)
class_names = [c.name for c in cls.classes]
classes = cls.classes + tuple(
c for c in base.classes if c.name not in class_names
)
# Keep decorators from the base class only if the derived class has none
decorators = cls.decorators or base.decorators
if cls.slots:
slots = cls.slots + tuple(s for s in base.slots or () if s not in cls.slots)
else:
slots = base.slots
return pytd.Class(
name=cls.name,
keywords=cls.keywords or base.keywords,
bases=bases,
methods=methods,
constants=constants,
classes=classes,
decorators=decorators,
slots=slots,
template=cls.template or base.template,
)
| OrderedSet |
python | mlflow__mlflow | mlflow/llama_index/pyfunc_wrapper.py | {
"start": 6098,
"end": 12686
} | class ____(_LlamaIndexModelWrapperBase):
@property
def index(self):
raise NotImplementedError("LlamaIndex Workflow does not have an index")
@property
def engine_type(self):
raise NotImplementedError("LlamaIndex Workflow is not an engine")
def predict(self, data, params: dict[str, Any] | None = None) -> list[str] | str:
inputs = self._format_predict_input(data, params)
# LlamaIndex Workflow runs async but MLflow pyfunc doesn't support async inference yet.
predictions = self._wait_async_task(self._run_predictions(inputs))
# Even if the input is single instance, the signature enforcement convert it to a Pandas
# DataFrame with a single row. In this case, we should unwrap the result (list) so it
# won't be inconsistent with the output without signature enforcement.
should_unwrap = len(data) == 1 and isinstance(predictions, list)
return predictions[0] if should_unwrap else predictions
def _format_predict_input(
self, data, params: dict[str, Any] | None = None
) -> list[dict[str, Any]]:
inputs = _convert_llm_input_data_with_unwrapping(data)
params = params or {}
if isinstance(inputs, dict):
return [{**inputs, **params}]
return [{**x, **params} for x in inputs]
async def _run_predictions(self, inputs: list[dict[str, Any]]) -> asyncio.Future:
tasks = [self._predict_single(x) for x in inputs]
return await asyncio.gather(*tasks)
async def _predict_single(self, x: dict[str, Any]) -> Any:
if not isinstance(x, dict):
raise ValueError(f"Unsupported input type: {type(x)}. It must be a dictionary.")
return await self._llama_model.run(**x)
def _wait_async_task(self, task: asyncio.Future) -> Any:
"""
A utility function to run async tasks in a blocking manner.
If there is no event loop running already, for example, in a model serving endpoint,
we can simply create a new event loop and run the task there. However, in a notebook
environment (or pytest with asyncio decoration), there is already an event loop running
at the root level and we cannot start a new one.
"""
if not self._is_event_loop_running():
return asyncio.new_event_loop().run_until_complete(task)
else:
# NB: The popular way to run async task where an event loop is already running is to
# use nest_asyncio. However, nest_asyncio.apply() breaks the async OpenAI client
# somehow, which is used for the most of LLM calls in LlamaIndex including Databricks
# LLMs. Therefore, we use a hacky workaround that creates a new thread and run the
# new event loop there. This may degrade the performance compared to the native
# asyncio, but it should be fine because this is only used in the notebook env.
results = None
exception = None
def _run():
nonlocal results, exception
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
results = loop.run_until_complete(task)
except Exception as e:
exception = e
finally:
loop.close()
thread = threading.Thread(
target=_run, name=f"mlflow_llamaindex_async_task_runner_{uuid.uuid4().hex[:8]}"
)
thread.start()
thread.join()
if exception:
raise exception
return results
def _is_event_loop_running(self) -> bool:
try:
loop = asyncio.get_running_loop()
return loop is not None
except Exception:
return False
def create_pyfunc_wrapper(
model: Any,
engine_type: str | None = None,
model_config: dict[str, Any] | None = None,
):
"""
A factory function that creates a Pyfunc wrapper around a LlamaIndex index/engine/workflow.
Args:
model: A LlamaIndex index/engine/workflow.
engine_type: The type of the engine. Only required if `model` is an index
and must be one of [chat, query, retriever].
model_config: A dictionary of model configuration parameters.
"""
try:
from llama_index.core.workflow import Workflow
if isinstance(model, Workflow):
return _create_wrapper_from_workflow(model, model_config)
except ImportError:
pass
from llama_index.core.indices.base import BaseIndex
if isinstance(model, BaseIndex):
return _create_wrapper_from_index(model, engine_type, model_config)
else:
# Engine does not have a common base class so we assume
# everything else is an engine
return _create_wrapper_from_engine(model, model_config)
def _create_wrapper_from_index(index, engine_type: str, model_config: dict[str, Any] | None = None):
model_config = model_config or {}
if engine_type == QUERY_ENGINE_NAME:
engine = index.as_query_engine(**model_config)
return QueryEngineWrapper(engine, model_config)
elif engine_type == CHAT_ENGINE_NAME:
engine = index.as_chat_engine(**model_config)
return ChatEngineWrapper(engine, model_config)
elif engine_type == RETRIEVER_ENGINE_NAME:
engine = index.as_retriever(**model_config)
return RetrieverEngineWrapper(engine, model_config)
else:
raise ValueError(
f"Unsupported engine type: {engine_type}. It must be one of {SUPPORTED_ENGINES}"
)
def _create_wrapper_from_engine(engine: Any, model_config: dict[str, Any] | None = None):
from llama_index.core.base.base_query_engine import BaseQueryEngine
from llama_index.core.chat_engine.types import BaseChatEngine
from llama_index.core.retrievers import BaseRetriever
if isinstance(engine, BaseChatEngine):
return ChatEngineWrapper(engine, model_config)
elif isinstance(engine, BaseQueryEngine):
return QueryEngineWrapper(engine, model_config)
elif isinstance(engine, BaseRetriever):
return RetrieverEngineWrapper(engine, model_config)
else:
raise ValueError(
f"Unsupported engine type: {type(engine)}. It must be one of {SUPPORTED_ENGINES}"
)
def _create_wrapper_from_workflow(workflow: Any, model_config: dict[str, Any] | None = None):
return WorkflowWrapper(workflow, model_config)
| WorkflowWrapper |
python | pypa__setuptools | setuptools/_distutils/tests/test_install.py | {
"start": 711,
"end": 8618
} | class ____(
support.TempdirManager,
):
@pytest.mark.xfail(
'platform.system() == "Windows" and sys.version_info > (3, 11)',
reason="pypa/distutils#148",
)
def test_home_installation_scheme(self):
# This ensure two things:
# - that --home generates the desired set of directory names
# - test --home is supported on all platforms
builddir = self.mkdtemp()
destination = os.path.join(builddir, "installation")
dist = Distribution({"name": "foopkg"})
# script_name need not exist, it just need to be initialized
dist.script_name = os.path.join(builddir, "setup.py")
dist.command_obj["build"] = support.DummyCommand(
build_base=builddir,
build_lib=os.path.join(builddir, "lib"),
)
cmd = install(dist)
cmd.home = destination
cmd.ensure_finalized()
assert cmd.install_base == destination
assert cmd.install_platbase == destination
def check_path(got, expected):
got = os.path.normpath(got)
expected = os.path.normpath(expected)
assert got == expected
impl_name = sys.implementation.name.replace("cpython", "python")
libdir = os.path.join(destination, "lib", impl_name)
check_path(cmd.install_lib, libdir)
_platlibdir = getattr(sys, "platlibdir", "lib")
platlibdir = os.path.join(destination, _platlibdir, impl_name)
check_path(cmd.install_platlib, platlibdir)
check_path(cmd.install_purelib, libdir)
check_path(
cmd.install_headers,
os.path.join(destination, "include", impl_name, "foopkg"),
)
check_path(cmd.install_scripts, os.path.join(destination, "bin"))
check_path(cmd.install_data, destination)
def test_user_site(self, monkeypatch):
# test install with --user
# preparing the environment for the test
self.tmpdir = self.mkdtemp()
orig_site = site.USER_SITE
orig_base = site.USER_BASE
monkeypatch.setattr(site, 'USER_BASE', os.path.join(self.tmpdir, 'B'))
monkeypatch.setattr(site, 'USER_SITE', os.path.join(self.tmpdir, 'S'))
monkeypatch.setattr(install_module, 'USER_BASE', site.USER_BASE)
monkeypatch.setattr(install_module, 'USER_SITE', site.USER_SITE)
def _expanduser(path):
if path.startswith('~'):
return os.path.normpath(self.tmpdir + path[1:])
return path
monkeypatch.setattr(os.path, 'expanduser', _expanduser)
for key in ('nt_user', 'posix_user'):
assert key in INSTALL_SCHEMES
dist = Distribution({'name': 'xx'})
cmd = install(dist)
# making sure the user option is there
options = [name for name, short, label in cmd.user_options]
assert 'user' in options
# setting a value
cmd.user = True
# user base and site shouldn't be created yet
assert not os.path.exists(site.USER_BASE)
assert not os.path.exists(site.USER_SITE)
# let's run finalize
cmd.ensure_finalized()
# now they should
assert os.path.exists(site.USER_BASE)
assert os.path.exists(site.USER_SITE)
assert 'userbase' in cmd.config_vars
assert 'usersite' in cmd.config_vars
actual_headers = os.path.relpath(cmd.install_headers, site.USER_BASE)
if os.name == 'nt' and not is_mingw():
site_path = os.path.relpath(os.path.dirname(orig_site), orig_base)
include = os.path.join(site_path, 'Include')
else:
include = sysconfig.get_python_inc(0, '')
expect_headers = os.path.join(include, 'xx')
assert os.path.normcase(actual_headers) == os.path.normcase(expect_headers)
def test_handle_extra_path(self):
dist = Distribution({'name': 'xx', 'extra_path': 'path,dirs'})
cmd = install(dist)
# two elements
cmd.handle_extra_path()
assert cmd.extra_path == ['path', 'dirs']
assert cmd.extra_dirs == 'dirs'
assert cmd.path_file == 'path'
# one element
cmd.extra_path = ['path']
cmd.handle_extra_path()
assert cmd.extra_path == ['path']
assert cmd.extra_dirs == 'path'
assert cmd.path_file == 'path'
# none
dist.extra_path = cmd.extra_path = None
cmd.handle_extra_path()
assert cmd.extra_path is None
assert cmd.extra_dirs == ''
assert cmd.path_file is None
# three elements (no way !)
cmd.extra_path = 'path,dirs,again'
with pytest.raises(DistutilsOptionError):
cmd.handle_extra_path()
def test_finalize_options(self):
dist = Distribution({'name': 'xx'})
cmd = install(dist)
# must supply either prefix/exec-prefix/home or
# install-base/install-platbase -- not both
cmd.prefix = 'prefix'
cmd.install_base = 'base'
with pytest.raises(DistutilsOptionError):
cmd.finalize_options()
# must supply either home or prefix/exec-prefix -- not both
cmd.install_base = None
cmd.home = 'home'
with pytest.raises(DistutilsOptionError):
cmd.finalize_options()
# can't combine user with prefix/exec_prefix/home or
# install_(plat)base
cmd.prefix = None
cmd.user = 'user'
with pytest.raises(DistutilsOptionError):
cmd.finalize_options()
def test_record(self):
install_dir = self.mkdtemp()
project_dir, dist = self.create_dist(py_modules=['hello'], scripts=['sayhi'])
os.chdir(project_dir)
self.write_file('hello.py', "def main(): print('o hai')")
self.write_file('sayhi', 'from hello import main; main()')
cmd = install(dist)
dist.command_obj['install'] = cmd
cmd.root = install_dir
cmd.record = os.path.join(project_dir, 'filelist')
cmd.ensure_finalized()
cmd.run()
content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
found = [pathlib.Path(line).name for line in content.splitlines()]
expected = [
'hello.py',
f'hello.{sys.implementation.cache_tag}.pyc',
'sayhi',
'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
]
assert found == expected
def test_record_extensions(self):
cmd = missing_compiler_executable()
if cmd is not None:
pytest.skip(f'The {cmd!r} command is not found')
install_dir = self.mkdtemp()
project_dir, dist = self.create_dist(
ext_modules=[Extension('xx', ['xxmodule.c'])]
)
os.chdir(project_dir)
support.copy_xxmodule_c(project_dir)
buildextcmd = build_ext(dist)
support.fixup_build_ext(buildextcmd)
buildextcmd.ensure_finalized()
cmd = install(dist)
dist.command_obj['install'] = cmd
dist.command_obj['build_ext'] = buildextcmd
cmd.root = install_dir
cmd.record = os.path.join(project_dir, 'filelist')
cmd.ensure_finalized()
cmd.run()
content = pathlib.Path(cmd.record).read_text(encoding='utf-8')
found = [pathlib.Path(line).name for line in content.splitlines()]
expected = [
_make_ext_name('xx'),
'UNKNOWN-0.0.0-py{}.{}.egg-info'.format(*sys.version_info[:2]),
]
assert found == expected
def test_debug_mode(self, caplog, monkeypatch):
# this covers the code called when DEBUG is set
monkeypatch.setattr(install_module, 'DEBUG', True)
caplog.set_level(logging.DEBUG)
self.test_record()
assert any(rec for rec in caplog.records if rec.levelno == logging.DEBUG)
| TestInstall |
python | milvus-io__pymilvus | tests/test_async_milvus_client.py | {
"start": 317,
"end": 12330
} | class ____:
"""Test cases for newly added features in AsyncMilvusClient"""
def test_get_server_type(self):
"""Test get_server_type returns correct value"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = MagicMock()
mock_handler.get_server_type.return_value = "milvus"
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
# get_server_type is called during __init__ for is_self_hosted, and again here
assert mock_handler.get_server_type.call_count >= 1
result = client.get_server_type()
assert result == "milvus"
# Verify it was called at least once more (during the explicit call)
assert mock_handler.get_server_type.call_count >= 2
@pytest.mark.asyncio
async def test_get_load_state_with_progress_when_loading(self):
"""Test get_load_state returns progress when state is Loading"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.get_load_state = AsyncMock(return_value=LoadState.Loading)
mock_handler.get_loading_progress = AsyncMock(return_value=75)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.get_load_state("test_collection")
assert result["state"] == LoadState.Loading
assert result["progress"] == 75
mock_handler.get_load_state.assert_called_once()
mock_handler.get_loading_progress.assert_called_once()
@pytest.mark.asyncio
async def test_get_load_state_without_progress_when_not_loading(self):
"""Test get_load_state does not return progress when state is not Loading"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.get_load_state = AsyncMock(return_value=LoadState.Loaded)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.get_load_state("test_collection")
assert result["state"] == LoadState.Loaded
assert "progress" not in result
mock_handler.get_load_state.assert_called_once()
mock_handler.get_loading_progress.assert_not_called()
@pytest.mark.asyncio
async def test_describe_collection_with_struct_array_fields(self):
"""Test describe_collection converts struct_array_fields to user-friendly format"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_result = {
"fields": [{"name": "field1", "type": "INT64"}],
"struct_array_fields": [
{"name": "struct_field", "type": "STRUCT", "element_type": "INT64"}
]
}
mock_handler.describe_collection = AsyncMock(return_value=mock_result)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.describe_collection("test_collection")
# Verify struct_array_fields is converted and added to fields
assert "struct_array_fields" not in result
assert len(result["fields"]) == 2 # original field + converted struct field
mock_handler.describe_collection.assert_called_once()
@pytest.mark.asyncio
async def test_describe_collection_without_struct_array_fields(self):
"""Test describe_collection works normally when no struct_array_fields"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_result = {
"fields": [{"name": "field1", "type": "INT64"}]
}
mock_handler.describe_collection = AsyncMock(return_value=mock_result)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.describe_collection("test_collection")
assert result == mock_result
assert "struct_array_fields" not in result
mock_handler.describe_collection.assert_called_once()
@pytest.mark.asyncio
async def test_search_with_ranker(self):
"""Test search method accepts ranker parameter"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.search = AsyncMock(return_value=[[{"id": 1, "distance": 0.1}]])
mock_fetch.return_value = mock_handler
mock_ranker = MagicMock(spec=Function)
client = AsyncMilvusClient()
result = await client.search(
"test_collection",
data=[[0.1, 0.2]],
ranker=mock_ranker
)
assert result == [[{"id": 1, "distance": 0.1}]]
# Verify ranker was passed to handler
call_args = mock_handler.search.call_args
# ranker is passed as keyword argument
assert call_args.kwargs.get("ranker") == mock_ranker
@pytest.mark.asyncio
async def test_hybrid_search_with_function_ranker(self):
"""Test hybrid_search accepts Function type ranker"""
from pymilvus.client.abstract import AnnSearchRequest
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.hybrid_search = AsyncMock(return_value=[[{"id": 1}]])
mock_fetch.return_value = mock_handler
mock_function_ranker = MagicMock(spec=Function)
mock_req = MagicMock(spec=AnnSearchRequest)
client = AsyncMilvusClient()
result = await client.hybrid_search(
"test_collection",
reqs=[mock_req],
ranker=mock_function_ranker
)
assert result == [[{"id": 1}]]
# ranker is passed as positional argument (3rd arg), check args[2]
call_args = mock_handler.hybrid_search.call_args
assert call_args[0][2] == mock_function_ranker # ranker is 3rd positional arg
@pytest.mark.asyncio
async def test_compact_with_is_l0(self):
"""Test compact method accepts is_l0 parameter"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.compact = AsyncMock(return_value=123)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.compact("test_collection", is_l0=True)
assert result == 123
call_args = mock_handler.compact.call_args
assert call_args[1]["is_l0"] is True
@pytest.mark.asyncio
async def test_flush_all(self):
"""Test flush_all method"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.flush_all = AsyncMock()
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
await client.flush_all(timeout=10)
mock_handler.flush_all.assert_called_once_with(timeout=10)
@pytest.mark.asyncio
async def test_get_flush_all_state(self):
"""Test get_flush_all_state method"""
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.get_flush_all_state = AsyncMock(return_value=True)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.get_flush_all_state(timeout=10)
assert result is True
mock_handler.get_flush_all_state.assert_called_once_with(timeout=10)
@pytest.mark.asyncio
async def test_get_compaction_plans(self):
"""Test get_compaction_plans method"""
from pymilvus.client.types import CompactionPlans
mock_plans = MagicMock(spec=CompactionPlans)
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_handler.get_compaction_plans = AsyncMock(return_value=mock_plans)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.get_compaction_plans(job_id=123, timeout=10)
assert result == mock_plans
mock_handler.get_compaction_plans.assert_called_once_with(123, timeout=10)
@pytest.mark.asyncio
async def test_update_replicate_configuration(self):
"""Test update_replicate_configuration method"""
clusters = [
{
"cluster_id": "cluster1",
"connection_param": {"uri": "http://localhost:19530", "token": "token1"}
}
]
cross_cluster_topology = [
{"source_cluster_id": "cluster1", "target_cluster_id": "cluster2"}
]
with patch('pymilvus.milvus_client.async_milvus_client.create_connection', return_value="test"), \
patch('pymilvus.orm.connections.Connections._fetch_handler') as mock_fetch:
mock_handler = AsyncMock()
mock_status = MagicMock()
mock_handler.update_replicate_configuration = AsyncMock(return_value=mock_status)
mock_fetch.return_value = mock_handler
client = AsyncMilvusClient()
result = await client.update_replicate_configuration(
clusters=clusters,
cross_cluster_topology=cross_cluster_topology,
timeout=10
)
assert result == mock_status
mock_handler.update_replicate_configuration.assert_called_once_with(
clusters=clusters,
cross_cluster_topology=cross_cluster_topology,
timeout=10
)
def test_create_struct_field_schema(self):
"""Test create_struct_field_schema class method"""
result = AsyncMilvusClient.create_struct_field_schema()
assert isinstance(result, StructFieldSchema)
| TestAsyncMilvusClientNewFeatures |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pydocstyle/setter.py | {
"start": 0,
"end": 301
} | class ____:
@property
def foo(self) -> str:
"""Docstring for foo."""
return "foo"
@foo.setter
def foo(self, value: str) -> None:
pass
@foo.deleter
def foo(self):
pass
@foo
def foo(self, value: str) -> None:
pass
| PropertyWithSetter |
python | matplotlib__matplotlib | lib/matplotlib/projections/polar.py | {
"start": 17495,
"end": 19003
} | class ____(mtransforms.ScaledTranslation):
"""
Apply a padding shift based on axes theta limits.
This is used to create padding for radial ticks.
Parameters
----------
axes : `~matplotlib.axes.Axes`
The owning Axes; used to determine limits.
pad : float
The padding to apply, in points.
mode : {'min', 'max', 'rlabel'}
Whether to shift away from the start (``'min'``) or the end (``'max'``)
of the axes, or using the rlabel position (``'rlabel'``).
"""
def __init__(self, axes, pad, mode):
super().__init__(pad, pad, axes.get_figure(root=False).dpi_scale_trans)
self.set_children(axes._realViewLim)
self.axes = axes
self.mode = mode
self.pad = pad
__str__ = mtransforms._make_str_method("axes", "pad", "mode")
def get_matrix(self):
if self._invalid:
if self.mode == 'rlabel':
angle = (
np.deg2rad(self.axes.get_rlabel_position()
* self.axes.get_theta_direction())
+ self.axes.get_theta_offset()
- np.pi / 2
)
elif self.mode == 'min':
angle = self.axes._realViewLim.xmin - np.pi / 2
elif self.mode == 'max':
angle = self.axes._realViewLim.xmax + np.pi / 2
self._t = (self.pad * np.cos(angle) / 72, self.pad * np.sin(angle) / 72)
return super().get_matrix()
| _ThetaShift |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 12702,
"end": 13713
} | class ____(TestModelMixin, TestBase):
def testRevert(self):
with reversion.create_revision():
obj = TestModel.objects.create()
with reversion.create_revision():
obj.name = "v2"
obj.save()
Version.objects.get_for_object(obj)[1].revert()
obj.refresh_from_db()
self.assertEqual(obj.name, "v1")
def testRevertBadSerializedData(self):
with reversion.create_revision():
obj = TestModel.objects.create()
Version.objects.get_for_object(obj).update(serialized_data="boom")
with self.assertRaises(reversion.RevertError):
Version.objects.get_for_object(obj).get().revert()
def testRevertBadFormat(self):
with reversion.create_revision():
obj = TestModel.objects.create()
Version.objects.get_for_object(obj).update(format="boom")
with self.assertRaises(reversion.RevertError):
Version.objects.get_for_object(obj).get().revert()
| RevertTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py | {
"start": 7105,
"end": 8630
} | class ____(EcsBaseTestCase):
@pytest.mark.parametrize(
("return_state", "expected"), [("ACTIVE", True), ("INACTIVE", False), ("DELETE_IN_PROGRESS", False)]
)
def test_default_values_poke(self, return_state, expected):
task = self.create_rendered_task(
EcsTaskDefinitionStateSensor, task_definition=TEST_TASK_DEFINITION_ARN
)
with mock.patch.object(task.hook, "get_task_definition_state") as m:
m.return_value = return_state
assert task.poke({}) == expected
m.assert_called_once_with(task_definition=TEST_TASK_DEFINITION_ARN)
@pytest.mark.parametrize(
("target_state", "return_state", "expected"),
[
(EcsTaskDefinitionStates.INACTIVE, "ACTIVE", False),
(EcsTaskDefinitionStates.INACTIVE, "INACTIVE", True),
(EcsTaskDefinitionStates.ACTIVE, "INACTIVE", False),
(EcsTaskDefinitionStates.ACTIVE, "ACTIVE", True),
],
)
def test_custom_values_poke(self, create_task_of_operator, target_state, return_state, expected):
task = self.create_rendered_task(
EcsTaskDefinitionStateSensor, task_definition=TEST_TASK_DEFINITION_ARN, target_state=target_state
)
with mock.patch.object(task.hook, "get_task_definition_state") as m:
m.return_value = return_state
assert task.poke({}) == expected
m.assert_called_once_with(task_definition=TEST_TASK_DEFINITION_ARN)
| TestEcsTaskDefinitionStateSensor |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_discovery_api.py | {
"start": 1004,
"end": 6178
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="google_test",
conn_type="google_cloud_platform",
host="google",
schema="refresh_token",
login="client_id",
password="client_secret",
)
)
@patch("airflow.providers.google.common.hooks.discovery_api.build")
@patch("airflow.providers.google.common.hooks.discovery_api.GoogleDiscoveryApiHook._authorize")
def test_get_conn(self, mock_authorize, mock_build):
google_discovery_api_hook = GoogleDiscoveryApiHook(
gcp_conn_id="google_test", api_service_name="youtube", api_version="v2"
)
google_discovery_api_hook.get_conn()
mock_build.assert_called_once_with(
serviceName=google_discovery_api_hook.api_service_name,
version=google_discovery_api_hook.api_version,
http=mock_authorize.return_value,
cache_discovery=False,
)
@patch("airflow.providers.google.common.hooks.discovery_api.getattr")
@patch("airflow.providers.google.common.hooks.discovery_api.GoogleDiscoveryApiHook.get_conn")
def test_query(self, mock_get_conn, mock_getattr):
google_discovery_api_hook = GoogleDiscoveryApiHook(
gcp_conn_id="google_test", api_service_name="analyticsreporting", api_version="v4"
)
endpoint = "analyticsreporting.reports.batchGet"
data = {
"body": {
"reportRequests": [
{
"viewId": "180628393",
"dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
"metrics": [{"expression": "ga:sessions"}],
"dimensions": [{"name": "ga:country"}],
}
]
}
}
num_retries = 1
google_discovery_api_hook.query(endpoint, data, num_retries=num_retries)
google_api_endpoint_name_parts = endpoint.split(".")
mock_getattr.assert_has_calls(
[
call(mock_get_conn.return_value, google_api_endpoint_name_parts[1]),
call()(),
call(mock_getattr.return_value.return_value, google_api_endpoint_name_parts[2]),
call()(**data),
call()().execute(num_retries=num_retries),
]
)
@patch("airflow.providers.google.common.hooks.discovery_api.getattr")
@patch("airflow.providers.google.common.hooks.discovery_api.GoogleDiscoveryApiHook.get_conn")
def test_query_with_pagination(self, mock_get_conn, mock_getattr):
google_api_conn_client_sub_call = mock_getattr.return_value.return_value
mock_getattr.return_value.side_effect = [
google_api_conn_client_sub_call,
google_api_conn_client_sub_call,
google_api_conn_client_sub_call,
google_api_conn_client_sub_call,
google_api_conn_client_sub_call,
None,
]
google_discovery_api_hook = GoogleDiscoveryApiHook(
gcp_conn_id="google_test", api_service_name="analyticsreporting", api_version="v4"
)
endpoint = "analyticsreporting.reports.batchGet"
data = {
"body": {
"reportRequests": [
{
"viewId": "180628393",
"dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
"metrics": [{"expression": "ga:sessions"}],
"dimensions": [{"name": "ga:country"}],
}
]
}
}
num_retries = 1
google_discovery_api_hook.query(endpoint, data, paginate=True, num_retries=num_retries)
api_endpoint_name_parts = endpoint.split(".")
google_api_conn_client = mock_get_conn.return_value
mock_getattr.assert_has_calls(
[
call(google_api_conn_client, api_endpoint_name_parts[1]),
call()(),
call(google_api_conn_client_sub_call, api_endpoint_name_parts[2]),
call()(**data),
call()().__bool__(),
call()().execute(num_retries=num_retries),
call(google_api_conn_client, api_endpoint_name_parts[1]),
call()(),
call(google_api_conn_client_sub_call, api_endpoint_name_parts[2] + "_next"),
call()(google_api_conn_client_sub_call, google_api_conn_client_sub_call.execute.return_value),
call()().__bool__(),
call()().execute(num_retries=num_retries),
call(google_api_conn_client, api_endpoint_name_parts[1]),
call()(),
call(google_api_conn_client_sub_call, api_endpoint_name_parts[2] + "_next"),
call()(google_api_conn_client_sub_call, google_api_conn_client_sub_call.execute.return_value),
]
)
| TestGoogleDiscoveryApiHook |
python | FactoryBoy__factory_boy | tests/test_transformer.py | {
"start": 2449,
"end": 2682
} | class ____(factory.Factory):
class Meta:
model = TestObject
one = factory.Transformer("", transform=str.upper)
two = factory.Transformer(factory.Sequence(int), transform=lambda n: n ** 2)
| TransformDeclarationFactory |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 76374,
"end": 79331
} | class ____(VariableTracker):
"""
Used to represent a wrapper object that contains the actual callable as an
attribute. For example, torch.jit.script/trace have the original function at
their _torchdynamo_inline attribute. Similarly, functions with
__script_if_tracing_wrapper have the original attr at "__original_fn".
"""
def __init__(self, wrapper_obj: Any, attr_to_trace: str, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.wrapper_obj = wrapper_obj
self.attr_to_trace = attr_to_trace
def var_getattr(self, tx: "InstructionTranslator", name: str) -> VariableTracker:
if name == self.attr_to_trace:
val = getattr(self.wrapper_obj, self.attr_to_trace)
source = self.source and AttrSource(self.source, name)
return VariableTracker.build(tx, val, source)
return super().var_getattr(tx, name)
def self_args(self) -> list[VariableTracker]:
return []
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if hasattr(self.wrapper_obj, "cache_info"):
target_fn = getattr(self.wrapper_obj, self.attr_to_trace, None)
module_name = getattr(target_fn, "__module__", "") or ""
if module_name.split(".", maxsplit=1)[0] != "torch":
msg = (
"Dynamo detected a call to a `functools.lru_cache`-wrapped "
"function. Dynamo ignores the cache wrapper and directly "
"traces the wrapped function. Silent incorrectness is only "
"a *potential* risk, not something we have observed. "
'Enable TORCH_LOGS="+dynamo" for a DEBUG stack trace.'
)
torch._dynamo.utils.warn_once(msg)
dynamo_logger = torch._dynamo.utils.logging.getLogger("torch._dynamo")
if dynamo_logger.isEnabledFor(logging.DEBUG):
user_stack = torch._guards.TracingContext.extract_stack()
user_stack = get_stack_above_dynamo() + user_stack
frame_loc = (user_stack[-1].filename, user_stack[-1].lineno)
user_stack_formatted = "".join(traceback.format_list(user_stack))
user_stack_trace = f"call to a lru_cache wrapped function at: {frame_loc[0]}:{frame_loc[1]}\n"
user_stack_trace += str(user_stack_formatted)
dynamo_logger.debug(user_stack_trace)
all_args = self.self_args() + list(args)
return variables.UserFunctionVariable(
polyfills.getattr_and_trace # type: ignore[arg-type]
).call_function(
tx,
[self, variables.ConstantVariable(self.attr_to_trace), *all_args],
kwargs,
)
| WrapperUserFunctionVariable |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 4330,
"end": 4454
} | class ____(ExpressionElementRole[_T]):
__slots__ = ()
_role_name = "Constant True/False/None expression"
| ConstExprRole |
python | django__django | django/db/models/expressions.py | {
"start": 5223,
"end": 16888
} | class ____:
"""Base class for all query expressions."""
empty_result_set_value = NotImplemented
# aggregate specific fields
is_summary = False
# Can the expression be used in a WHERE clause?
filterable = True
# Can the expression be used as a source expression in Window?
window_compatible = False
# Can the expression be used as a database default value?
allowed_default = False
# Can the expression be used during a constraint validation?
constraint_validation_compatible = True
# Does the expression possibly return more than one row?
set_returning = False
# Does the expression allow composite expressions?
allows_composite_expressions = False
def __init__(self, output_field=None):
if output_field is not None:
self.output_field = output_field
def __getstate__(self):
state = self.__dict__.copy()
state.pop("convert_value", None)
return state
def get_db_converters(self, connection):
return (
[]
if self.convert_value is self._convert_value_noop
else [self.convert_value]
) + self.output_field.get_db_converters(connection)
def get_source_expressions(self):
return []
def set_source_expressions(self, exprs):
assert not exprs
def _parse_expressions(self, *expressions):
return [
(
arg
if hasattr(arg, "resolve_expression")
else (F(arg) if isinstance(arg, str) else Value(arg))
)
for arg in expressions
]
def as_sql(self, compiler, connection):
"""
Responsible for returning a (sql, [params]) tuple to be included
in the current query.
Different backends can provide their own implementation, by
providing an `as_{vendor}` method and patching the Expression:
```
def override_as_sql(self, compiler, connection):
# custom logic
return super().as_sql(compiler, connection)
setattr(Expression, 'as_' + connection.vendor, override_as_sql)
```
Arguments:
* compiler: the query compiler responsible for generating the query.
Must have a compile method, returning a (sql, [params]) tuple.
Calling compiler(value) will return a quoted `value`.
* connection: the database connection used for the current query.
Return: (sql, params)
Where `sql` is a string containing ordered sql parameters to be
replaced with the elements of the list `params`.
"""
raise NotImplementedError("Subclasses must implement as_sql()")
@cached_property
def contains_aggregate(self):
return any(
expr and expr.contains_aggregate for expr in self.get_source_expressions()
)
@cached_property
def contains_over_clause(self):
return any(
expr and expr.contains_over_clause for expr in self.get_source_expressions()
)
@cached_property
def contains_column_references(self):
return any(
expr and expr.contains_column_references
for expr in self.get_source_expressions()
)
@cached_property
def contains_subquery(self):
return any(
expr and (getattr(expr, "subquery", False) or expr.contains_subquery)
for expr in self.get_source_expressions()
)
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
"""
Provide the chance to do any preprocessing or validation before being
added to the query.
Arguments:
* query: the backend query implementation
* allow_joins: boolean allowing or denying use of joins
in this query
* reuse: a set of reusable joins for multijoins
* summarize: a terminal aggregate clause
* for_save: whether this expression about to be used in a save or
update
Return: an Expression to be added to the query.
"""
c = self.copy()
c.is_summary = summarize
source_expressions = [
(
expr.resolve_expression(query, allow_joins, reuse, summarize, for_save)
if expr is not None
else None
)
for expr in c.get_source_expressions()
]
if not self.allows_composite_expressions and any(
isinstance(expr, ColPairs) for expr in source_expressions
):
raise ValueError(
f"{self.__class__.__name__} expression does not support "
"composite primary keys."
)
c.set_source_expressions(source_expressions)
return c
@property
def conditional(self):
return isinstance(self.output_field, fields.BooleanField)
@property
def field(self):
return self.output_field
@cached_property
def output_field(self):
"""Return the output type of this expressions."""
output_field = self._resolve_output_field()
if output_field is None:
raise OutputFieldIsNoneError(
"Cannot resolve expression type, unknown output_field"
)
return output_field
@property
def _output_field_or_none(self):
"""
Return the output field of this expression, or None if
_resolve_output_field() didn't return an output type.
"""
try:
return self.output_field
except OutputFieldIsNoneError:
return
def _resolve_output_field(self):
"""
Attempt to infer the output type of the expression.
As a guess, if the output fields of all source fields match then simply
infer the same type here.
If a source's output field resolves to None, exclude it from this
check. If all sources are None, then an error is raised higher up the
stack in the output_field property.
"""
# This guess is mostly a bad idea, but there is quite a lot of code
# (especially 3rd party Func subclasses) that depend on it, we'd need a
# deprecation path to fix it.
sources_iter = (
source for source in self.get_source_fields() if source is not None
)
for output_field in sources_iter:
for source in sources_iter:
if not isinstance(output_field, source.__class__):
raise FieldError(
"Expression contains mixed types: %s, %s. You must "
"set output_field."
% (
output_field.__class__.__name__,
source.__class__.__name__,
)
)
return output_field
@staticmethod
def _convert_value_noop(value, expression, connection):
return value
@cached_property
def convert_value(self):
"""
Expressions provide their own converters because users have the option
of manually specifying the output_field which may be a different type
from the one the database returns.
"""
field = self.output_field
internal_type = field.get_internal_type()
if internal_type == "FloatField":
return lambda value, expression, connection: (
None if value is None else float(value)
)
elif internal_type.endswith("IntegerField"):
return lambda value, expression, connection: (
None if value is None else int(value)
)
elif internal_type == "DecimalField":
return lambda value, expression, connection: (
None if value is None else Decimal(value)
)
return self._convert_value_noop
def get_lookup(self, lookup):
return self.output_field.get_lookup(lookup)
def get_transform(self, name):
return self.output_field.get_transform(name)
def relabeled_clone(self, change_map):
clone = self.copy()
clone.set_source_expressions(
[
e.relabeled_clone(change_map) if e is not None else None
for e in self.get_source_expressions()
]
)
return clone
def replace_expressions(self, replacements):
if not replacements:
return self
if replacement := replacements.get(self):
return replacement
if not (source_expressions := self.get_source_expressions()):
return self
clone = self.copy()
clone.set_source_expressions(
[
None if expr is None else expr.replace_expressions(replacements)
for expr in source_expressions
]
)
return clone
def get_refs(self):
refs = set()
for expr in self.get_source_expressions():
if expr is None:
continue
refs |= expr.get_refs()
return refs
def copy(self):
return copy.copy(self)
def prefix_references(self, prefix):
clone = self.copy()
clone.set_source_expressions(
[
(
F(f"{prefix}{expr.name}")
if isinstance(expr, F)
else expr.prefix_references(prefix)
)
for expr in self.get_source_expressions()
]
)
return clone
def get_group_by_cols(self):
if not self.contains_aggregate:
return [self]
cols = []
for source in self.get_source_expressions():
cols.extend(source.get_group_by_cols())
return cols
def get_source_fields(self):
"""Return the underlying field types used by this aggregate."""
return [e._output_field_or_none for e in self.get_source_expressions()]
def asc(self, **kwargs):
return OrderBy(self, **kwargs)
def desc(self, **kwargs):
return OrderBy(self, descending=True, **kwargs)
def reverse_ordering(self):
return self
def flatten(self):
"""
Recursively yield this expression and all subexpressions, in
depth-first order.
"""
yield self
for expr in self.get_source_expressions():
if expr:
if hasattr(expr, "flatten"):
yield from expr.flatten()
else:
yield expr
def select_format(self, compiler, sql, params):
"""
Custom format for select clauses. For example, EXISTS expressions need
to be wrapped in CASE WHEN on Oracle.
"""
if hasattr(self.output_field, "select_format"):
return self.output_field.select_format(compiler, sql, params)
return sql, params
def get_expression_for_validation(self):
# Ignore expressions that cannot be used during a constraint
# validation.
if not getattr(self, "constraint_validation_compatible", True):
try:
(expression,) = self.get_source_expressions()
except ValueError as e:
raise ValueError(
"Expressions with constraint_validation_compatible set to False "
"must have only one source expression."
) from e
else:
return expression
return self
@deconstructible
| BaseExpression |
python | numba__numba | numba/cuda/dispatcher.py | {
"start": 19839,
"end": 20356
} | class ____(CacheImpl):
def reduce(self, kernel):
return kernel._reduce_states()
def rebuild(self, target_context, payload):
return _Kernel._rebuild(**payload)
def check_cachable(self, cres):
# CUDA Kernels are always cachable - the reasons for an entity not to
# be cachable are:
#
# - The presence of lifted loops, or
# - The presence of dynamic globals.
#
# neither of which apply to CUDA kernels.
return True
| CUDACacheImpl |
python | huggingface__transformers | src/transformers/models/marian/modeling_marian.py | {
"start": 2461,
"end": 5173
} | class ____(nn.Embedding):
"""This module produces sinusoidal positional embeddings of any length."""
def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None) -> None:
super().__init__(num_positions, embedding_dim, _freeze=True)
def create_weight(self):
"""
Identical to the XLM create_sinusoidal_embeddings except features are not interleaved. The cos features are in
the 2nd half of the vector. [dim // 2:]
"""
n_pos, dim = self.weight.shape
position_enc = np.array(
[[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)]
)
out = torch.empty(n_pos, dim, dtype=self.weight.dtype, requires_grad=False)
sentinel = dim // 2 if dim % 2 == 0 else (dim // 2) + 1
out[:, 0:sentinel] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
out[:, sentinel:] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
return out
@torch.no_grad()
def forward(
self, input_ids_shape: torch.Size, past_key_values_length: int = 0, position_ids: Optional[torch.Tensor] = None
) -> torch.Tensor:
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
if position_ids is None:
bsz, seq_len = input_ids_shape[:2]
position_ids = torch.arange(
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
)
return super().forward(position_ids)
# Copied from transformers.models.bert.modeling_bert.eager_attention_forward
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: Optional[float] = None,
dropout: float = 0.0,
**kwargs: Unpack[TransformersKwargs],
):
if scaling is None:
scaling = query.size(-1) ** -0.5
# Take the dot product between "query" and "key" to get the raw attention scores.
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
if attention_mask is not None:
attention_mask = attention_mask[:, :, :, : key.shape[-2]]
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
# Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->Marian
| MarianSinusoidalPositionalEmbedding |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_member_team_details.py | {
"start": 3414,
"end": 7320
} | class ____(OrganizationMemberTeamTestBase):
method = "post"
def test_manager_can_join_team(self) -> None:
self.login_as(self.manager)
self.get_success_response(
self.org.slug, self.manager.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.manager
).exists()
def test_owner_can_join_team(self) -> None:
owner = self.create_member(organization=self.org, user=self.create_user(), role="owner")
self.login_as(owner)
self.get_success_response(
self.org.slug, owner.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=owner
).exists()
def test_admin_on_team_can_add_members_to_team(self) -> None:
self.login_as(self.admin_on_team)
# member
self.get_success_response(
self.org.slug, self.member.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.member
).exists()
# manager
self.get_success_response(
self.org.slug, self.manager.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.manager
).exists()
def test_manager_can_add_members_to_team(self) -> None:
self.login_as(self.manager)
# member
self.get_success_response(
self.org.slug, self.member.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.member
).exists()
# owner
self.get_success_response(
self.org.slug, self.owner.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.owner.id
).exists()
def test_owner_can_add_members_to_team(self) -> None:
self.login_as(self.owner)
# member
self.get_success_response(
self.org.slug, self.member.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.member
).exists()
# manager
self.get_success_response(
self.org.slug, self.manager.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=self.manager
).exists()
# owner
target_owner = self.create_member(
organization=self.org, user=self.create_user(), role="owner"
)
self.get_success_response(
self.org.slug, target_owner.id, self.team.slug, status_code=status.HTTP_201_CREATED
)
assert OrganizationMemberTeam.objects.filter(
team=self.team, organizationmember=target_owner
).exists()
@patch(
"sentry.roles.organization_roles.get",
wraps=mock_organization_roles_get_factory(organization_roles.get),
)
def test_cannot_add_to_team_when_team_roles_disabled(self, mock_get: MagicMock) -> None:
self.login_as(self.manager)
response = self.get_error_response(
self.org.slug, self.member.id, self.team.slug, status_code=403
)
assert (
response.data["detail"]
== "The user with a 'member' role cannot have team-level permissions."
)
| CreateOrganizationMemberTeamTest |
python | ray-project__ray | python/ray/serve/exceptions.py | {
"start": 917,
"end": 1355
} | class ____(RayServeException, TaskCancelledError):
"""Raise when a Serve request is cancelled."""
def __init__(self, request_id: Optional[str] = None):
self._request_id: Optional[str] = request_id
def __str__(self):
if self._request_id:
return f"Request {self._request_id} was cancelled."
else:
return "Request was cancelled."
@PublicAPI(stability="alpha")
| RequestCancelledError |
python | tensorflow__tensorflow | tensorflow/tools/proto_splitter/split_test.py | {
"start": 4858,
"end": 4942
} | class ____(split.ComposableSplitter):
def build_chunks(self):
pass
| NoOpSplitter |
python | joke2k__faker | tests/providers/test_address.py | {
"start": 103017,
"end": 103720
} | class ____:
"""Test pl_PL address provider methods"""
def test_postcode(self, faker, num_samples):
for _ in range(num_samples):
postcode = faker.postcode()
match = re.findall(r"^\d{2}-\d{3}$", postcode)
assert match
def test_zipcode(self, faker, num_samples):
for _ in range(num_samples):
zipcode = faker.zipcode()
match = re.findall(r"^\d{2}-\d{3}$", zipcode)
assert match
def test_postalcode(self, faker, num_samples):
for _ in range(num_samples):
postalcode = faker.postalcode()
match = re.findall(r"^^\d{2}-\d{3}$$", postalcode)
assert match
| TestPlPl |
python | scipy__scipy | scipy/_lib/_sparse.py | {
"start": 59,
"end": 875
} | class ____(ABC):
pass
def issparse(x):
"""Is `x` of a sparse array or sparse matrix type?
Parameters
----------
x
object to check for being a sparse array or sparse matrix
Returns
-------
bool
True if `x` is a sparse array or a sparse matrix, False otherwise
Notes
-----
Use `isinstance(x, sp.sparse.sparray)` to check between an array or matrix.
Use `a.format` to check the sparse format, e.g. `a.format == 'csr'`.
Examples
--------
>>> import numpy as np
>>> from scipy.sparse import csr_array, csr_matrix, issparse
>>> issparse(csr_matrix([[5]]))
True
>>> issparse(csr_array([[5]]))
True
>>> issparse(np.array([[5]]))
False
>>> issparse(5)
False
"""
return isinstance(x, SparseABC)
| SparseABC |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-baiduvectordb/llama_index/vector_stores/baiduvectordb/base.py | {
"start": 1688,
"end": 1910
} | class ____:
name: str
data_type: str = "STRING"
def __init__(self, name: str, data_type: str = "STRING"):
self.name = name
self.data_type = "STRING" if data_type is None else data_type
| TableField |
python | mlflow__mlflow | tests/dspy/test_save.py | {
"start": 1046,
"end": 1263
} | class ____(dspy.Module):
def __init__(self):
super().__init__()
self.prog = dspy.ChainOfThought("question -> answer")
def forward(self, question):
return self.prog(question=question)
| CoT |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_twodim_base.py | {
"start": 17260,
"end": 17543
} | class ____(TestCase):
def test_exceptions(self):
assert_raises(ValueError, triu_indices_from, np.ones((2,)))
assert_raises(ValueError, triu_indices_from, np.ones((2, 2, 2)))
# assert_raises(ValueError, triu_indices_from, np.ones((2, 3)))
| TestTriuIndicesFrom |
python | pytorch__pytorch | test/nn/test_pooling.py | {
"start": 1211,
"end": 6540
} | class ____(TestCase):
def _sum_pool2d(self, x, kernel_size):
windows = torch.nn.functional.unfold(
x, kernel_size=kernel_size, stride=kernel_size
)
return torch.sum(windows, dim=1)
def _sum_pool3d(self, x, kernel_size):
# Because unfold does not support 3D sliding window we will split tensor to multiple tensors and calculate sum
h = kernel_size[0]
splited_x = [t.sum(0) for t in x.split(h) if t.size(0) == h]
# sum_pool2d assumes tensor in (1, 1, n, m) view, so unsqueeze two times
splited_x = [
self._sum_pool2d(t.unsqueeze(0).unsqueeze(0), kernel_size[1:])
for t in splited_x
]
joined_x = torch.cat(splited_x)
return joined_x.view(1, joined_x.numel())
def _avg_pool2d(self, x, kernel_size):
size = reduce(operator.mul, kernel_size)
return self._sum_pool2d(x, kernel_size) / size
def _avg_pool3d(self, x, kernel_size):
size = reduce(operator.mul, kernel_size)
return self._sum_pool3d(x, kernel_size) / size
def test_doubletensor_avg_pool2d(self):
n, m = 5, 8
input = torch.rand(1, 1, n, m, dtype=torch.double)
for i in range(1, n + 1):
for j in range(1, m + 1):
actual = torch.nn.functional.avg_pool2d(input[0], (i, j))
actual = actual.view(1, actual.numel())
expected = self._avg_pool2d(input, (i, j))
self.assertEqual(actual, expected, rtol=0, atol=1e-5)
def test_doubletensor_avg_pool2d_with_divisor(self):
n, m = 3, 3
input = torch.rand(1, 1, n, m, dtype=torch.double)
for i in range(1, n + 1):
for j in range(1, m + 1):
for divisor in [1, 7, i * j]:
actual = F.avg_pool2d(input[0], (i, j), divisor_override=divisor)
actual = actual.view(1, actual.numel())
expected = self._sum_pool2d(input, (i, j)) / divisor
self.assertEqual(actual, expected, rtol=0, atol=1e-5)
def test_doubletensor_avg_pool3d(self):
h, w, d = 5, 6, 7
input = torch.rand(h, w, d, dtype=torch.double)
for i in range(1, h + 1):
for j in range(1, w + 1):
for k in range(1, d + 1):
actual = torch.nn.functional.avg_pool3d(
input.unsqueeze(0), (i, j, k)
)
actual = actual.view(1, actual.numel())
expected = self._avg_pool3d(input, (i, j, k))
self.assertEqual(actual, expected, rtol=0, atol=1e-5)
def test_doubletensor_avg_pool3d_with_divisor(self):
h, w, d = 6, 5, 7
input = torch.rand(h, w, d, dtype=torch.double)
for i in range(1, h + 1):
for j in range(1, w + 1):
for k in range(1, d + 1):
for divisor in [1, 7, i * j]:
actual = torch.nn.functional.avg_pool3d(
input.unsqueeze(0), (i, j, k), divisor_override=divisor
)
actual = actual.view(1, actual.numel())
expected = self._sum_pool3d(input, (i, j, k)) / divisor
self.assertEqual(actual, expected, rtol=0, atol=1e-5)
def test_avg_pool1d_ceil_mode(self):
# Regression test for gh-36977
x = 10 * torch.randn((1, 16, 4))
y = torch.nn.functional.avg_pool1d(
x, ceil_mode=True, count_include_pad=True, kernel_size=1, stride=2
)
self.assertTrue(not torch.isnan(y).any())
if TEST_CUDA:
y = torch.nn.functional.avg_pool1d(
x.to("cuda"),
ceil_mode=True,
count_include_pad=True,
kernel_size=1,
stride=2,
)
self.assertTrue(not torch.isnan(y).any())
def test_avg_pool2d_ceil_mode(self):
# Regression test for gh-36977
x = 10 * torch.randn((1, 16, 4, 4))
y = torch.nn.functional.avg_pool2d(
x,
ceil_mode=True,
count_include_pad=True,
kernel_size=(1, 2),
padding=(0, 1),
stride=2,
)
self.assertTrue(not torch.isnan(y).any())
if TEST_CUDA:
y = torch.nn.functional.avg_pool2d(
x.to("cuda"),
ceil_mode=True,
count_include_pad=True,
kernel_size=(1, 2),
padding=(0, 1),
stride=2,
)
self.assertTrue(not torch.isnan(y).any())
def test_avg_pool3d_ceil_mode(self):
# Regression test for gh-36977
x = 10 * torch.randn((1, 16, 4, 4, 4))
y = torch.nn.functional.avg_pool3d(
x, ceil_mode=True, count_include_pad=True, kernel_size=(1, 2, 3), stride=2
)
self.assertTrue(not torch.isnan(y).any())
if TEST_CUDA:
y = torch.nn.functional.avg_pool3d(
x.to("cuda"),
ceil_mode=True,
count_include_pad=True,
kernel_size=(1, 2, 3),
stride=2,
)
self.assertTrue(not torch.isnan(y).any())
| TestAvgPool |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/missingSuper1.py | {
"start": 1153,
"end": 1213
} | class ____(ParentC):
def __init__(self):
pass
| ChildE |
python | apache__airflow | airflow-core/src/airflow/jobs/triggerer_job_runner.py | {
"start": 28056,
"end": 28230
} | class ____(TypedDict):
"""Type class for the trigger details dictionary."""
task: asyncio.Task
name: str
events: int
@attrs.define(kw_only=True)
| TriggerDetails |
python | ansible__ansible | test/lib/ansible_test/_internal/python_requirements.py | {
"start": 2409,
"end": 2528
} | class ____(PipCommand):
"""Details required to get the pip version."""
@dataclasses.dataclass(frozen=True)
| PipVersion |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_diff_less_than_threshold.py | {
"start": 5506,
"end": 12631
} | class ____(ProfileNumericColumnsDiffExpectation):
"""Expect a statistic's value for a given column of a DataProfiler difference report to be less than the specified threshold.
This expectation takes the difference report between the data it is called on and a DataProfiler profile of the same schema loaded from a provided path.
This function builds upon the custom ProfileNumericColumnsDiff Expectation of Capital One's DataProfiler Expectations.
Each numerical column will be checked against a user provided dictionary of columns paired with dictionaries of statistics containing a threshold value.
It is expected that a statistics value for a given column is less than the specified threshold.
Args:
profile_path (str): A path to a saved DataProfiler profile object on the local filesystem.
limit_check_report_keys (dict): A dict, containing column names as keys and dicts as values that contain statistics as keys and ints or floats as values
denoting the threshold that the statistic delta is expectated to exceed.
mostly (float - optional): a value indicating the lower bound percentage of successful values that must be present to evaluate to success=True.
validator.expect_profile_numerical_columns_diff_less_than_threshold(
profile_path = "C:/path_to/my_profile.pkl",
limit_check_report_keys = {
"column_one": {
"min": 0
},
"*": {
"*": 1
},
}
)
Note: In limit_check_report_keys, "*" in place of a column denotes a general operator in which the value it stores will be applied to every column in the data that has no explicit key.
"*" in place of a statistic denotes a general operator in which the bounds it stores will be applied to every statistic for the given column that has no explicit key.
"""
example_profile_data = [
[2, 5, "10", "ten", 25],
[4, 10, "20", "twenty", 50],
[6, 15, "30", "thirty", 75],
[8, 20, "40", "forty", 100],
[10, 25, "50", "fifty", 125],
]
example_profile_columns = [
"by_2",
"by_5",
"str_by_10",
"words_by_10",
"by_25",
]
df = pd.DataFrame(example_profile_data, columns=example_profile_columns)
profiler_opts = dp.ProfilerOptions()
profiler_opts.structured_options.multiprocess.is_enabled = False
example_profile = dp.Profiler(df, options=profiler_opts)
profile_path = "/example_profiles/expect_profile_diff_less_than_threshold_profile.pkl"
dir_path = os.path.dirname(os.path.abspath(__file__)) # noqa: PTH120, PTH100
profile_path = dir_path + profile_path
example_profile.save(filepath=profile_path)
examples = [
{
"data": {
"by_2": [4, 6, 8, 10, 12],
"by_5": [10, 15, 20, 25, 30],
"str_by_10": ["20", "30", "40", "50", "60"],
"words_by_10": ["twenty", "thirty", "forty", "fifty", "sixty"],
"by_25": [50, 75, 100, 125, 150],
},
"tests": [
{
"title": "profile_min_delta_below_threshold",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {
"min": 1000,
},
},
},
"out": {"success": True},
},
{
"title": "profile_all_stats_above_delta_threshold",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": -1000},
"by_2": {
"min": 2,
},
},
},
"out": {"success": False},
},
{
"title": "checking_single_failure_in_one_column",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": 1000},
"by_2": {"min": 2},
},
},
"out": {"success": False},
},
{
"title": "single_failure_still_mostly_successful",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": 1000},
"by_2": {"min": 2},
},
"mostly": 0.75,
},
"out": {"success": True},
},
],
},
]
profile_metric = "data_profiler.profile_numeric_columns_diff_less_than_threshold"
success_keys = (
"profile_path",
"limit_check_report_keys",
"numerical_diff_statistics",
"mostly",
)
default_limit_check_report_keys = {
"*": {
"min": 0,
"max": 0,
"sum": 0,
"mean": 0,
"median": 0,
"median_absolute_deviation": 0,
"variance": 0,
"stddev": 0,
"unique_count": 0,
"unique_ratio": 0,
"gini_impurity": 0,
"unalikeability": 0,
"sample_size": 0,
"null_count": 0,
}
}
numerical_diff_statistics = list(default_limit_check_report_keys["*"].keys())
default_kwarg_values = {
"limit_check_report_keys": default_limit_check_report_keys,
"numerical_diff_statistics": numerical_diff_statistics,
"mostly": 1.0,
}
library_metadata = {
"requirements": ["dataprofiler", "tensorflow", "scikit-learn", "numpy"],
"maturity": "experimental", # "concept_only", "experimental", "beta", or "production"
"tags": [
"dataprofiler",
"dataassistance",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@stevensecreti", # Don't forget to add your github handle here!
],
}
if __name__ == "__main__":
diagnostics_report = ExpectProfileNumericColumnsDiffLessThanThreshold().run_diagnostics()
print(diagnostics_report.generate_checklist())
| ExpectProfileNumericColumnsDiffLessThanThreshold |
python | jupyterlab__jupyterlab | jupyterlab/labapp.py | {
"start": 10035,
"end": 10215
} | class ____(WorkspaceImportApp):
version = version
@default("workspaces_dir")
def _default_workspaces_dir(self):
return get_workspaces_dir()
| LabWorkspaceImportApp |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_aliases.py | {
"start": 1433,
"end": 3264
} | class ____:
def test_valid(self) -> None:
prop = bcpc.CoordinateLike()
assert prop.is_valid(-1.0)
assert prop.is_valid(-1)
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid(0.0)
assert prop.is_valid(1.0)
assert prop.is_valid("2020-01-11T13:00:00")
assert prop.is_valid("2020-01-11")
assert prop.is_valid(datetime.datetime.now())
assert prop.is_valid(datetime.time(10,12))
assert prop.is_valid(np.datetime64("2020-01-11"))
if is_installed("pandas"):
import pandas as pd
assert prop.is_valid(pd.Timestamp("2010-01-11"))
assert prop.is_valid("")
assert prop.is_valid(("", ""))
assert prop.is_valid(("", "", ""))
def test_invalid(self) -> None:
prop = bcpc.CoordinateLike()
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_valid(True)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid(())
assert not prop.is_valid([])
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
# TODO (bev) class Test_TimeDelta(object)
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
Test___all__ = verify_all(bcpc, ALL)
| Test_CoordinateLike |
python | python__mypy | mypy/nodes.py | {
"start": 64186,
"end": 64622
} | class ____(Expression):
"""Integer literal"""
__slots__ = ("value",)
__match_args__ = ("value",)
value: int # 0 by default
def __init__(self, value: int) -> None:
super().__init__()
self.value = value
def accept(self, visitor: ExpressionVisitor[T]) -> T:
return visitor.visit_int_expr(self)
# How mypy uses StrExpr and BytesExpr:
#
# b'x' -> BytesExpr
# 'x', u'x' -> StrExpr
| IntExpr |
python | pydata__xarray | xarray/tests/test_datatree_mapping.py | {
"start": 7941,
"end": 9631
} | class ____:
def test_construct_using_type(self):
# from datatree GH issue https://github.com/xarray-contrib/datatree/issues/188
# xarray's .weighted is unusual because it uses type() to create a Dataset/DataArray
a = xr.DataArray(
np.random.rand(3, 4, 10),
dims=["x", "y", "time"],
coords={"area": (["x", "y"], np.random.rand(3, 4))},
).to_dataset(name="data")
b = xr.DataArray(
np.random.rand(2, 6, 14),
dims=["x", "y", "time"],
coords={"area": (["x", "y"], np.random.rand(2, 6))},
).to_dataset(name="data")
dt = xr.DataTree.from_dict({"a": a, "b": b})
def weighted_mean(ds):
if "area" not in ds.coords:
return None
return ds.weighted(ds.area).mean(["x", "y"])
dt.map_over_datasets(weighted_mean)
def test_alter_inplace_forbidden(self):
simpsons = xr.DataTree.from_dict(
{
"/": xr.Dataset({"age": 83}),
"/Herbert": xr.Dataset({"age": 40}),
"/Homer": xr.Dataset({"age": 39}),
"/Homer/Bart": xr.Dataset({"age": 10}),
"/Homer/Lisa": xr.Dataset({"age": 8}),
"/Homer/Maggie": xr.Dataset({"age": 1}),
},
name="Abe",
)
def fast_forward(ds: xr.Dataset, years: float) -> xr.Dataset:
"""Add some years to the age, but by altering the given dataset"""
ds["age"] = ds["age"] + years
return ds
with pytest.raises(AttributeError):
simpsons.map_over_datasets(fast_forward, 10)
| TestMutableOperations |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_watch_grpc_server.py | {
"start": 503,
"end": 1473
} | class ____(BaseTestSuite):
def test_grpc_server_handle_message_subscription(self, graphql_context):
events = []
test_subscriber = LocationStateSubscriber(events.append)
location = next(
iter(graphql_context.process_context.create_request_context().code_locations)
)
graphql_context.process_context.add_state_subscriber(test_subscriber)
location.client.shutdown_server()
# Wait for event
start_time = time.time()
timeout = 60
while not len(events) > 0:
if time.time() - start_time > timeout:
raise Exception("Timed out waiting for LocationStateChangeEvent")
time.sleep(1)
assert len(events) == 1
assert isinstance(events[0], LocationStateChangeEvent)
assert events[0].event_type == LocationStateChangeEventType.LOCATION_ERROR
assert events[0].location_name == location.name
| TestSubscribeToGrpcServerEvents |
python | dask__distributed | distributed/shuffle/_core.py | {
"start": 15950,
"end": 16974
} | class ____(abc.ABC, Generic[_T_partition_id]):
id: ShuffleId
disk: bool
@property
@abc.abstractmethod
def output_partitions(self) -> Generator[_T_partition_id]:
"""Output partitions"""
@abc.abstractmethod
def pick_worker(self, partition: _T_partition_id, workers: Sequence[str]) -> str:
"""Pick a worker for a partition"""
def create_new_run(
self,
worker_for: dict[_T_partition_id, str],
span_id: str | None,
) -> SchedulerShuffleState:
return SchedulerShuffleState(
run_spec=ShuffleRunSpec(spec=self, worker_for=worker_for, span_id=span_id),
participating_workers=set(worker_for.values()),
)
@abc.abstractmethod
def create_run_on_worker(
self,
run_id: int,
span_id: str | None,
worker_for: dict[_T_partition_id, str],
plugin: ShuffleWorkerPlugin,
) -> ShuffleRun:
"""Create the new shuffle run on the worker."""
@dataclass(eq=False)
| ShuffleSpec |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 11121,
"end": 11336
} | class ____(Where):
"""Contains comparison for document content"""
key: str
content: str
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$contains": self.content}}
@dataclass
| Contains |
python | pytorch__pytorch | torch/utils/_debug_mode.py | {
"start": 10553,
"end": 12871
} | class ____(_DebugCall):
"""Normal operator call"""
def __init__(
self,
op,
args: tuple,
kwargs: dict,
call_depth: int,
stack: bool = False,
) -> None:
super().__init__(call_depth, stack=stack)
self.op = op
self.args = args
self.kwargs = kwargs
self.args_str: str | None = None
self.kwargs_str: str | None = None
def stringify_args(
self, attributes: list[str], tensor_memo: TensorIdTracker | None = None
) -> None:
self.args_str = ", ".join(
_arg_to_str(arg, attributes, tensor_memo) for arg in self.args
)
if self.kwargs:
self.kwargs_str = ", " + ", ".join(
f"{k}={_arg_to_str(v, attributes, tensor_memo)}"
for k, v in self.kwargs.items()
)
else:
self.kwargs_str = ""
del self.args
del self.kwargs
def render(self, attributes: list[str]) -> str:
if self.args_str is not None:
args_str = self.args_str
else:
args_str = ", ".join(_arg_to_str(arg, attributes) for arg in self.args)
if self.kwargs_str is not None:
kwargs_str = self.kwargs_str
else:
if self.kwargs:
kwargs_str = ", " + ", ".join(
f"{k}={_arg_to_str(v, attributes)}" for k, v in self.kwargs.items()
)
else:
kwargs_str = ""
if isinstance(self.op, torch._ops.OpOverload):
op_name = self.op.__qualname__
elif hasattr(self.op, "__module__") and hasattr(self.op, "__name__"):
op_name = f"{self.op.__module__}.{self.op.__name__}"
else:
op_name = str(self.op)
base_str = f"{op_name}({args_str}{kwargs_str})"
if self.output_str:
base_str += self.output_str
if self.log:
base_str += f" # {self.log}"
return base_str
def __iter__(self):
# for BC; tuple(self) returns (op, args, kwargs, call_depth)
if self.args_str is not None:
yield from [self.op, self.args_str, self.kwargs_str, self.call_depth]
else:
yield from [self.op, self.args, self.kwargs, self.call_depth]
| _OpCall |
python | wandb__wandb | wandb/automations/events.py | {
"start": 6980,
"end": 7840
} | class ____(GQLBase):
event_type: EventType
scope: AutomationScope
"""The scope of the event."""
filter: JsonEncoded[Any]
def then(self, action: InputAction) -> NewAutomation:
"""Define a new Automation in which this event triggers the given action."""
from .automations import NewAutomation
if isinstance(action, (InputActionTypes, SavedActionTypes)):
return NewAutomation(event=self, action=action)
raise TypeError(f"Expected a valid action, got: {nameof(type(action))!r}")
def __rshift__(self, other: InputAction) -> NewAutomation:
"""Implement `event >> action` to define an automation."""
return self.then(other)
# ------------------------------------------------------------------------------
# Events that trigger on specific mutations in the backend
| _BaseEventInput |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/auto_materialize_asset_evaluations.py | {
"start": 2024,
"end": 2307
} | class ____(graphene.ObjectType):
partitionKeysOrError = graphene.Field(GraphenePartitionKeysOrError)
evaluationData = graphene.Field(GrapheneAutoMaterializeRuleEvaluationData)
class Meta:
name = "AutoMaterializeRuleEvaluation"
| GrapheneAutoMaterializeRuleEvaluation |
python | scikit-learn__scikit-learn | asv_benchmarks/benchmarks/common.py | {
"start": 5612,
"end": 6478
} | class ____(ABC):
"""Abstract base class for benchmarks of estimators implementing predict"""
if Benchmark.bench_predict:
def time_predict(self, *args):
self.estimator.predict(self.X)
def peakmem_predict(self, *args):
self.estimator.predict(self.X)
if Benchmark.base_commit is not None:
def track_same_prediction(self, *args):
est_path = get_estimator_path(self, Benchmark.base_commit, args, True)
with est_path.open(mode="rb") as f:
estimator_base = pickle.load(f)
y_val_pred_base = estimator_base.predict(self.X_val)
y_val_pred = self.estimator.predict(self.X_val)
return np.allclose(y_val_pred_base, y_val_pred)
@property
@abstractmethod
def params(self):
pass
| Predictor |
python | pytorch__pytorch | benchmarks/functional_autograd_benchmark/torchaudio_models.py | {
"start": 4176,
"end": 4844
} | class ____(nn.Module):
def __init__(self, module):
"""
Collapses input of dim T*N*H to (T*N)*H, and applies to a module.
Allows handling of variable sequence lengths and minibatch sizes.
:param module: Module to apply input to.
"""
super().__init__()
self.module = module
def forward(self, x):
t, n = x.size(0), x.size(1)
x = x.view(t * n, -1)
x = self.module(x)
x = x.view(t, n, -1)
return x
def __repr__(self):
tmpstr = self.__class__.__name__ + " (\n"
tmpstr += self.module.__repr__()
tmpstr += ")"
return tmpstr
| SequenceWise |
python | allegroai__clearml | clearml/backend_api/services/v2_23/projects.py | {
"start": 148181,
"end": 153158
} | class ____(Request):
"""
Update project information
:param project: Project id
:type project: str
:param name: Project name. Unique within the company.
:type name: str
:param description: Project description
:type description: str
:param tags: User-defined tags list
:type tags: Sequence[str]
:param system_tags: System tags list. This field is reserved for system use,
please don't use it.
:type system_tags: Sequence[str]
:param default_output_destination: The default output destination URL for new
tasks under this project
:type default_output_destination: str
"""
_service = "projects"
_action = "update"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": "string",
},
"description": {"description": "Project description", "type": "string"},
"name": {
"description": "Project name. Unique within the company.",
"type": "string",
},
"project": {"description": "Project id", "type": "string"},
"system_tags": {
"description": "System tags list. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": "array",
},
"tags": {
"description": "User-defined tags list",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["project"],
"type": "object",
}
def __init__(
self,
project: str,
name: Optional[str] = None,
description: Optional[str] = None,
tags: Optional[List[str]] = None,
system_tags: Optional[List[str]] = None,
default_output_destination: Optional[str] = None,
**kwargs: Any
) -> None:
super(UpdateRequest, self).__init__(**kwargs)
self.project = project
self.name = name
self.description = description
self.tags = tags
self.system_tags = system_tags
self.default_output_destination = default_output_destination
@schema_property("project")
def project(self) -> str:
return self._property_project
@project.setter
def project(self, value: str) -> None:
if value is None:
self._property_project = None
return
self.assert_isinstance(value, "project", six.string_types)
self._property_project = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
@schema_property("description")
def description(self) -> Optional[str]:
return self._property_description
@description.setter
def description(self, value: Optional[str]) -> None:
if value is None:
self._property_description = None
return
self.assert_isinstance(value, "description", six.string_types)
self._property_description = value
@schema_property("tags")
def tags(self) -> Optional[List[str]]:
return self._property_tags
@tags.setter
def tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_tags = None
return
self.assert_isinstance(value, "tags", (list, tuple))
self.assert_isinstance(value, "tags", six.string_types, is_array=True)
self._property_tags = value
@schema_property("system_tags")
def system_tags(self) -> Optional[List[str]]:
return self._property_system_tags
@system_tags.setter
def system_tags(self, value: Optional[List[str]]) -> None:
if value is None:
self._property_system_tags = None
return
self.assert_isinstance(value, "system_tags", (list, tuple))
self.assert_isinstance(value, "system_tags", six.string_types, is_array=True)
self._property_system_tags = value
@schema_property("default_output_destination")
def default_output_destination(self) -> Optional[str]:
return self._property_default_output_destination
@default_output_destination.setter
def default_output_destination(self, value: Optional[str]) -> None:
if value is None:
self._property_default_output_destination = None
return
self.assert_isinstance(value, "default_output_destination", six.string_types)
self._property_default_output_destination = value
| UpdateRequest |
python | Textualize__textual | tests/command_palette/test_declare_sources.py | {
"start": 1715,
"end": 2178
} | class ____(Screen[None]):
def on_mount(self) -> None:
self.app.action_command_palette()
async def test_no_screen_command_sources() -> None:
"""An app with a screen with no sources declared should work fine."""
async with AppWithInitialScreen(ScreenWithNoSources()).run_test() as pilot:
assert isinstance(pilot.app.screen, CommandPalette)
assert pilot.app.screen._provider_classes == {SystemCommandsProvider}
| ScreenWithNoSources |
python | altair-viz__altair | altair/expr/core.py | {
"start": 7948,
"end": 8121
} | class ____(Expression):
def __init__(self, name) -> None:
super().__init__(name=name)
def __repr__(self) -> str:
return str(self.name)
| ConstExpression |
python | huggingface__transformers | src/transformers/models/plbart/modeling_plbart.py | {
"start": 37432,
"end": 43634
} | class ____(PLBartPreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: PLBartConfig):
super().__init__(config)
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
self.shared = PLBartScaledWordEmbedding(vocab_size, config.d_model, padding_idx, embed_scale=embed_scale)
self.encoder = PLBartEncoder(config)
self.decoder = PLBartDecoder(config)
self.post_init()
def get_input_embeddings(self):
return self.shared
def set_input_embeddings(self, value):
self.shared = value
self.encoder.embed_tokens = self.shared
self.decoder.embed_tokens = self.shared
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[list[torch.FloatTensor]] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
) -> Union[tuple[torch.Tensor], Seq2SeqModelOutput]:
r"""
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Indices of decoder input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`] or [`PLBartMultiTokenizer`] depending on the checkpoint.
See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
[What are decoder input IDs?](../glossary#decoder-input-ids)
PLBart uses a specific language id token as the starting token for `decoder_input_ids` generation that
varies according to source and target language, *e.g.* 50003 for *en_XX*, and 50001 for *java*. If
`past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
`past_key_values`).
For translation and summarization training, `decoder_input_ids` should be provided. If no
`decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
for denoising pre-training following the paper.
decoder_attention_mask (:
obj:*torch.LongTensor* of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior:
generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
use_cache = use_cache if use_cache is not None else self.config.use_cache
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# different to other models, PLBart automatically creates decoder_input_ids from
# input_ids if no decoder_input_ids are provided
if decoder_input_ids is None and decoder_inputs_embeds is None:
decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id)
if encoder_outputs is None:
encoder_outputs = self.encoder(
input_ids=input_ids,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
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,
)
# decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
decoder_outputs = self.decoder(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
encoder_hidden_states=encoder_outputs[0],
encoder_attention_mask=attention_mask,
past_key_values=past_key_values,
inputs_embeds=decoder_inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
cache_position=cache_position,
)
if not return_dict:
return decoder_outputs + encoder_outputs
return Seq2SeqModelOutput(
last_hidden_state=decoder_outputs.last_hidden_state,
past_key_values=decoder_outputs.past_key_values,
decoder_hidden_states=decoder_outputs.hidden_states,
decoder_attentions=decoder_outputs.attentions,
cross_attentions=decoder_outputs.cross_attentions,
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
encoder_hidden_states=encoder_outputs.hidden_states,
encoder_attentions=encoder_outputs.attentions,
)
@auto_docstring(
custom_intro="""
The PLBART Model with a language modeling head. Can be used for code-to-text, text-to-code and code-to-code.
"""
)
| PLBartModel |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 31211,
"end": 31764
} | class ____(PreTrainedModel):
config_class = Sam3Config
base_model_prefix = "sam3"
main_input_name = "pixel_values"
input_modalities = ["image", "text"]
_supports_sdpa = True
_supports_flash_attn = True
_supports_flex_attn = True
_supports_attention_backend = True
def _init_weights(self, module):
super()._init_weights(module)
if isinstance(module, Sam3ViTEmbeddings):
init.normal_(module.position_embeddings, mean=0.0, std=self.config.initializer_range)
@auto_docstring
| Sam3PreTrainedModel |
python | django-import-export__django-import-export | import_export/formats/base_formats.py | {
"start": 3488,
"end": 3585
} | class ____(TextFormat):
TABLIB_MODULE = "tablib.formats._csv"
CONTENT_TYPE = "text/csv"
| CSV |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.