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
huggingface__transformers
tests/models/clipseg/test_modeling_clipseg.py
{ "start": 20226, "end": 23437 }
class ____(unittest.TestCase): @slow def test_inference_image_segmentation(self): model_name = "CIDAS/clipseg-rd64-refined" processor = CLIPSegProcessor.from_pretrained(model_name) model = CLIPSegForImageSegmentation.from_pretrained(model_name).to(torch_device) image = prepare_img() texts = ["a cat", "a remote", "a blanket"] inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the predicted masks self.assertEqual( outputs.logits.shape, torch.Size((3, 352, 352)), ) expected_masks_slice = torch.tensor( [[-7.4613, -7.4785, -7.3628], [-7.3268, -7.0899, -7.1333], [-6.9838, -6.7900, -6.8913]] ).to(torch_device) torch.testing.assert_close(outputs.logits[0, :3, :3], expected_masks_slice, rtol=1e-3, atol=1e-3) # verify conditional and pooled output expected_conditional = torch.tensor([0.5601, -0.0314, 0.1980]).to(torch_device) expected_pooled_output = torch.tensor([0.5036, -0.2681, -0.2644]).to(torch_device) torch.testing.assert_close(outputs.conditional_embeddings[0, :3], expected_conditional, rtol=1e-3, atol=1e-3) torch.testing.assert_close(outputs.pooled_output[0, :3], expected_pooled_output, rtol=1e-3, atol=1e-3) @slow def test_inference_interpolate_pos_encoding(self): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. model = CLIPSegModel.from_pretrained("openai/clip-vit-base-patch32").to(torch_device) processor = CLIPSegProcessor.from_pretrained( "openai/clip-vit-base-patch32", size={"height": 180, "width": 180}, crop_size={"height": 180, "width": 180} ) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") inputs = processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device) # interpolate_pos_encodiung false should return value error with self.assertRaises(ValueError, msg="doesn't match model"): with torch.no_grad(): model(**inputs, interpolate_pos_encoding=False) # forward pass with torch.no_grad(): outputs = model(**inputs, interpolate_pos_encoding=True) # verify the logits expected_shape = torch.Size((1, 26, 768)) self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape) expected_slice = torch.tensor( [[-0.1538, 0.0322, -0.3235], [0.2893, 0.1135, -0.5708], [0.0461, 0.1540, -0.6018]] ).to(torch_device) torch.testing.assert_close( outputs.vision_model_output.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4 )
CLIPSegModelIntegrationTest
python
openai__openai-python
src/openai/resources/chat/completions/completions.py
{ "start": 161991, "end": 162846 }
class ____: def __init__(self, completions: Completions) -> None: self._completions = completions self.parse = to_streamed_response_wrapper( completions.parse, ) self.create = to_streamed_response_wrapper( completions.create, ) self.retrieve = to_streamed_response_wrapper( completions.retrieve, ) self.update = to_streamed_response_wrapper( completions.update, ) self.list = to_streamed_response_wrapper( completions.list, ) self.delete = to_streamed_response_wrapper( completions.delete, ) @cached_property def messages(self) -> MessagesWithStreamingResponse: return MessagesWithStreamingResponse(self._completions.messages)
CompletionsWithStreamingResponse
python
walkccc__LeetCode
solutions/1908. Game of Nim/1908.py
{ "start": 0, "end": 116 }
class ____: def nimGame(self, piles: list[int]) -> bool: return functools.reduce(operator.xor, piles) > 0
Solution
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 97401, "end": 104589 }
class ____(Expr): def __str__(self): return f"{type(self).__name__}({self.operands[0]})" @functools.cached_property def _name(self): return f"delayed-container-{self.deterministic_token}" def _layer(self) -> dict: from dask.delayed import Delayed if isinstance(self.operands[0], TaskRef): tasks = [ Alias((self._name, ix), fut.key) for ix, fut in enumerate(self.operands) ] dsk = {t.key: t for t in tasks} elif isinstance(self.operands[0], Delayed): expr = collections_to_expr(self.operands).optimize() keys = expr.__dask_keys__() dsk = expr.__dask_graph__() # Many APIs in dask-expr are not honoring __dask_keys__ but are instead # assuming they can just construct the keys themselves by walking the # partitions. Therefore we'll have to remap the key names and can't just # expose __dask_keys__() for ix, actual_key in enumerate(keys): dsk[(self._name, ix)] = Alias((self._name, ix), actual_key[0]) else: raise TypeError("Expected a Delayed or Future object") return dsk def _divisions(self): return (None,) * (len(self.operands) + 1) @property def ndim(self): return 0 def is_broadcastable(dfs, s): """ This Series is broadcastable against another dataframe in the sequence """ def compare(s, df): try: return s.divisions == (min(df.columns), max(df.columns)) except (TypeError, ValueError): return False return ( s.ndim == 1 and s.npartitions == 1 and s.known_divisions and any(compare(s, df) for df in dfs if df.ndim == 2) or s.ndim == 0 ) def are_co_aligned(*exprs): """Do inputs come from the same parents, modulo blockwise?""" from dask.dataframe.dask_expr._cumulative import CumulativeAggregations from dask.dataframe.dask_expr._reductions import Reduction seen = set() # Scalars can always be broadcasted stack = [e for e in exprs if e.ndim > 0] ancestors = [] while stack: e = stack.pop() if e._name in seen: continue seen.add(e._name) if isinstance(e, IO): ancestors.append(e) elif e.ndim == 0: # Scalars are valid ancestors that are always broadcastable, # so don't walk through them continue elif isinstance(e, (_DelayedExpr, Isin)): continue elif isinstance(e, (Blockwise, CumulativeAggregations, Reduction)): # TODO: Capture this in inheritance logic dependencies = e.dependencies() stack.extend(dependencies) else: ancestors.append(e) unique_ancestors = { # Account for column projection within IO expressions _tokenize_partial(item, ["columns", "_series", "_dataset_info_cache"]) for item in ancestors } # Don't check divisions or npartitions at all return len(unique_ancestors) <= 1 ## Utilities for Expr fusion def is_valid_blockwise_op(expr): return isinstance(expr, Blockwise) and not isinstance( expr, (FromPandas, FromArray, FromDelayed) ) def optimize_blockwise_fusion(expr): """Traverse the expression graph and apply fusion""" def _fusion_pass(expr): # Full pass to find global dependencies seen = set() stack = [expr] dependents = defaultdict(set) dependencies = {} expr_mapping = {} while stack: next = stack.pop() if next._name in seen: continue seen.add(next._name) if is_valid_blockwise_op(next): dependencies[next._name] = set() if next._name not in dependents: dependents[next._name] = set() expr_mapping[next._name] = next for operand in next.dependencies(): stack.append(operand) if is_valid_blockwise_op(operand): if next._name in dependencies: dependencies[next._name].add(operand._name) dependents[operand._name].add(next._name) expr_mapping[operand._name] = operand expr_mapping[next._name] = next # Traverse each "root" until we find a fusable sub-group. # Here we use root to refer to a Blockwise Expr node that # has no Blockwise dependents roots = [ expr_mapping[k] for k, v in dependents.items() if v == set() or all(not is_valid_blockwise_op(expr_mapping[_expr]) for _expr in v) ] while roots: root = roots.pop() seen = set() stack = [root] group = [] while stack: next = stack.pop() if next._name in seen: continue seen.add(next._name) group.append(next) for dep_name in dependencies[next._name]: dep = expr_mapping[dep_name] stack_names = {s._name for s in stack} group_names = {g._name for g in group} if ( dep.npartitions == root.npartitions or next._broadcast_dep(dep) ) and not (dependents[dep._name] - stack_names - group_names): # All of deps dependents are contained # in the local group (or the local stack # of expr nodes that we know we will be # adding to the local group). # All nodes must also have the same number # of partitions, since broadcasting within # a group is not allowed. stack.append(dep) elif dependencies[dep._name] and dep._name not in [ r._name for r in roots ]: # Couldn't fuse dep, but we may be able to # use it as a new root on the next pass roots.append(dep) # Replace fusable sub-group if len(group) > 1: group_deps = [] local_names = [_expr._name for _expr in group] for _expr in group: group_deps += [ operand for operand in _expr.dependencies() if operand._name not in local_names ] _ret = expr.substitute(group[0], Fused(group, *group_deps)) return _ret, not roots # Return original expr if no fusable sub-groups were found return expr, True while True: original_name = expr._name expr, done = _fusion_pass(expr) if done or expr._name == original_name: break return expr
DelayedsExpr
python
django__django
django/contrib/messages/storage/base.py
{ "start": 194, "end": 1512 }
class ____: """ Represent an actual message that can be stored in any of the supported storage classes (typically session- or cookie-based) and rendered in a view or template. """ def __init__(self, level, message, extra_tags=None): self.level = int(level) self.message = message self.extra_tags = extra_tags def _prepare(self): """ Prepare the message for serialization by forcing the ``message`` and ``extra_tags`` to str in case they are lazy translations. """ self.message = str(self.message) self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None def __eq__(self, other): if not isinstance(other, Message): return NotImplemented return self.level == other.level and self.message == other.message def __str__(self): return str(self.message) def __repr__(self): extra_tags = f", extra_tags={self.extra_tags!r}" if self.extra_tags else "" return f"Message(level={self.level}, message={self.message!r}{extra_tags})" @property def tags(self): return " ".join(tag for tag in [self.extra_tags, self.level_tag] if tag) @property def level_tag(self): return LEVEL_TAGS.get(self.level, "")
Message
python
Lightning-AI__lightning
tests/tests_pytorch/plugins/test_amp_plugins.py
{ "start": 2110, "end": 7342 }
class ____(BoringModel): # sister test: tests/trainer/optimization/test_manual_optimization.py::test_multiple_optimizers_step def on_after_backward(self) -> None: # check grads are scaled scale = self.trainer.precision_plugin.scaler.get_scale() assert scale != 1.0 # the return value if not enabled grads = [p.grad for p in self.parameters()] inv_scale = 1 / scale self.original_grads = [p * inv_scale for p in grads] def check_grads_unscaled(self, optimizer=None): if optimizer is not None: scaler = self.trainer.precision_plugin.scaler state = scaler._per_optimizer_states[id(optimizer)] assert state["stage"].name == "UNSCALED" grads = [p.grad for p in self.parameters()] assert len(grads) == len(self.original_grads) for actual, expected in zip(grads, self.original_grads): torch.testing.assert_close(actual, expected, equal_nan=True) def check_grads_clipped(self): parameters = list(self.parameters()) assert len(parameters) == len(self.clipped_parameters) for actual, expected in zip(parameters, self.clipped_parameters): torch.testing.assert_close(actual.grad, expected.grad, equal_nan=True) def on_before_optimizer_step(self, optimizer, *_): self.check_grads_unscaled(optimizer) # manually clip self.clipped_parameters = [] for p in self.parameters(): copy = p.detach().clone() copy.grad = p.grad.clone() self.clipped_parameters.append(copy) clip_val = self.trainer.gradient_clip_val torch.nn.utils.clip_grad_value_(self.clipped_parameters, clip_val) def configure_gradient_clipping(self, *args, **kwargs): # let lightning clip super().configure_gradient_clipping(*args, **kwargs) # check clipping worked as expected self.check_grads_clipped() def optimizer_step(self, epoch, batch_idx, optimizer, closure, **_): # pass self as a kwarg optimizer.step(closure, pl_module=self) def configure_optimizers(self): return TestClippingOptimizer(self.layer.parameters(), lr=0.1) @RunIf(min_cuda_gpus=2) @pytest.mark.parametrize("accum", [1, 2]) def test_amp_gradient_unscale(tmp_path, accum: int): model = TestPrecisionModel() trainer = Trainer( max_epochs=2, default_root_dir=tmp_path, limit_train_batches=2, limit_val_batches=0, strategy="ddp_spawn", accelerator="gpu", devices=2, precision="16-mixed", # use a tiny value to make sure it works gradient_clip_val=1e-3, gradient_clip_algorithm="value", log_every_n_steps=1, accumulate_grad_batches=accum, enable_progress_bar=False, ) trainer.fit(model) @RunIf(min_cuda_gpus=1) def test_amp_skip_optimizer(tmp_path): """Test that optimizers can be skipped when using amp.""" class CustomBoringModel(BoringModel): def __init__(self): super().__init__() self.automatic_optimization = False self.layer1 = torch.nn.Linear(32, 32) self.layer2 = torch.nn.Linear(32, 2) def forward(self, x: Tensor): x = self.layer1(x) return self.layer2(x) def training_step(self, batch, batch_idx): _, opt2 = self.optimizers() output = self(batch) loss = self.loss(output) opt2.zero_grad() self.manual_backward(loss) # only optimizer 2 steps opt2.step() def configure_optimizers(self): return [ torch.optim.SGD(self.layer1.parameters(), lr=0.1), torch.optim.SGD(self.layer2.parameters(), lr=0.1), ] trainer = Trainer(default_root_dir=tmp_path, accelerator="gpu", devices=1, fast_dev_run=1, precision="16-mixed") model = CustomBoringModel() trainer.fit(model) def test_cpu_amp_precision_context_manager(): """Test to ensure that the context manager correctly is set to CPU + bfloat16.""" plugin = MixedPrecision("bf16-mixed", "cpu") assert plugin.device == "cpu" assert plugin.scaler is None context_manager = plugin.autocast_context_manager() assert isinstance(context_manager, torch.autocast) assert context_manager.fast_dtype == torch.bfloat16 def test_amp_precision_plugin_parameter_validation(): MixedPrecision("16-mixed", "cpu") # should not raise exception MixedPrecision("bf16-mixed", "cpu") with pytest.raises( ValueError, match=re.escape("Passed `MixedPrecision(precision='16')`. Precision must be '16-mixed' or 'bf16-mixed'"), ): MixedPrecision("16", "cpu") with pytest.raises( ValueError, match=re.escape("Passed `MixedPrecision(precision=16)`. Precision must be '16-mixed' or 'bf16-mixed'"), ): MixedPrecision(16, "cpu") with pytest.raises( ValueError, match=re.escape("Passed `MixedPrecision(precision='bf16')`. Precision must be '16-mixed' or 'bf16-mixed'"), ): MixedPrecision("bf16", "cpu")
TestPrecisionModel
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_kw_only.py
{ "start": 143, "end": 261 }
class ____: """Simple dataclass with a kw_only parameter.""" a: int b: str @dataclass(kw_only=False)
FooBar
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/dagster_type.py
{ "start": 13955, "end": 14346 }
class ____(BuiltinScalarDagsterType): def __init__(self): super(_Float, self).__init__( name="Float", loader=BuiltinSchemas.FLOAT_INPUT, type_check_fn=self.type_check_fn, typing_type=float, ) def type_check_scalar_value(self, value: object) -> TypeCheck: return _fail_if_not_of_type(value, float, "float")
_Float
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/sensors/cloud_storage_transfer_service.py
{ "start": 1672, "end": 6623 }
class ____(BaseSensorOperator): """ Waits for at least one operation belonging to the job to have the expected status. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataTransferServiceJobStatusSensor` :param job_name: The name of the transfer job :param expected_statuses: The expected state of the operation. See: https://cloud.google.com/storage-transfer/docs/reference/rest/v1/transferOperations#Status :param project_id: (Optional) the ID of the project that owns the Transfer Job. If set to None or missing, the default project_id from the Google Cloud connection is used. :param gcp_conn_id: The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param deferrable: Run sensor in deferrable mode """ # [START gcp_transfer_job_sensor_template_fields] template_fields: Sequence[str] = ( "job_name", "impersonation_chain", ) # [END gcp_transfer_job_sensor_template_fields] operator_extra_links = (CloudStorageTransferJobLink(),) def __init__( self, *, job_name: str, expected_statuses: set[str] | str, project_id: str = PROVIDE_PROJECT_ID, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), **kwargs, ) -> None: super().__init__(**kwargs) self.job_name = job_name self.expected_statuses = ( {expected_statuses} if isinstance(expected_statuses, str) else expected_statuses ) self.project_id = project_id self.gcp_cloud_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.deferrable = deferrable def poke(self, context: Context) -> bool: ti = context["ti"] hook = CloudDataTransferServiceHook( gcp_conn_id=self.gcp_cloud_conn_id, impersonation_chain=self.impersonation_chain, ) operations = hook.list_transfer_operations( request_filter={"project_id": self.project_id or hook.project_id, "job_names": [self.job_name]} ) for operation in operations: self.log.info("Progress for operation %s: %s", operation[NAME], operation[METADATA][COUNTERS]) check = CloudDataTransferServiceHook.operations_contain_expected_statuses( operations=operations, expected_statuses=self.expected_statuses ) if check: ti.xcom_push(key="sensed_operations", value=operations) project_id = self.project_id or hook.project_id if project_id: CloudStorageTransferJobLink.persist( context=context, project_id=project_id, job_name=self.job_name, ) return check def execute(self, context: Context) -> None: """Run on the worker and defer using the triggers if deferrable is set to True.""" if not self.deferrable: super().execute(context) elif not self.poke(context=context): self.defer( timeout=self.execution_timeout, trigger=CloudStorageTransferServiceCheckJobStatusTrigger( job_name=self.job_name, expected_statuses=self.expected_statuses, project_id=self.project_id, poke_interval=self.poke_interval, gcp_conn_id=self.gcp_cloud_conn_id, impersonation_chain=self.impersonation_chain, ), method_name="execute_complete", ) def execute_complete(self, context: Context, event: dict[str, Any]) -> None: """ Act as a callback for when the trigger fires. This returns immediately. It relies on trigger to throw an exception, otherwise it assumes execution was successful. """ if event["status"] == "error": raise AirflowException(event["message"]) ti = context["ti"] ti.xcom_push(key="sensed_operations", value=event["operations"])
CloudDataTransferServiceJobStatusSensor
python
davidhalter__jedi
test/static_analysis/attribute_warnings.py
{ "start": 471, "end": 746 }
class ____(): def __init__(self, dct): # Jedi doesn't even try to understand such code for k, v in dct.items(): setattr(self, k, v) self.defined = 3 c = SetattrCls({'a': 'b'}) c.defined #! 2 warning attribute-error c.undefined
SetattrCls
python
huggingface__transformers
tests/quantization/gptq/test_gptq.py
{ "start": 1075, "end": 2485 }
class ____(unittest.TestCase): def test_bits(self): with self.assertRaises(ValueError): GPTQConfig(bits="") GPTQConfig(bits=1) GPTQConfig(bits=2) GPTQConfig(bits=4) def test_dataset(self): with self.assertRaises(ValueError): GPTQConfig(bits=2, dataset="auto_gpt") GPTQConfig(bits=2, dataset="c4") def test_damp_percent(self): with self.assertRaises(ValueError): GPTQConfig(bits=2, damp_percent=10) GPTQConfig(bits=2, damp_percent=-1) GPTQConfig(bits=2, damp_percent="0") GPTQConfig(bits=2, damp_percent=0.01) def test_to_dict(self): quantization_config = GPTQConfig(bits=2) quantization_config.to_dict() def test_from_dict(self): dict = {"bits": 2} quantization_config = GPTQConfig.from_dict(dict) self.assertEqual(dict["bits"], quantization_config.bits) @require_optimum def test_optimum_config(self): from optimum.gptq import GPTQQuantizer config = GPTQConfig(bits=2) optimum_config = GPTQQuantizer.from_dict(config.to_dict_optimum()) self.assertEqual(optimum_config.bits, config.bits) new_config = GPTQConfig.from_dict_optimum(optimum_config.to_dict()) self.assertEqual(optimum_config.bits, new_config.bits) @slow @require_optimum @require_gptq
GPTQConfigTest
python
scikit-learn__scikit-learn
sklearn/utils/_param_validation.py
{ "start": 21881, "end": 22963 }
class ____(_Constraint): """Constraint representing objects that expose specific methods. It is useful for parameters following a protocol and where we don't want to impose an affiliation to a specific module or class. Parameters ---------- methods : str or list of str The method(s) that the object is expected to expose. """ @validate_params( {"methods": [str, list]}, prefer_skip_nested_validation=True, ) def __init__(self, methods): super().__init__() if isinstance(methods, str): methods = [methods] self.methods = methods def is_satisfied_by(self, val): return all(callable(getattr(val, method, None)) for method in self.methods) def __str__(self): if len(self.methods) == 1: methods = f"{self.methods[0]!r}" else: methods = ( f"{', '.join([repr(m) for m in self.methods[:-1]])} and" f" {self.methods[-1]!r}" ) return f"an object implementing {methods}"
HasMethods
python
dagster-io__dagster
python_modules/dagster/dagster/_core/instance/types.py
{ "start": 5064, "end": 6342 }
class ____(DynamicPartitionsStore): """A batch loader that caches the partition keys for a given dynamic partitions definition, to avoid repeated calls to the database for the same partitions definition. """ def __init__(self, instance: "DagsterInstance"): self._instance = instance @cached_method def get_dynamic_partitions(self, partitions_def_name: str) -> Sequence[str]: return self._instance.get_dynamic_partitions(partitions_def_name) @cached_method def get_paginated_dynamic_partitions( self, partitions_def_name: str, limit: int, ascending: bool, cursor: Optional[str] = None ) -> PaginatedResults[str]: return self._instance.get_paginated_dynamic_partitions( partitions_def_name=partitions_def_name, limit=limit, ascending=ascending, cursor=cursor ) @cached_method def has_dynamic_partition(self, partitions_def_name: str, partition_key: str) -> bool: return self._instance.has_dynamic_partition(partitions_def_name, partition_key) @cached_method def get_dynamic_partitions_definition_id(self, partitions_def_name: str) -> str: return self._instance.get_dynamic_partitions_definition_id(partitions_def_name) @record
CachingDynamicPartitionsLoader
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/base.py
{ "start": 7157, "end": 15315 }
class ____(InspectionAttrExtensionType): NOT_EXTENSION = "not_extension" """Symbol indicating an :class:`InspectionAttr` that's not part of sqlalchemy.ext. Is assigned to the :attr:`.InspectionAttr.extension_type` attribute. """ _never_set = frozenset([NEVER_SET]) _none_set = frozenset([None, NEVER_SET, PASSIVE_NO_RESULT]) _none_only_set = frozenset([None]) _SET_DEFERRED_EXPIRED = util.symbol("SET_DEFERRED_EXPIRED") _DEFER_FOR_STATE = util.symbol("DEFER_FOR_STATE") _RAISE_FOR_STATE = util.symbol("RAISE_FOR_STATE") _F = TypeVar("_F", bound=Callable[..., Any]) _Self = TypeVar("_Self") def _assertions( *assertions: Any, ) -> Callable[[_F], _F]: @util.decorator def generate(fn: _F, self: _Self, *args: Any, **kw: Any) -> _Self: for assertion in assertions: assertion(self, fn.__name__) fn(self, *args, **kw) return self return generate if TYPE_CHECKING: def manager_of_class(cls: Type[_O]) -> ClassManager[_O]: ... @overload def opt_manager_of_class(cls: AliasedClass[Any]) -> None: ... @overload def opt_manager_of_class( cls: _ExternalEntityType[_O], ) -> Optional[ClassManager[_O]]: ... def opt_manager_of_class( cls: _ExternalEntityType[_O], ) -> Optional[ClassManager[_O]]: ... def instance_state(instance: _O) -> InstanceState[_O]: ... def instance_dict(instance: object) -> Dict[str, Any]: ... else: # these can be replaced by sqlalchemy.ext.instrumentation # if augmented class instrumentation is enabled. def manager_of_class(cls): try: return cls.__dict__[DEFAULT_MANAGER_ATTR] except KeyError as ke: raise exc.UnmappedClassError( cls, f"Can't locate an instrumentation manager for class {cls}" ) from ke def opt_manager_of_class(cls): return cls.__dict__.get(DEFAULT_MANAGER_ATTR) instance_state = operator.attrgetter(DEFAULT_STATE_ATTR) instance_dict = operator.attrgetter("__dict__") def instance_str(instance: object) -> str: """Return a string describing an instance.""" return state_str(instance_state(instance)) def state_str(state: InstanceState[Any]) -> str: """Return a string describing an instance via its InstanceState.""" if state is None: return "None" else: return "<%s at 0x%x>" % (state.class_.__name__, id(state.obj())) def state_class_str(state: InstanceState[Any]) -> str: """Return a string describing an instance's class via its InstanceState. """ if state is None: return "None" else: return "<%s>" % (state.class_.__name__,) def attribute_str(instance: object, attribute: str) -> str: return instance_str(instance) + "." + attribute def state_attribute_str(state: InstanceState[Any], attribute: str) -> str: return state_str(state) + "." + attribute def object_mapper(instance: _T) -> Mapper[_T]: """Given an object, return the primary Mapper associated with the object instance. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError` if no mapping is configured. This function is available via the inspection system as:: inspect(instance).mapper Using the inspection system will raise :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is not part of a mapping. """ return object_state(instance).mapper def object_state(instance: _T) -> InstanceState[_T]: """Given an object, return the :class:`.InstanceState` associated with the object. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError` if no mapping is configured. Equivalent functionality is available via the :func:`_sa.inspect` function as:: inspect(instance) Using the inspection system will raise :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is not part of a mapping. """ state = _inspect_mapped_object(instance) if state is None: raise exc.UnmappedInstanceError(instance) else: return state @inspection._inspects(object) def _inspect_mapped_object(instance: _T) -> Optional[InstanceState[_T]]: try: return instance_state(instance) except (exc.UnmappedClassError,) + exc.NO_STATE: return None def _class_to_mapper( class_or_mapper: Union[Mapper[_T], Type[_T]], ) -> Mapper[_T]: # can't get mypy to see an overload for this insp = inspection.inspect(class_or_mapper, False) if insp is not None: return insp.mapper # type: ignore else: assert isinstance(class_or_mapper, type) raise exc.UnmappedClassError(class_or_mapper) def _mapper_or_none( entity: Union[Type[_T], _InternalEntityType[_T]], ) -> Optional[Mapper[_T]]: """Return the :class:`_orm.Mapper` for the given class or None if the class is not mapped. """ # can't get mypy to see an overload for this insp = inspection.inspect(entity, False) if insp is not None: return insp.mapper # type: ignore else: return None def _is_mapped_class(entity: Any) -> bool: """Return True if the given object is a mapped class, :class:`_orm.Mapper`, or :class:`.AliasedClass`. """ insp = inspection.inspect(entity, False) return ( insp is not None and not insp.is_clause_element and (insp.is_mapper or insp.is_aliased_class) ) def _is_aliased_class(entity: Any) -> bool: insp = inspection.inspect(entity, False) return insp is not None and getattr(insp, "is_aliased_class", False) @no_type_check def _entity_descriptor(entity: _EntityType[Any], key: str) -> Any: """Return a class attribute given an entity and string name. May return :class:`.InstrumentedAttribute` or user-defined attribute. """ insp = inspection.inspect(entity) if insp.is_selectable: description = entity entity = insp.c elif insp.is_aliased_class: entity = insp.entity description = entity elif hasattr(insp, "mapper"): description = entity = insp.mapper.class_ else: description = entity try: return getattr(entity, key) except AttributeError as err: raise sa_exc.InvalidRequestError( "Entity '%s' has no property '%s'" % (description, key) ) from err if TYPE_CHECKING: def _state_mapper(state: InstanceState[_O]) -> Mapper[_O]: ... else: _state_mapper = util.dottedgetter("manager.mapper") def _inspect_mapped_class( class_: Type[_O], configure: bool = False ) -> Optional[Mapper[_O]]: try: class_manager = opt_manager_of_class(class_) if class_manager is None or not class_manager.is_mapped: return None mapper = class_manager.mapper except exc.NO_STATE: return None else: if configure: mapper._check_configure() return mapper def _parse_mapper_argument(arg: Union[Mapper[_O], Type[_O]]) -> Mapper[_O]: insp = inspection.inspect(arg, raiseerr=False) if insp_is_mapper(insp): return insp raise sa_exc.ArgumentError(f"Mapper or mapped class expected, got {arg!r}") def class_mapper(class_: Type[_O], configure: bool = True) -> Mapper[_O]: """Given a class, return the primary :class:`_orm.Mapper` associated with the key. Raises :exc:`.UnmappedClassError` if no mapping is configured on the given class, or :exc:`.ArgumentError` if a non-class object is passed. Equivalent functionality is available via the :func:`_sa.inspect` function as:: inspect(some_mapped_class) Using the inspection system will raise :class:`sqlalchemy.exc.NoInspectionAvailable` if the class is not mapped. """ mapper = _inspect_mapped_class(class_, configure=configure) if mapper is None: if not isinstance(class_, type): raise sa_exc.ArgumentError( "Class object expected, got '%r'." % (class_,) ) raise exc.UnmappedClassError(class_) else: return mapper
NotExtension
python
sympy__sympy
sympy/utilities/codegen.py
{ "start": 30739, "end": 31003 }
class ____(Exception): @property def missing_args(self): return self.args[1] header_comment = """Code generated with SymPy %(version)s See http://www.sympy.org/ for more information. This file is part of '%(project)s' """
CodeGenArgumentListError
python
viewflow__viewflow
viewflow/workflow/status.py
{ "start": 82, "end": 281 }
class ____(models.TextChoices): CANCELED = "CANCELED", pgettext_lazy("STATUS", "Canceled") DONE = "DONE", pgettext_lazy("STATUS", "Done") NEW = "NEW", pgettext_lazy("STATUS", "New")
PROCESS
python
walkccc__LeetCode
solutions/2972. Count the Number of Incremovable Subarrays II/2972-2.py
{ "start": 0, "end": 1217 }
class ____: # Same as 2970. Count the Number of Incremovable Subarrays I def incremovableSubarrayCount(self, nums: list[int]) -> int: n = len(nums) startIndex = self._getStartIndexOfSuffix(nums) # If the complete array is strictly increasing, the total number of ways we # can remove elements equals the total number of possible subarrays. if startIndex == 0: return n * (n + 1) // 2 # The valid removals starting from nums[0] include nums[0..startIndex - 1], # nums[0..startIndex], ..., nums[0..n). ans = n - startIndex + 1 # Enumerate each prefix subarray that is strictly increasing. j = startIndex for i in range(startIndex): if i > 0 and nums[i] <= nums[i - 1]: break # Since nums[0..i] is strictly increasing, move j to the place such that # nums[j] > nums[i]. The valid removals will then be nums[i + 1..j - 1], # nums[i + 1..j], ..., nums[i + 1..n). while j < n and nums[i] >= nums[j]: j += 1 ans += n - j + 1 return ans def _getStartIndexOfSuffix(self, nums: list[int]) -> int: for i in range(len(nums) - 2, -1, -1): if nums[i] >= nums[i + 1]: return i + 1 return 0
Solution
python
xlwings__xlwings
xlwings/constants.py
{ "start": 57690, "end": 57883 }
class ____: xlNoRestrictions = 0 # from enum XlEnableSelection xlNoSelection = -4142 # from enum XlEnableSelection xlUnlockedCells = 1 # from enum XlEnableSelection
EnableSelection
python
huggingface__transformers
tests/models/mistral3/test_processing_mistral3.py
{ "start": 931, "end": 16806 }
class ____(ProcessorTesterMixin, unittest.TestCase): """This tests Pixtral processor with the new `spatial_merge_size` argument in Mistral3.""" processor_class = PixtralProcessor model_id = "hf-internal-testing/Mistral-Small-3.1-24B-Instruct-2503-only-processor" @classmethod def _setup_test_attributes(cls, processor): cls.url_0 = url_to_local_path( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" ) cls.image_0 = np.random.randint(255, size=(3, 876, 1300), dtype=np.uint8) cls.url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg" cls.image_1 = np.random.randint(255, size=(3, 480, 640), dtype=np.uint8) cls.image_2 = np.random.randint(255, size=(3, 1024, 1024), dtype=np.uint8) cls.image_token = processor.image_token @staticmethod def prepare_processor_dict(): return { "chat_template": "{%- set today = strftime_now(\"%Y-%m-%d\") %}\n{%- set default_system_message = \"You are Mistral Small 3, a Large Language Model (LLM) created by Mistral AI, a French startup headquartered in Paris.\\nYour knowledge base was last updated on 2023-10-01. The current date is \" + today + \".\\n\\nWhen you're not sure about some information, you say that you don't have the information and don't make up anything.\\nIf the user's question is not clear, ambiguous, or does not provide enough context for you to accurately answer the question, you do not try to answer it right away and you rather ask the user to clarify their request (e.g. \\\"What are some good restaurants around me?\\\" => \\\"Where are you?\\\" or \\\"When is the next flight to Tokyo\\\" => \\\"Where do you travel from?\\\")\" %}\n\n{{- bos_token }}\n\n{%- if messages[0]['role'] == 'system' %}\n {%- if messages[0] is string %}\n {%- set system_message = messages[0]['content'] %}\n {%- set loop_messages = messages[1:] %}\n {%- else %} \n {%- set system_message = messages[0]['content'][0]['text'] %}\n {%- set loop_messages = messages[1:] %}\n {%- endif %}\n{%- else %}\n {%- set system_message = default_system_message %}\n {%- set loop_messages = messages %}\n{%- endif %}\n{{- '[SYSTEM_PROMPT]' + system_message + '[/SYSTEM_PROMPT]' }}\n\n{%- for message in loop_messages %}\n {%- if message['role'] == 'user' %}\n {%- if message['content'] is string %}\n {{- '[INST]' + message['content'] + '[/INST]' }}\n {%- else %}\n {{- '[INST]' }}\n {%- for block in message['content'] %}\n {%- if block['type'] == 'text' %}\n {{- block['text'] }}\n {%- elif block['type'] == 'image' or block['type'] == 'image_url' %}\n {{- '[IMG]' }}\n {%- else %}\n {{- raise_exception('Only text and image blocks are supported in message content!') }}\n {%- endif %}\n {%- endfor %}\n {{- '[/INST]' }}\n {%- endif %}\n {%- elif message['role'] == 'system' %}\n {{- '[SYSTEM_PROMPT]' + message['content'] + '[/SYSTEM_PROMPT]' }}\n {%- elif message['role'] == 'assistant' %}\n {%- if message['content'] is string %}\n {{- message['content'] + eos_token }}\n {%- else %}\n {{- message['content'][0]['text'] + eos_token }}\n {%- endif %}\n {%- else %}\n {{- raise_exception('Only user, system and assistant roles are supported!') }}\n {%- endif %}\n{%- endfor %}", "spatial_merge_size":2, "patch_size": 128, } # fmt: skip def test_image_token_filling(self): processor = self.processor_class.from_pretrained(self.tmpdirname) # Important to check with non square image image = torch.randint(0, 2, (3, 500, 316)) expected_image_tokens = 4 image_token_index = 10 messages = [ { "role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}], }, { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "What is shown in this image?"}, ], }, ] inputs = processor( text=[processor.apply_chat_template(messages)], images=[image], return_tensors="pt", ) image_tokens = (inputs["input_ids"] == image_token_index).sum().item() self.assertEqual(expected_image_tokens, image_tokens) def test_processor_with_single_image(self): processor = self.processor_class.from_pretrained(self.tmpdirname) prompt_string = "USER: [IMG]\nWhat's the content of the image? ASSISTANT:" # Make small for checking image token expansion processor.image_processor.size = {"longest_edge": 30} processor.patch_size = 6 # Test passing in an image inputs_image = processor(text=prompt_string, images=self.image_0, return_tensors="pt") self.assertIn("input_ids", inputs_image) self.assertTrue(len(inputs_image["input_ids"]) == 1) self.assertIsInstance(inputs_image["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([1, 3, 24, 36])) # fmt: off input_ids = inputs_image["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to "USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the content of the image? ASSISTANT:" [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing in a url inputs_url = processor(text=prompt_string, images=self.url_0, return_tensors="pt") self.assertIn("input_ids", inputs_url) self.assertTrue(len(inputs_url["input_ids"]) == 1) self.assertIsInstance(inputs_url["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([1, 3, 24, 36])) # fmt: off input_ids = inputs_url["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to "USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the content of the image? ASSISTANT:" [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing inputs as a single list inputs_image = processor(text=prompt_string, images=[self.image_0], return_tensors="pt") self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([1, 3, 24, 36])) # fmt: off self.assertEqual( inputs_image["input_ids"][0].tolist(), [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test as nested single list inputs_image = processor(text=prompt_string, images=[[self.image_0]], return_tensors="pt") self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([1, 3, 24, 36])) # fmt: off self.assertEqual( inputs_image["input_ids"][0].tolist(), [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on def test_processor_with_multiple_images_single_list(self): processor = self.processor_class.from_pretrained(self.tmpdirname) prompt_string = "USER: [IMG][IMG]\nWhat's the difference between these two images? ASSISTANT:" # Make small for checking image token expansion processor.image_processor.size = {"longest_edge": 30} processor.patch_size = 6 # Test passing in an image inputs_image = processor(text=prompt_string, images=[self.image_0, self.image_1], return_tensors="pt") self.assertIn("input_ids", inputs_image) self.assertTrue(len(inputs_image["input_ids"]) == 1) self.assertIsInstance(inputs_image["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([2, 3, 24, 36])) # fmt: off input_ids = inputs_image["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"] [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing in a url inputs_url = processor(text=prompt_string, images=[self.url_0, self.url_1], return_tensors="pt") self.assertIn("input_ids", inputs_url) self.assertTrue(len(inputs_url["input_ids"]) == 1) self.assertIsInstance(inputs_url["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([2, 3, 24, 36])) # fmt: off input_ids = inputs_url["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"] [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing in as a nested list inputs_url = processor(text=prompt_string, images=[[self.image_0, self.image_1]], return_tensors="pt") self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([2, 3, 24, 36])) # fmt: off self.assertEqual( inputs_url["input_ids"][0].tolist(), [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on def test_processor_with_multiple_images_multiple_lists(self): processor = self.processor_class.from_pretrained(self.tmpdirname) prompt_string = [ "USER: [IMG][IMG]\nWhat's the difference between these two images? ASSISTANT:", "USER: [IMG]\nWhat's the content of the image? ASSISTANT:", ] processor.tokenizer.pad_token = "</s>" image_inputs = [[self.image_0, self.image_1], [self.image_2]] # Make small for checking image token expansion processor.image_processor.size = {"longest_edge": 30} processor.patch_size = 6 # Test passing in an image inputs_image = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True) self.assertIn("input_ids", inputs_image) self.assertTrue(len(inputs_image["input_ids"]) == 2) self.assertIsInstance(inputs_image["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([3, 3, 36, 36])) # fmt: off input_ids = inputs_image["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"] [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing in a url inputs_url = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True) self.assertIn("input_ids", inputs_url) self.assertTrue(len(inputs_url["input_ids"]) == 2) self.assertIsInstance(inputs_url["input_ids"], torch.Tensor) self.assertIsInstance(inputs_image["pixel_values"], torch.Tensor) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([3, 3, 36, 36])) # fmt: off input_ids = inputs_url["input_ids"] self.assertEqual( input_ids[0].tolist(), # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"] [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on # Test passing as a single flat list inputs_image = processor( text=prompt_string, images=[self.image_0, self.image_1, self.image_2], return_tensors="pt", padding=True ) self.assertTrue(inputs_image["pixel_values"].shape == torch.Size([3, 3, 36, 36])) # fmt: off self.assertEqual( inputs_image["input_ids"][0].tolist(), [1, 21510, 1058, 1032, 10, 10, 10, 12, 10, 10, 10, 13, 10, 10, 10, 12, 10, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058] ) # fmt: on def test_processor_returns_full_length_batches(self): # to avoid https://github.com/huggingface/transformers/issues/34204 processor = self.processor_class.from_pretrained(self.tmpdirname) prompt_string = [ "USER: [IMG]\nWhat's the content of the image? ASSISTANT:", ] * 5 processor.tokenizer.pad_token = "</s>" image_inputs = [[self.image_0]] * 5 # Make small for checking image token expansion processor.image_processor.size = {"longest_edge": 30} processor.patch_size = 6 # Test passing in an image inputs_image = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True) self.assertIn("input_ids", inputs_image) self.assertTrue(len(inputs_image["input_ids"]) == 5) def test_special_mm_token_truncation(self): """Tests that special vision tokens do not get truncated when `truncation=True` is set.""" processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") image_input = self.prepare_image_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=None, padding=True, ) with self.assertRaises(ValueError): _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=True, padding=True, max_length=3, )
Mistral3ProcessorTest
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 118689, "end": 119535 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, api_token: str, start_date: str, batch_size: Optional[int] = None ): """Airbyte Source for Dixa. Documentation can be found at https://docs.airbyte.com/integrations/sources/dixa Args: name (str): The name of the destination. api_token (str): Dixa API token start_date (str): The connector pulls records updated from this date onwards. batch_size (Optional[int]): Number of days to batch into one request. Max 31. """ self.api_token = check.str_param(api_token, "api_token") self.start_date = check.str_param(start_date, "start_date") self.batch_size = check.opt_int_param(batch_size, "batch_size") super().__init__("Dixa", name)
DixaSource
python
redis__redis-py
redis/backoff.py
{ "start": 3464, "end": 4461 }
class ____(AbstractBackoff): """Decorrelated jitter backoff upon failure""" def __init__(self, cap: float = DEFAULT_CAP, base: float = DEFAULT_BASE) -> None: """ `cap`: maximum backoff time in seconds `base`: base backoff time in seconds """ self._cap = cap self._base = base self._previous_backoff = 0 def __hash__(self) -> int: return hash((self._base, self._cap)) def __eq__(self, other) -> bool: if not isinstance(other, DecorrelatedJitterBackoff): return NotImplemented return self._base == other._base and self._cap == other._cap def reset(self) -> None: self._previous_backoff = 0 def compute(self, failures: int) -> float: max_backoff = max(self._base, self._previous_backoff * 3) temp = random.uniform(self._base, max_backoff) self._previous_backoff = min(self._cap, temp) return self._previous_backoff
DecorrelatedJitterBackoff
python
astropy__astropy
astropy/units/tests/test_quantity_non_ufuncs.py
{ "start": 34410, "end": 38362 }
class ____(InvariantUnitTestSetup): def test_average(self): q1 = np.arange(9.0).reshape(3, 3) * u.m q2 = np.eye(3) / u.s o = np.average(q1, weights=q2) expected = np.average(q1.value, weights=q2.value) * u.m assert np.all(o == expected) def test_mean(self): self.check(np.mean) def test_std(self): self.check(np.std) def test_var(self): o = np.var(self.q) expected = np.var(self.q.value) * self.q.unit**2 assert np.all(o == expected) def test_median(self): self.check(np.median) def test_median_nan_scalar(self): # See gh-12165; this dropped the unit in numpy < 1.22 data = [1.0, 2, np.nan, 3, 4] << u.km result = np.median(data) assert_array_equal(result, np.nan * u.km) def test_quantile(self): self.check(np.quantile, 0.5) o = np.quantile(self.q, 50 * u.percent) expected = np.quantile(self.q.value, 0.5) * u.m assert np.all(o == expected) # For ndarray input, we return a Quantity. o2 = np.quantile(self.q.value, 50 * u.percent) assert o2.unit == u.dimensionless_unscaled assert np.all(o2 == expected.value) o3 = 0 * o2 result = np.quantile(self.q, 50 * u.percent, out=o3) assert result is o3 assert np.all(o3 == expected) o4 = 0 * o2 result = np.quantile(self.q, 50 * u.percent, None, o4) assert result is o4 assert np.all(o4 == expected) def test_percentile(self): self.check(np.percentile, 0.5) o = np.percentile(self.q, 0.5 * u.one) expected = np.percentile(self.q.value, 50) * u.m assert np.all(o == expected) def test_trace(self): self.check(np.trace) def test_count_nonzero(self): q1 = np.arange(9.0).reshape(3, 3) * u.m o = np.count_nonzero(q1) assert type(o) is not u.Quantity assert o == 8 o = np.count_nonzero(q1, axis=1) # Returns integer Quantity with units of m assert type(o) is np.ndarray assert np.all(o == np.array([2, 3, 3])) def test_allclose(self): q1 = np.arange(3.0) * u.m q2 = np.array([0.0, 101.0, 199.0]) * u.cm atol = 2 * u.cm rtol = 1.0 * u.percent assert np.allclose(q1, q2, atol=atol) assert np.allclose(q1, q2, atol=0.0, rtol=rtol) def test_allclose_atol_default_unit(self): q1 = np.arange(3.0) * u.m q2 = np.array([0.0, 101.0, 199.0]) * u.cm assert np.allclose(q1, q2, atol=0.011, rtol=0) assert not np.allclose(q2, q1, atol=0.011, rtol=0) def test_allclose_failures(self): q1 = np.arange(3.0) * u.m q2 = np.array([0.0, 101.0, 199.0]) * u.cm with pytest.raises(u.UnitsError): np.allclose(q1, q2, atol=2 * u.s, rtol=0) with pytest.raises(u.UnitsError): np.allclose(q1, q2, atol=0, rtol=1.0 * u.s) def test_array_equal(self): q1 = np.arange(3.0) * u.m q2 = q1.to(u.cm) assert np.array_equal(q1, q2) q3 = q1.value * u.cm assert not np.array_equal(q1, q3) @pytest.mark.parametrize("equal_nan", [False, True]) def test_array_equal_nan(self, equal_nan): q1 = np.linspace(0, 1, num=11) * u.m q1[0] = np.nan q2 = q1.to(u.cm) result = np.array_equal(q1, q2, equal_nan=equal_nan) assert result == equal_nan def test_array_equal_incompatible_units(self): assert not np.array_equal([1, 2] * u.m, [1, 2] * u.s) def test_array_equiv(self): q1 = np.array([[0.0, 1.0, 2.0]] * 3) * u.m q2 = q1[0].to(u.cm) assert np.array_equiv(q1, q2) q3 = q1[0].value * u.cm assert not np.array_equiv(q1, q3) def test_array_equiv_incompatible_units(self): assert not np.array_equiv([1, 1] * u.m, [1] * u.s)
TestReductionLikeFunctions
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vision.py
{ "start": 14112, "end": 17594 }
class ____(GoogleCloudBaseOperator): """ Permanently deletes a ``ProductSet``. ``Products`` and ``ReferenceImages`` in the ``ProductSet`` are not deleted. The actual image files are not deleted from Google Cloud Storage. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudVisionDeleteProductSetOperator` :param location: (Required) The region where the ProductSet is located. Valid regions (as of 2019-02-05) are: us-east1, us-west1, europe-west1, asia-east1 :param product_set_id: (Required) The resource id of this ProductSet. :param project_id: (Optional) The project in which the ProductSet should be created. If set to None or missing, the default project_id from the Google Cloud connection is used. :param retry: (Optional) A retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: (Optional) The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: (Optional) Additional metadata that is provided to the method. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ # [START vision_productset_delete_template_fields] template_fields: Sequence[str] = ( "location", "project_id", "product_set_id", "gcp_conn_id", "impersonation_chain", ) # [END vision_productset_delete_template_fields] def __init__( self, *, location: str, product_set_id: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: MetaData = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.location = location self.project_id = project_id self.product_set_id = product_set_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = CloudVisionHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) hook.delete_product_set( location=self.location, product_set_id=self.product_set_id, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, )
CloudVisionDeleteProductSetOperator
python
PyCQA__pylint
pylint/extensions/_check_docs_utils.py
{ "start": 10496, "end": 15376 }
class ____(Docstring): re_type = r""" [~!.]? # Optional link style prefix \w(?:\w|\.[^\.])* # Valid python name """ re_simple_container_type = rf""" {re_type} # a container type [\(\[] [^\n\s]+ [\)\]] # with the contents of the container """ re_multiple_simple_type = rf""" (?:{re_simple_container_type}|{re_type}) (?:(?:\s+(?:of|or)\s+|\s*,\s*|\s+\|\s+)(?:{re_simple_container_type}|{re_type}))* """ re_xref = rf""" (?::\w+:)? # optional tag `{re_type}` # what to reference """ re_param_raw = rf""" : # initial colon (?: # Sphinx keywords param|parameter| arg|argument| key|keyword ) \s+ # whitespace (?: # optional type declaration ({re_type}|{re_simple_container_type}) \s+ )? ((\\\*{{0,2}}\w+)|(\w+)) # Parameter name with potential asterisks \s* # whitespace : # final colon """ re_param_in_docstring = re.compile(re_param_raw, re.X | re.S) re_type_raw = rf""" :type # Sphinx keyword \s+ # whitespace ({re_multiple_simple_type}) # Parameter name \s* # whitespace : # final colon """ re_type_in_docstring = re.compile(re_type_raw, re.X | re.S) re_property_type_raw = rf""" :type: # Sphinx keyword \s+ # whitespace {re_multiple_simple_type} # type declaration """ re_property_type_in_docstring = re.compile(re_property_type_raw, re.X | re.S) re_raise_raw = rf""" : # initial colon (?: # Sphinx keyword raises?| except|exception ) \s+ # whitespace ({re_multiple_simple_type}) # exception type \s* # whitespace : # final colon """ re_raise_in_docstring = re.compile(re_raise_raw, re.X | re.S) re_rtype_in_docstring = re.compile(r":rtype:") re_returns_in_docstring = re.compile(r":returns?:") supports_yields = False def matching_sections(self) -> int: """Returns the number of matching docstring sections.""" return sum( bool(i) for i in ( self.re_param_in_docstring.search(self.doc), self.re_raise_in_docstring.search(self.doc), self.re_rtype_in_docstring.search(self.doc), self.re_returns_in_docstring.search(self.doc), self.re_property_type_in_docstring.search(self.doc), ) ) def exceptions(self) -> set[str]: types: set[str] = set() for match in re.finditer(self.re_raise_in_docstring, self.doc): raise_type = match.group(1) types.update(_split_multiple_exc_types(raise_type)) return types def has_params(self) -> bool: if not self.doc: return False return self.re_param_in_docstring.search(self.doc) is not None def has_returns(self) -> bool: if not self.doc: return False return bool(self.re_returns_in_docstring.search(self.doc)) def has_rtype(self) -> bool: if not self.doc: return False return bool(self.re_rtype_in_docstring.search(self.doc)) def has_property_returns(self) -> bool: if not self.doc: return False # The summary line is the return doc, # so the first line must not be a known directive. return not self.doc.lstrip().startswith(":") def has_property_type(self) -> bool: if not self.doc: return False return bool(self.re_property_type_in_docstring.search(self.doc)) def match_param_docs(self) -> tuple[set[str], set[str]]: params_with_doc = set() params_with_type = set() for match in re.finditer(self.re_param_in_docstring, self.doc): name = match.group(2) # Remove escape characters necessary for asterisks name = name.replace("\\", "") params_with_doc.add(name) param_type = match.group(1) if param_type is not None: params_with_type.add(name) params_with_type.update(re.findall(self.re_type_in_docstring, self.doc)) return params_with_doc, params_with_type
SphinxDocstring
python
airbytehq__airbyte
airbyte-integrations/connectors/source-fauna/unit_tests/test_util.py
{ "start": 1139, "end": 1354 }
class ____: """ A limited version of FullConfig, storing only the values needed for discover() """ def __init__(self, collection: CollectionConfig): self.collection = collection
DiscoverConfig
python
tiangolo__fastapi
docs_src/sql_databases/tutorial002_py39.py
{ "start": 493, "end": 2642 }
class ____(HeroBase): name: Union[str, None] = None age: Union[int, None] = None secret_name: Union[str, None] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: Session = Depends(get_session)): db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=list[HeroPublic]) def read_heroes( session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, le=100), ): heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() return heroes @app.get("/heroes/{hero_id}", response_model=HeroPublic) def read_hero(hero_id: int, session: Session = Depends(get_session)): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero @app.patch("/heroes/{hero_id}", response_model=HeroPublic) def update_hero( hero_id: int, hero: HeroUpdate, session: Session = Depends(get_session) ): hero_db = session.get(Hero, hero_id) if not hero_db: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.model_dump(exclude_unset=True) hero_db.sqlmodel_update(hero_data) session.add(hero_db) session.commit() session.refresh(hero_db) return hero_db @app.delete("/heroes/{hero_id}") def delete_hero(hero_id: int, session: Session = Depends(get_session)): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") session.delete(hero) session.commit() return {"ok": True}
HeroUpdate
python
getsentry__sentry
src/sentry/apidocs/parameters.py
{ "start": 32158, "end": 36187 }
class ____: OWNER = OpenApiParameter( name="owner", location="path", required=True, type=str, description="The owner of the repository.", ) REPOSITORY = OpenApiParameter( name="repository", location="path", required=True, type=str, description="The name of the repository.", ) INTERVAL = OpenApiParameter( name="interval", location="query", required=False, type=str, description="""The time interval to search for results by. Available fields are: - `INTERVAL_30_DAY` - `INTERVAL_7_DAY` - `INTERVAL_1_DAY` """, ) BRANCH = OpenApiParameter( name="branch", location="query", required=False, type=str, description="""The branch to search for results by. If not specified, the default is all branches. """, ) TEST_RESULTS_FILTER_BY = OpenApiParameter( name="filterBy", location="query", required=False, type=str, description="""An optional field to filter by, which will constrain the results to only include tests that match the filter. Available fields are: - `FLAKY_TESTS` - `FAILED_TESTS` - `SLOWEST_TESTS` - `SKIPPED_TESTS` """, ) TEST_RESULTS_SORT_BY = OpenApiParameter( name="sortBy", location="query", required=False, type=str, description="""The property to sort results by. If not specified, the default is `TOTAL_FAIL_COUNT` in descending order. Use `-` for descending order. Available fields are: - `AVG_DURATION` - `FLAKE_RATE` - `FAILURE_RATE` - `TOTAL_FAIL_COUNT` - `UPDATED_AT` """, ) LIMIT = OpenApiParameter( name="limit", location="query", required=False, type=int, description="""The number of results to return. If not specified, defaults to 20.""", ) FIRST = OpenApiParameter( name="first", location="query", required=False, type=int, default=20, description="""The number of results to return from the start of the list.""", ) LAST = OpenApiParameter( name="last", location="query", required=False, type=int, description="""The number of results to return from the end of the list.""", ) CURSOR = OpenApiParameter( name="cursor", location="query", required=False, type=str, description="""The cursor pointing to a specific position in the result set to start the query from. Results after the cursor will be returned if used with `next` or before the cursor if used with `prev` for `navigation`.""", ) TERM = OpenApiParameter( name="term", location="query", required=False, type=str, description="""The term substring to filter name strings by using the `contains` operator.""", ) NAVIGATION = OpenApiParameter( name="navigation", location="query", required=False, type=str, description="""Whether to get the previous or next page from paginated results. Use `next` for forward pagination after the cursor or `prev` for backward pagination before the cursor. If not specified, defaults to `next`. If no cursor is provided, the cursor is the beginning of the result set.""", ) TEST_SUITES = OpenApiParameter( name="testSuites", location="query", required=False, type=str, many=True, description="""A list of test suites belonging to a repository's test results.""", ) TOKENS_SORT_BY = OpenApiParameter( name="sortBy", location="query", required=False, type=str, description="""The property to sort results by. If not specified, the default is `COMMIT_DATE` in descending order. Use `-` for descending order. Available fields are: - `NAME` - `COMMIT_DATE` """, )
PreventParams
python
huggingface__transformers
src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
{ "start": 24743, "end": 30083 }
class ____(XLMRobertaXLPreTrainedModel): _no_split_modules = ["XLMRobertaXLEmbeddings", "XLMRobertaXLLayer"] def __init__(self, config, add_pooling_layer=True): r""" add_pooling_layer (bool, *optional*, defaults to `True`): Whether to add a pooling layer """ super().__init__(config) self.config = config self.gradient_checkpointing = False self.embeddings = XLMRobertaXLEmbeddings(config) self.encoder = XLMRobertaXLEncoder(config) self.pooler = XLMRobertaXLPooler(config) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @check_model_inputs() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: if self.config.is_decoder: use_cache = use_cache if use_cache is not None else self.config.use_cache else: use_cache = False if use_cache and past_key_values is None: past_key_values = ( EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config)) if encoder_hidden_states is not None or self.config.is_encoder_decoder else DynamicCache(config=self.config) ) if (input_ids is None) ^ (inputs_embeds is not None): raise ValueError("You must specify exactly one of input_ids or inputs_embeds") if input_ids is not None: device = input_ids.device seq_length = input_ids.shape[1] else: device = inputs_embeds.device seq_length = inputs_embeds.shape[1] past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0 if cache_position is None: cache_position = torch.arange(past_key_values_length, past_key_values_length + seq_length, device=device) embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds, past_key_values_length=past_key_values_length, ) attention_mask, encoder_attention_mask = self._create_attention_masks( attention_mask=attention_mask, encoder_attention_mask=encoder_attention_mask, embedding_output=embedding_output, encoder_hidden_states=encoder_hidden_states, cache_position=cache_position, past_key_values=past_key_values, ) encoder_outputs = self.encoder( embedding_output, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, use_cache=use_cache, cache_position=cache_position, position_ids=position_ids, **kwargs, ) sequence_output = encoder_outputs.last_hidden_state pooled_output = self.pooler(sequence_output) if self.pooler is not None else None return BaseModelOutputWithPoolingAndCrossAttentions( last_hidden_state=sequence_output, pooler_output=pooled_output, past_key_values=encoder_outputs.past_key_values, ) def _create_attention_masks( self, attention_mask, encoder_attention_mask, embedding_output, encoder_hidden_states, cache_position, past_key_values, ): if self.config.is_decoder: attention_mask = create_causal_mask( config=self.config, input_embeds=embedding_output, attention_mask=attention_mask, cache_position=cache_position, past_key_values=past_key_values, ) else: attention_mask = create_bidirectional_mask( config=self.config, input_embeds=embedding_output, attention_mask=attention_mask, ) if encoder_attention_mask is not None: encoder_attention_mask = create_bidirectional_mask( config=self.config, input_embeds=embedding_output, attention_mask=encoder_attention_mask, encoder_hidden_states=encoder_hidden_states, ) return attention_mask, encoder_attention_mask
XLMRobertaXLModel
python
mwaskom__seaborn
tests/_stats/test_aggregation.py
{ "start": 1924, "end": 3914 }
class ____(AggregationFixtures): # Note: Most of the underlying code is exercised in tests/test_statistics @pytest.mark.parametrize("func", [np.mean, "mean"]) def test_mean_sd(self, df, func): ori = "x" df = df[["x", "y"]] gb = self.get_groupby(df, ori) res = Est(func, "sd")(df, gb, ori, {}) grouped = df.groupby("x", as_index=False)["y"] est = grouped.mean() err = grouped.std().fillna(0) # fillna needed only on pinned tests expected = est.assign(ymin=est["y"] - err["y"], ymax=est["y"] + err["y"]) assert_frame_equal(res, expected) def test_sd_single_obs(self): y = 1.5 ori = "x" df = pd.DataFrame([{"x": "a", "y": y}]) gb = self.get_groupby(df, ori) res = Est("mean", "sd")(df, gb, ori, {}) expected = df.assign(ymin=y, ymax=y) assert_frame_equal(res, expected) def test_median_pi(self, df): ori = "x" df = df[["x", "y"]] gb = self.get_groupby(df, ori) res = Est("median", ("pi", 100))(df, gb, ori, {}) grouped = df.groupby("x", as_index=False)["y"] est = grouped.median() expected = est.assign(ymin=grouped.min()["y"], ymax=grouped.max()["y"]) assert_frame_equal(res, expected) def test_weighted_mean(self, df, rng): weights = rng.uniform(0, 5, len(df)) gb = self.get_groupby(df[["x", "y"]], "x") df = df.assign(weight=weights) res = Est("mean")(df, gb, "x", {}) for _, res_row in res.iterrows(): rows = df[df["x"] == res_row["x"]] expected = np.average(rows["y"], weights=rows["weight"]) assert res_row["y"] == expected def test_seed(self, df): ori = "x" gb = self.get_groupby(df, ori) args = df, gb, ori, {} res1 = Est("mean", "ci", seed=99)(*args) res2 = Est("mean", "ci", seed=99)(*args) assert_frame_equal(res1, res2)
TestEst
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI032.py
{ "start": 283, "end": 437 }
class ____: def __eq__(self, other: Any, strange_extra_arg: list[str]) -> Any: ... def __ne__(self, *, kw_only_other: Any) -> bool: ...
WeirdButFine
python
walkccc__LeetCode
solutions/694. Number of Distinct Islands/694.py
{ "start": 0, "end": 702 }
class ____: def numDistinctIslands(self, grid: list[list[int]]) -> int: seen = set() def dfs(i: int, j: int, i0: int, j0: int): if i < 0 or i == len(grid) or j < 0 or j == len(grid[0]): return if grid[i][j] == 0 or (i, j) in seen: return seen.add((i, j)) island.append((i - i0, j - j0)) dfs(i + 1, j, i0, j0) dfs(i - 1, j, i0, j0) dfs(i, j + 1, i0, j0) dfs(i, j - 1, i0, j0) islands = set() # all the different islands for i in range(len(grid)): for j in range(len(grid[0])): island = [] dfs(i, j, i, j) if island: islands.add(frozenset(island)) return len(islands)
Solution
python
ethereum__web3.py
web3/eth/async_eth.py
{ "start": 2095, "end": 24236 }
class ____(BaseEth): # mypy types w3: "AsyncWeb3[Any]" is_async = True _default_contract_factory: type[AsyncContract | AsyncContractCaller] = AsyncContract # eth_accounts _accounts: Method[Callable[[], Awaitable[tuple[ChecksumAddress]]]] = Method( RPC.eth_accounts, is_property=True, ) @property async def accounts(self) -> tuple[ChecksumAddress]: return await self._accounts() # eth_blobBaseFee _eth_blobBaseFee: Method[Callable[[], Awaitable[Wei]]] = Method( RPC.eth_blobBaseFee, is_property=True, ) @property async def blob_base_fee(self) -> Wei: return await self._eth_blobBaseFee() # eth_blockNumber get_block_number: Method[Callable[[], Awaitable[BlockNumber]]] = Method( RPC.eth_blockNumber, is_property=True, ) @property async def block_number(self) -> BlockNumber: return await self.get_block_number() # eth_chainId _chain_id: Method[Callable[[], Awaitable[int]]] = Method( RPC.eth_chainId, is_property=True, ) @property async def chain_id(self) -> int: return await self._chain_id() # eth_gasPrice _gas_price: Method[Callable[[], Awaitable[Wei]]] = Method( RPC.eth_gasPrice, is_property=True, ) @property async def gas_price(self) -> Wei: return await self._gas_price() # eth_maxPriorityFeePerGas _max_priority_fee: Method[Callable[[], Awaitable[Wei]]] = Method( RPC.eth_maxPriorityFeePerGas, is_property=True, ) @property async def max_priority_fee(self) -> Wei: """ Try to use eth_maxPriorityFeePerGas but, since this is not part of the spec and is only supported by some clients, fall back to an eth_feeHistory calculation with min and max caps. """ try: return await self._max_priority_fee() except Web3RPCError: warnings.warn( "There was an issue with the method eth_maxPriorityFeePerGas. " "Calculating using eth_feeHistory.", stacklevel=2, ) return await async_fee_history_priority_fee(self) # eth_syncing _syncing: Method[Callable[[], Awaitable[SyncStatus | bool]]] = Method( RPC.eth_syncing, is_property=True, ) @property async def syncing(self) -> SyncStatus | bool: return await self._syncing() # eth_feeHistory _fee_history: Method[ Callable[ [int, BlockParams | BlockNumber, list[float] | None], Awaitable[FeeHistory], ] ] = Method(RPC.eth_feeHistory, mungers=[default_root_munger]) async def fee_history( self, block_count: int, newest_block: BlockParams | BlockNumber, reward_percentiles: list[float] | None = None, ) -> FeeHistory: reward_percentiles = reward_percentiles or [] return await self._fee_history(block_count, newest_block, reward_percentiles) # eth_call _call: Method[ Callable[ [ TxParams, BlockIdentifier | None, StateOverride | None, ], Awaitable[HexBytes], ] ] = Method(RPC.eth_call, mungers=[BaseEth.call_munger]) async def call( self, transaction: TxParams, block_identifier: BlockIdentifier | None = None, state_override: StateOverride | None = None, ccip_read_enabled: bool | None = None, ) -> HexBytes: ccip_read_enabled_on_provider = self.w3.provider.global_ccip_read_enabled if ( # default conditions: ccip_read_enabled_on_provider and ccip_read_enabled is not False # explicit call flag overrides provider flag, # enabling ccip read for specific calls: or not ccip_read_enabled_on_provider and ccip_read_enabled is True ): return await self._durin_call(transaction, block_identifier, state_override) return await self._call(transaction, block_identifier, state_override) async def _durin_call( self, transaction: TxParams, block_identifier: BlockIdentifier | None = None, state_override: StateOverride | None = None, ) -> HexBytes: max_redirects = self.w3.provider.ccip_read_max_redirects if not max_redirects or max_redirects < 4: raise Web3ValueError( "ccip_read_max_redirects property on provider must be at least 4." ) for _ in range(max_redirects): try: return await self._call(transaction, block_identifier, state_override) except OffchainLookup as offchain_lookup: durin_calldata = await async_handle_offchain_lookup( offchain_lookup.payload, transaction, ) transaction["data"] = durin_calldata raise TooManyRequests("Too many CCIP read redirects") # eth_simulateV1 _simulateV1: Method[ Callable[ [SimulateV1Payload, BlockIdentifier], Awaitable[Sequence[SimulateV1Result]], ] ] = Method(RPC.eth_simulateV1) async def simulate_v1( self, payload: SimulateV1Payload, block_identifier: BlockIdentifier, ) -> Sequence[SimulateV1Result]: return await self._simulateV1(payload, block_identifier) # eth_createAccessList _create_access_list: Method[ Callable[ [TxParams, BlockIdentifier | None], Awaitable[CreateAccessListResponse], ] ] = Method(RPC.eth_createAccessList, mungers=[BaseEth.create_access_list_munger]) async def create_access_list( self, transaction: TxParams, block_identifier: BlockIdentifier | None = None, ) -> CreateAccessListResponse: return await self._create_access_list(transaction, block_identifier) # eth_estimateGas _estimate_gas: Method[ Callable[ [TxParams, BlockIdentifier | None, StateOverride | None], Awaitable[int], ] ] = Method(RPC.eth_estimateGas, mungers=[BaseEth.estimate_gas_munger]) async def estimate_gas( self, transaction: TxParams, block_identifier: BlockIdentifier | None = None, state_override: StateOverride | None = None, ) -> int: return await self._estimate_gas(transaction, block_identifier, state_override) # eth_getTransactionByHash _get_transaction: Method[Callable[[_Hash32], Awaitable[TxData]]] = Method( RPC.eth_getTransactionByHash, mungers=[default_root_munger] ) async def get_transaction(self, transaction_hash: _Hash32) -> TxData: return await self._get_transaction(transaction_hash) # eth_getRawTransactionByHash _get_raw_transaction: Method[Callable[[_Hash32], Awaitable[HexBytes]]] = Method( RPC.eth_getRawTransactionByHash, mungers=[default_root_munger] ) async def get_raw_transaction(self, transaction_hash: _Hash32) -> HexBytes: return await self._get_raw_transaction(transaction_hash) # eth_getTransactionByBlockNumberAndIndex # eth_getTransactionByBlockHashAndIndex _get_transaction_by_block: Method[ Callable[[BlockIdentifier, int], Awaitable[TxData]] ] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getTransactionByBlockNumberAndIndex, if_hash=RPC.eth_getTransactionByBlockHashAndIndex, if_number=RPC.eth_getTransactionByBlockNumberAndIndex, ), mungers=[default_root_munger], ) async def get_transaction_by_block( self, block_identifier: BlockIdentifier, index: int ) -> TxData: return await self._get_transaction_by_block(block_identifier, index) # eth_getRawTransactionByBlockHashAndIndex # eth_getRawTransactionByBlockNumberAndIndex _get_raw_transaction_by_block: Method[ Callable[[BlockIdentifier, int], Awaitable[HexBytes]] ] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getRawTransactionByBlockNumberAndIndex, if_hash=RPC.eth_getRawTransactionByBlockHashAndIndex, if_number=RPC.eth_getRawTransactionByBlockNumberAndIndex, ), mungers=[default_root_munger], ) async def get_raw_transaction_by_block( self, block_identifier: BlockIdentifier, index: int ) -> HexBytes: return await self._get_raw_transaction_by_block(block_identifier, index) # eth_getBlockTransactionCountByHash # eth_getBlockTransactionCountByNumber get_block_transaction_count: Method[ Callable[[BlockIdentifier], Awaitable[int]] ] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getBlockTransactionCountByNumber, if_hash=RPC.eth_getBlockTransactionCountByHash, if_number=RPC.eth_getBlockTransactionCountByNumber, ), mungers=[default_root_munger], ) # eth_sendTransaction _send_transaction: Method[Callable[[TxParams], Awaitable[HexBytes]]] = Method( RPC.eth_sendTransaction, mungers=[BaseEth.send_transaction_munger] ) async def send_transaction(self, transaction: TxParams) -> HexBytes: return await self._send_transaction(transaction) # eth_sendRawTransaction _send_raw_transaction: Method[ Callable[[HexStr | bytes], Awaitable[HexBytes]] ] = Method( RPC.eth_sendRawTransaction, mungers=[default_root_munger], ) async def send_raw_transaction(self, transaction: HexStr | bytes) -> HexBytes: return await self._send_raw_transaction(transaction) # eth_getBlockByHash # eth_getBlockByNumber _get_block: Method[ Callable[[BlockIdentifier, bool], Awaitable[BlockData]] ] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getBlockByNumber, if_hash=RPC.eth_getBlockByHash, if_number=RPC.eth_getBlockByNumber, ), mungers=[BaseEth.get_block_munger], ) async def get_block( self, block_identifier: BlockIdentifier, full_transactions: bool = False, ) -> BlockData: return await self._get_block(block_identifier, full_transactions) # eth_getBlockReceipts _get_block_receipts: Method[ Callable[[BlockIdentifier], Awaitable[BlockReceipts]] ] = Method( RPC.eth_getBlockReceipts, mungers=[default_root_munger], ) async def get_block_receipts( self, block_identifier: BlockIdentifier ) -> BlockReceipts: return await self._get_block_receipts(block_identifier) # eth_getBalance _get_balance: Method[ Callable[ [Address | ChecksumAddress | ENS, BlockIdentifier | None], Awaitable[Wei], ] ] = Method( RPC.eth_getBalance, mungers=[BaseEth.block_id_munger], ) async def get_balance( self, account: Address | ChecksumAddress | ENS, block_identifier: BlockIdentifier | None = None, ) -> Wei: return await self._get_balance(account, block_identifier) # eth_getCode _get_code: Method[ Callable[ [Address | ChecksumAddress | ENS, BlockIdentifier | None], Awaitable[HexBytes], ] ] = Method(RPC.eth_getCode, mungers=[BaseEth.block_id_munger]) async def get_code( self, account: Address | ChecksumAddress | ENS, block_identifier: BlockIdentifier | None = None, ) -> HexBytes: return await self._get_code(account, block_identifier) # eth_getLogs _get_logs: Method[Callable[[FilterParams], Awaitable[list[LogReceipt]]]] = Method( RPC.eth_getLogs, mungers=[default_root_munger] ) async def get_logs( self, filter_params: FilterParams, ) -> list[LogReceipt]: return await self._get_logs(filter_params) # eth_getTransactionCount _get_transaction_count: Method[ Callable[ [Address | ChecksumAddress | ENS, BlockIdentifier | None], Awaitable[Nonce], ] ] = Method( RPC.eth_getTransactionCount, mungers=[BaseEth.block_id_munger], ) async def get_transaction_count( self, account: Address | ChecksumAddress | ENS, block_identifier: BlockIdentifier | None = None, ) -> Nonce: return await self._get_transaction_count(account, block_identifier) # eth_getTransactionReceipt _transaction_receipt: Method[Callable[[_Hash32], Awaitable[TxReceipt]]] = Method( RPC.eth_getTransactionReceipt, mungers=[default_root_munger] ) async def get_transaction_receipt(self, transaction_hash: _Hash32) -> TxReceipt: return await self._transaction_receipt(transaction_hash) async def wait_for_transaction_receipt( self, transaction_hash: _Hash32, timeout: float | None = 120, poll_latency: float = 0.1, ) -> TxReceipt: async def _wait_for_tx_receipt_with_timeout( _tx_hash: _Hash32, _poll_latency: float ) -> TxReceipt: while True: try: tx_receipt = await self._transaction_receipt(_tx_hash) except (TransactionNotFound, TransactionIndexingInProgress): tx_receipt = None if tx_receipt is not None: break await asyncio.sleep(poll_latency) return tx_receipt try: return await asyncio.wait_for( _wait_for_tx_receipt_with_timeout(transaction_hash, poll_latency), timeout=timeout, ) except asyncio.TimeoutError: raise TimeExhausted( f"Transaction {HexBytes(transaction_hash) !r} is not in the chain " f"after {timeout} seconds" ) # eth_getStorageAt _get_storage_at: Method[ Callable[ [Address | ChecksumAddress | ENS, int, BlockIdentifier | None], Awaitable[HexBytes], ] ] = Method( RPC.eth_getStorageAt, mungers=[BaseEth.get_storage_at_munger], ) async def get_storage_at( self, account: Address | ChecksumAddress | ENS, position: int, block_identifier: BlockIdentifier | None = None, ) -> HexBytes: return await self._get_storage_at(account, position, block_identifier) async def replace_transaction( self, transaction_hash: _Hash32, new_transaction: TxParams ) -> HexBytes: current_transaction = await async_get_required_transaction( self.w3, transaction_hash ) return await async_replace_transaction( self.w3, current_transaction, new_transaction ) async def modify_transaction( self, transaction_hash: _Hash32, **transaction_params: Unpack[TxParams] ) -> HexBytes: assert_valid_transaction_params(cast(TxParams, transaction_params)) current_transaction = await async_get_required_transaction( self.w3, transaction_hash ) current_transaction_params = extract_valid_transaction_params( current_transaction ) new_transaction = merge(current_transaction_params, transaction_params) return await async_replace_transaction( self.w3, current_transaction, new_transaction ) # eth_sign _sign: Method[Callable[..., Awaitable[HexStr]]] = Method( RPC.eth_sign, mungers=[BaseEth.sign_munger] ) async def sign( self, account: Address | ChecksumAddress | ENS, data: int | bytes = None, hexstr: HexStr = None, text: str = None, ) -> HexStr: return await self._sign(account, data, hexstr, text) # eth_signTransaction _sign_transaction: Method[Callable[[TxParams], Awaitable[SignedTx]]] = Method( RPC.eth_signTransaction, mungers=[default_root_munger], ) async def sign_transaction(self, transaction: TxParams) -> SignedTx: return await self._sign_transaction(transaction) # eth_signTypedData _sign_typed_data: Method[ Callable[ [Address | ChecksumAddress | ENS, dict[str, Any]], Awaitable[HexStr], ] ] = Method( RPC.eth_signTypedData, mungers=[default_root_munger], ) async def sign_typed_data( self, account: Address | ChecksumAddress | ENS, data: dict[str, Any] ) -> HexStr: return await self._sign_typed_data(account, data) # eth_getUncleCountByBlockHash # eth_getUncleCountByBlockNumber _get_uncle_count: Method[Callable[[BlockIdentifier], Awaitable[int]]] = Method( method_choice_depends_on_args=select_method_for_block_identifier( if_predefined=RPC.eth_getUncleCountByBlockNumber, if_hash=RPC.eth_getUncleCountByBlockHash, if_number=RPC.eth_getUncleCountByBlockNumber, ), mungers=[default_root_munger], ) @deprecated_for("all get_uncle* methods will be removed in v8") async def get_uncle_count(self, block_identifier: BlockIdentifier) -> int: return await self._get_uncle_count(block_identifier) # eth_newFilter, eth_newBlockFilter, eth_newPendingTransactionFilter filter: Method[ Callable[[str | FilterParams | HexStr | None], Awaitable[AsyncFilter]] ] = Method( method_choice_depends_on_args=select_filter_method( if_new_block_filter=RPC.eth_newBlockFilter, if_new_pending_transaction_filter=RPC.eth_newPendingTransactionFilter, if_new_filter=RPC.eth_newFilter, ), mungers=[BaseEth.filter_munger], ) # eth_getFilterChanges, eth_getFilterLogs, eth_uninstallFilter _get_filter_changes: Method[ Callable[[HexStr], Awaitable[list[LogReceipt]]] ] = Method(RPC.eth_getFilterChanges, mungers=[default_root_munger]) async def get_filter_changes(self, filter_id: HexStr) -> list[LogReceipt]: return await self._get_filter_changes(filter_id) _get_filter_logs: Method[Callable[[HexStr], Awaitable[list[LogReceipt]]]] = Method( RPC.eth_getFilterLogs, mungers=[default_root_munger] ) async def get_filter_logs(self, filter_id: HexStr) -> list[LogReceipt]: return await self._get_filter_logs(filter_id) _uninstall_filter: Method[Callable[[HexStr], Awaitable[bool]]] = Method( RPC.eth_uninstallFilter, mungers=[default_root_munger], ) async def uninstall_filter(self, filter_id: HexStr) -> bool: return await self._uninstall_filter(filter_id) # eth_subscribe / eth_unsubscribe _subscribe: Method[Callable[[SubscriptionType], Awaitable[HexStr]]] = Method( RPC.eth_subscribe, mungers=[default_root_munger], ) async def subscribe( self, subscription_type: SubscriptionType, subscription_arg: None | ( LogsSubscriptionArg # logs, optional filter params | bool # newPendingTransactions, full_transactions ) = None, handler: EthSubscriptionHandler | None = None, handler_context: dict[str, Any] | None = None, label: str | None = None, parallelize: bool | None = None, ) -> HexStr: if not isinstance(self.w3.provider, PersistentConnectionProvider): raise MethodNotSupported( "eth_subscribe is only supported with providers that support " "persistent connections." ) sub = EthSubscription._create_type_aware_subscription( subscription_params=(subscription_type, subscription_arg), handler=handler, handler_context=handler_context or {}, label=label, parallelize=parallelize, ) return await self.w3.subscription_manager.subscribe(sub) _unsubscribe: Method[Callable[[HexStr], Awaitable[bool]]] = Method( RPC.eth_unsubscribe, mungers=[default_root_munger], ) async def unsubscribe(self, subscription_id: HexStr) -> bool: if not isinstance(self.w3.provider, PersistentConnectionProvider): raise MethodNotSupported( "eth_unsubscribe is only supported with providers that support " "persistent connections." ) for sub in self.w3.subscription_manager.subscriptions: if sub._id == subscription_id: return await sub.unsubscribe() raise Web3ValueError( f"Cannot unsubscribe subscription with id `{subscription_id}`. " "Subscription not found." ) # -- contract methods -- # @overload def contract(self, address: None = None, **kwargs: Any) -> type[AsyncContract]: ... @overload def contract( self, address: Address | ChecksumAddress | ENS, **kwargs: Any ) -> AsyncContract: ... def contract( self, address: Address | ChecksumAddress | ENS | None = None, **kwargs: Any, ) -> type[AsyncContract] | AsyncContract: ContractFactoryClass = kwargs.pop( "ContractFactoryClass", self._default_contract_factory ) ContractFactory = ContractFactoryClass.factory(self.w3, **kwargs) if address: return ContractFactory(address) else: return ContractFactory def set_contract_factory( self, contract_factory: type[AsyncContract | AsyncContractCaller], ) -> None: self._default_contract_factory = contract_factory
AsyncEth
python
boto__boto3
tests/integration/test_dynamodb.py
{ "start": 2460, "end": 7724 }
class ____(BaseDynamoDBTest): @classmethod def setUpClass(cls): super().setUpClass() cls.table.put_item(Item=cls.item_data) @classmethod def tearDownClass(cls): cls.table.delete_item(Key={'MyHashKey': 'mykey'}) super().tearDownClass() def scan(self, filter_expression): return self.table.scan( FilterExpression=filter_expression, ConsistentRead=True ) def query(self, key_condition_expression, filter_expression=None): kwargs = { 'KeyConditionExpression': key_condition_expression, 'ConsistentRead': True, } if filter_expression is not None: kwargs['FilterExpression'] = filter_expression return self.table.query(**kwargs) def test_filter_expression(self): r = self.scan(filter_expression=Attr('MyHashKey').eq('mykey')) self.assertEqual(r['Items'][0]['MyHashKey'], 'mykey') def test_key_condition_expression(self): r = self.query(key_condition_expression=Key('MyHashKey').eq('mykey')) self.assertEqual(r['Items'][0]['MyHashKey'], 'mykey') def test_key_condition_with_filter_condition_expression(self): r = self.query( key_condition_expression=Key('MyHashKey').eq('mykey'), filter_expression=Attr('MyString').eq('mystring'), ) self.assertEqual(r['Items'][0]['MyString'], 'mystring') def test_condition_less_than(self): r = self.scan(filter_expression=Attr('MyNumber').lt(Decimal('1.26'))) self.assertTrue(r['Items'][0]['MyNumber'] < Decimal('1.26')) def test_condition_less_than_equal(self): r = self.scan(filter_expression=Attr('MyNumber').lte(Decimal('1.26'))) self.assertTrue(r['Items'][0]['MyNumber'] <= Decimal('1.26')) def test_condition_greater_than(self): r = self.scan(filter_expression=Attr('MyNumber').gt(Decimal('1.24'))) self.assertTrue(r['Items'][0]['MyNumber'] > Decimal('1.24')) def test_condition_greater_than_equal(self): r = self.scan(filter_expression=Attr('MyNumber').gte(Decimal('1.24'))) self.assertTrue(r['Items'][0]['MyNumber'] >= Decimal('1.24')) def test_condition_begins_with(self): r = self.scan(filter_expression=Attr('MyString').begins_with('my')) self.assertTrue(r['Items'][0]['MyString'].startswith('my')) def test_condition_between(self): r = self.scan( filter_expression=Attr('MyNumber').between( Decimal('1.24'), Decimal('1.26') ) ) self.assertTrue(r['Items'][0]['MyNumber'] > Decimal('1.24')) self.assertTrue(r['Items'][0]['MyNumber'] < Decimal('1.26')) def test_condition_not_equal(self): r = self.scan(filter_expression=Attr('MyHashKey').ne('notmykey')) self.assertNotEqual(r['Items'][0]['MyHashKey'], 'notmykey') def test_condition_in(self): r = self.scan( filter_expression=Attr('MyHashKey').is_in(['notmykey', 'mykey']) ) self.assertIn(r['Items'][0]['MyHashKey'], ['notmykey', 'mykey']) def test_condition_exists(self): r = self.scan(filter_expression=Attr('MyString').exists()) self.assertIn('MyString', r['Items'][0]) def test_condition_not_exists(self): r = self.scan(filter_expression=Attr('MyFakeKey').not_exists()) self.assertNotIn('MyFakeKey', r['Items'][0]) def test_condition_contains(self): r = self.scan(filter_expression=Attr('MyString').contains('my')) self.assertIn('my', r['Items'][0]['MyString']) def test_condition_size(self): r = self.scan( filter_expression=Attr('MyString').size().eq(len('mystring')) ) self.assertEqual(len(r['Items'][0]['MyString']), len('mystring')) def test_condition_attribute_type(self): r = self.scan(filter_expression=Attr('MyMap').attribute_type('M')) self.assertIsInstance(r['Items'][0]['MyMap'], collections_abc.Mapping) def test_condition_and(self): r = self.scan( filter_expression=( Attr('MyHashKey').eq('mykey') & Attr('MyString').eq('mystring') ) ) item = r['Items'][0] self.assertTrue( item['MyHashKey'] == 'mykey' and item['MyString'] == 'mystring' ) def test_condition_or(self): r = self.scan( filter_expression=( Attr('MyHashKey').eq('mykey2') | Attr('MyString').eq('mystring') ) ) item = r['Items'][0] self.assertTrue( item['MyHashKey'] == 'mykey2' or item['MyString'] == 'mystring' ) def test_condition_not(self): r = self.scan(filter_expression=(~Attr('MyHashKey').eq('mykey2'))) item = r['Items'][0] self.assertTrue(item['MyHashKey'] != 'mykey2') def test_condition_in_map(self): r = self.scan(filter_expression=Attr('MyMap.foo').eq('bar')) self.assertEqual(r['Items'][0]['MyMap']['foo'], 'bar') def test_condition_in_list(self): r = self.scan(filter_expression=Attr('MyList[0]').eq('foo')) self.assertEqual(r['Items'][0]['MyList'][0], 'foo')
TestDynamoDBConditions
python
pytorch__pytorch
test/mobile/model_test/math_ops.py
{ "start": 8845, "end": 10278 }
class ____(torch.nn.Module): def forward(self): return self.reduction_ops() def reduction_ops(self): a = torch.randn(4) b = torch.randn(4) c = torch.tensor(0.5) return len( torch.argmax(a), torch.argmin(a), torch.amax(a), torch.amin(a), torch.aminmax(a), torch.all(a), torch.any(a), torch.max(a), a.max(a), torch.max(a, 0), torch.min(a), a.min(a), torch.min(a, 0), torch.dist(a, b), torch.logsumexp(a, 0), torch.mean(a), torch.mean(a, 0), torch.nanmean(a), torch.median(a), torch.nanmedian(a), torch.mode(a), torch.norm(a), a.norm(2), torch.norm(a, dim=0), torch.norm(c, torch.tensor(2)), torch.nansum(a), torch.prod(a), torch.quantile(a, torch.tensor([0.25, 0.5, 0.75])), torch.quantile(a, 0.5), torch.nanquantile(a, torch.tensor([0.25, 0.5, 0.75])), torch.std(a), torch.std_mean(a), torch.sum(a), torch.unique(a), torch.unique_consecutive(a), torch.var(a), torch.var_mean(a), torch.count_nonzero(a), )
ReductionOpsModule
python
pandas-dev__pandas
pandas/tests/reshape/concat/test_index.py
{ "start": 201, "end": 6427 }
class ____: def test_concat_ignore_index(self, sort): frame1 = DataFrame( {"test1": ["a", "b", "c"], "test2": [1, 2, 3], "test3": [4.5, 3.2, 1.2]} ) frame2 = DataFrame({"test3": [5.2, 2.2, 4.3]}) frame1.index = Index(["x", "y", "z"]) frame2.index = Index(["x", "y", "q"]) v1 = concat([frame1, frame2], axis=1, ignore_index=True, sort=sort) nan = np.nan expected = DataFrame( [ [nan, nan, nan, 4.3], ["a", 1, 4.5, 5.2], ["b", 2, 3.2, 2.2], ["c", 3, 1.2, nan], ], index=Index(["q", "x", "y", "z"]), ) if not sort: expected = expected.loc[["x", "y", "z", "q"]] tm.assert_frame_equal(v1, expected) @pytest.mark.parametrize( "name_in1,name_in2,name_in3,name_out", [ ("idx", "idx", "idx", "idx"), ("idx", "idx", None, None), ("idx", None, None, None), ("idx1", "idx2", None, None), ("idx1", "idx1", "idx2", None), ("idx1", "idx2", "idx3", None), (None, None, None, None), ], ) def test_concat_same_index_names(self, name_in1, name_in2, name_in3, name_out): # GH13475 indices = [ Index(["a", "b", "c"], name=name_in1), Index(["b", "c", "d"], name=name_in2), Index(["c", "d", "e"], name=name_in3), ] frames = [ DataFrame({c: [0, 1, 2]}, index=i) for i, c in zip(indices, ["x", "y", "z"]) ] result = concat(frames, axis=1) exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out) expected = DataFrame( { "x": [0, 1, 2, np.nan, np.nan], "y": [np.nan, 0, 1, 2, np.nan], "z": [np.nan, np.nan, 0, 1, 2], }, index=exp_ind, ) tm.assert_frame_equal(result, expected) def test_concat_rename_index(self): a = DataFrame( np.random.default_rng(2).random((3, 3)), columns=list("ABC"), index=Index(list("abc"), name="index_a"), ) b = DataFrame( np.random.default_rng(2).random((3, 3)), columns=list("ABC"), index=Index(list("abc"), name="index_b"), ) result = concat([a, b], keys=["key0", "key1"], names=["lvl0", "lvl1"]) exp = concat([a, b], keys=["key0", "key1"], names=["lvl0"]) names = list(exp.index.names) names[1] = "lvl1" exp.index.set_names(names, inplace=True) tm.assert_frame_equal(result, exp) assert result.index.names == exp.index.names def test_concat_copy_index_series(self, axis): # GH 29879 ser = Series([1, 2]) comb = concat([ser, ser], axis=axis) if axis in [0, "index"]: assert comb.index is not ser.index else: assert comb.index is ser.index def test_concat_copy_index_frame(self, axis): # GH 29879 df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) comb = concat([df, df], axis=axis) if axis in [0, "index"]: assert not comb.index.is_(df.index) assert comb.columns.is_(df.columns) elif axis in [1, "columns"]: assert comb.index.is_(df.index) assert not comb.columns.is_(df.columns) def test_default_index(self): # is_series and ignore_index s1 = Series([1, 2, 3], name="x") s2 = Series([4, 5, 6], name="y") res = concat([s1, s2], axis=1, ignore_index=True) assert isinstance(res.columns, pd.RangeIndex) exp = DataFrame([[1, 4], [2, 5], [3, 6]]) # use check_index_type=True to check the result have # RangeIndex (default index) tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) # is_series and all inputs have no names s1 = Series([1, 2, 3]) s2 = Series([4, 5, 6]) res = concat([s1, s2], axis=1, ignore_index=False) assert isinstance(res.columns, pd.RangeIndex) exp = DataFrame([[1, 4], [2, 5], [3, 6]]) exp.columns = pd.RangeIndex(2) tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) # is_dataframe and ignore_index df1 = DataFrame({"A": [1, 2], "B": [5, 6]}) df2 = DataFrame({"A": [3, 4], "B": [7, 8]}) res = concat([df1, df2], axis=0, ignore_index=True) exp = DataFrame([[1, 5], [2, 6], [3, 7], [4, 8]], columns=["A", "B"]) tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) res = concat([df1, df2], axis=1, ignore_index=True) exp = DataFrame([[1, 5, 3, 7], [2, 6, 4, 8]]) tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) def test_dups_index(self): # GH 4771 # single dtypes df = DataFrame( np.random.default_rng(2).integers(0, 10, size=40).reshape(10, 4), columns=["A", "A", "C", "C"], ) result = concat([df, df], axis=1) tm.assert_frame_equal(result.iloc[:, :4], df) tm.assert_frame_equal(result.iloc[:, 4:], df) result = concat([df, df], axis=0) tm.assert_frame_equal(result.iloc[:10], df) tm.assert_frame_equal(result.iloc[10:], df) # multi dtypes df = concat( [ DataFrame( np.random.default_rng(2).standard_normal((10, 4)), columns=["A", "A", "B", "B"], ), DataFrame( np.random.default_rng(2).integers(0, 10, size=20).reshape(10, 2), columns=["A", "C"], ), ], axis=1, ) result = concat([df, df], axis=1) tm.assert_frame_equal(result.iloc[:, :6], df) tm.assert_frame_equal(result.iloc[:, 6:], df) result = concat([df, df], axis=0) tm.assert_frame_equal(result.iloc[:10], df) tm.assert_frame_equal(result.iloc[10:], df)
TestIndexConcat
python
sympy__sympy
sympy/matrices/expressions/determinant.py
{ "start": 1706, "end": 3426 }
class ____(Expr): """Matrix Permanent Represents the permanent of a matrix expression. Examples ======== >>> from sympy import MatrixSymbol, Permanent, ones >>> A = MatrixSymbol('A', 3, 3) >>> Permanent(A) Permanent(A) >>> Permanent(ones(3, 3)).doit() 6 """ def __new__(cls, mat): mat = sympify(mat) if not mat.is_Matrix: raise TypeError("Input to Permanent, %s, not a matrix" % str(mat)) return Basic.__new__(cls, mat) @property def arg(self): return self.args[0] def doit(self, expand=False, **hints): if isinstance(self.arg, MatrixBase): return self.arg.per() else: return self def per(matexpr): """ Matrix Permanent Examples ======== >>> from sympy import MatrixSymbol, Matrix, per, ones >>> A = MatrixSymbol('A', 3, 3) >>> per(A) Permanent(A) >>> per(ones(5, 5)) 120 >>> M = Matrix([1, 2, 5]) >>> per(M) 8 """ return Permanent(matexpr).doit() from sympy.assumptions.ask import ask, Q from sympy.assumptions.refine import handlers_dict def refine_Determinant(expr, assumptions): """ >>> from sympy import MatrixSymbol, Q, assuming, refine, det >>> X = MatrixSymbol('X', 2, 2) >>> det(X) Determinant(X) >>> with assuming(Q.orthogonal(X)): ... print(refine(det(X))) 1 """ if ask(Q.orthogonal(expr.arg), assumptions): return S.One elif ask(Q.singular(expr.arg), assumptions): return S.Zero elif ask(Q.unit_triangular(expr.arg), assumptions): return S.One return expr handlers_dict['Determinant'] = refine_Determinant
Permanent
python
getsentry__sentry
tests/sentry/lang/javascript/test_processing.py
{ "start": 161, "end": 10359 }
class ____(TestCase): def test_is_in_app_with_webpack_paths(self) -> None: # Test webpack paths with node_modules self.assertFalse( is_in_app( { "abs_path": "webpack:///../node_modules/@sentry/browser/esm/helpers.js", "filename": "../node_modules/@sentry/browser/esm/helpers.js", } ) ) # Test webpack paths with ~ self.assertFalse( is_in_app( { "abs_path": "webpack:///~/@sentry/browser/esm/helpers.js", "filename": "~/@sentry/browser/esm/helpers.js", } ) ) # Test webpack paths with ./ prefix (should be in-app) self.assertTrue( is_in_app( { "abs_path": "webpack:///./@sentry/browser/esm/helpers.js", "filename": "./@sentry/browser/esm/helpers.js", } ) ) # Test webpack paths with regular path (should be in-app) self.assertTrue( is_in_app( {"abs_path": "webpack:///foo/bar/src/App.jsx", "filename": "foo/bar/src/App.jsx"} ) ) # Test webpack paths with ./ prefix in abs_path self.assertTrue( is_in_app( {"abs_path": "webpack:///./foo/bar/App.tsx", "filename": "./foo/bar/src/App.jsx"} ) ) # Test webpack paths with node_modules in ./ path self.assertFalse( is_in_app( { "abs_path": "webpack:///./node_modules/@sentry/browser/esm/helpers.js", "filename": "./node_modules/@sentry/browser/esm/helpers.js", } ) ) def test_is_in_app_with_app_paths(self) -> None: # Test app paths with node_modules self.assertFalse( is_in_app( { "abs_path": "app:///../node_modules/@sentry/browser/esm/helpers.js", "filename": "../node_modules/@sentry/browser/esm/helpers.js", } ) ) # Test app paths without node_modules self.assertTrue( is_in_app( { "abs_path": "app:///../@sentry/browser/esm/helpers.js", "filename": "../@sentry/browser/esm/helpers.js", } ) ) # Test app paths with node_modules in the path self.assertFalse( is_in_app( { "abs_path": "app:///node_modules/rxjs/internal/operators/switchMap.js", "filename": "node_modules/rxjs/internal/operators/switchMap.js", } ) ) def test_is_in_app_with_general_paths(self) -> None: # Test file paths with node_modules self.assertFalse( is_in_app( { "abs_path": "file:///../node_modules/@sentry/browser/esm/helpers.js", "filename": "../node_modules/@sentry/browser/esm/helpers.js", } ) ) # Test file paths without node_modules (should return None) self.assertIsNone( is_in_app( { "abs_path": "file:///../@sentry/browser/esm/helpers.js", "filename": "../@sentry/browser/esm/helpers.js", } ) ) def test_node_modules_regex(self) -> None: # Test the NODE_MODULES_RE pattern directly self.assertIsNotNone(NODE_MODULES_RE.search("/node_modules/")) self.assertIsNotNone(NODE_MODULES_RE.search("path/node_modules/package")) self.assertIsNotNone(NODE_MODULES_RE.search("/path/to/node_modules/react")) # Should not match without the slashes self.assertIsNone(NODE_MODULES_RE.search("node_modules")) self.assertIsNone(NODE_MODULES_RE.search("mynode_modules")) def _get_test_data_and_symbolicator(self, in_app_frames: bool, symbolicated_in_app=True): """Helper method to create test data and mock symbolicator Args: in_app_frames: If True, use frames that will be marked as in_app. If False, use only non-in-app frames. symbolicated_in_app: Only relevant when in_app_frames=True. If True, all in_app frames will be symbolicated. If False, some in_app frames will not be symbolicated. """ if in_app_frames: # Use frames where one is in_app (App.jsx) and one is not (react) frames = [ { "abs_path": "webpack:///app/components/App.jsx", "filename": "app/components/App.jsx", "lineno": 10, "colno": 15, "function": "render", "platform": "javascript", }, { "abs_path": "webpack:///node_modules/react/index.js", "filename": "node_modules/react/index.js", "lineno": 20, "colno": 30, "function": "createElement", "platform": "javascript", }, ] symbolicated_frames = [ { "abs_path": "webpack:///app/components/App.jsx", "filename": "app/components/App.jsx", "lineno": 42, "colno": 23, "function": "MyComponent.renderHeader", "data": { "symbolicated": symbolicated_in_app, "sourcemap": "webpack:///app/components/App.jsx.map", "resolved_with": "source-map", }, "platform": "javascript", }, { "abs_path": "webpack:///node_modules/react/index.js", "filename": "./node_modules/react/index.js", # Note ./ prefix "lineno": 20, "colno": 30, "function": "createElement", "data": { "symbolicated": True, "sourcemap": "webpack:///node_modules/react/index.js.map", "resolved_with": "source-map", }, "platform": "javascript", }, ] else: # Use only non-in-app frames (both from node_modules) frames = [ { "abs_path": "webpack:///node_modules/lodash/index.js", "filename": "./node_modules/lodash/index.js", # has /node_modules/ "lineno": 10, "colno": 15, "function": "map", "platform": "javascript", }, { "abs_path": "webpack:///node_modules/react/index.js", "filename": "./node_modules/react/index.js", # has /node_modules/ "lineno": 20, "colno": 30, "function": "createElement", "platform": "javascript", }, ] symbolicated_frames = [ { "abs_path": "webpack:///node_modules/lodash/index.js", "filename": "./node_modules/lodash/index.js", "lineno": 10, "colno": 15, "function": "map", "platform": "javascript", "data": {"symbolicated": True}, }, { "abs_path": "webpack:///node_modules/react/index.js", "filename": "./node_modules/react/index.js", "lineno": 20, "colno": 30, "function": "createElement", "platform": "javascript", "data": {"symbolicated": True}, }, ] data = { "platform": "javascript", "exception": { "values": [ { "type": "Error", "stacktrace": {"frames": frames}, } ] }, } symbolicator = Mock() symbolicator.process_js.return_value = { "status": "completed", "stacktraces": [{"frames": symbolicated_frames}], "raw_stacktraces": [{"frames": frames}], } return data, symbolicator def test_process_js_stacktraces_with_symbolicated_in_app_frames(self) -> None: """Test symbolicated_in_app is True when all in-app frames are symbolicated""" data, symbolicator = self._get_test_data_and_symbolicator( in_app_frames=True, symbolicated_in_app=True ) result = process_js_stacktraces(symbolicator, data) self.assertTrue(result["symbolicated_in_app"]) def test_process_js_stacktraces_with_unsymbolicated_in_app_frames(self) -> None: """Test symbolicated_in_app is False when in-app frames are not symbolicated""" data, symbolicator = self._get_test_data_and_symbolicator( in_app_frames=True, symbolicated_in_app=False ) result = process_js_stacktraces(symbolicator, data) self.assertFalse(result["symbolicated_in_app"]) def test_process_js_stacktraces_with_no_in_app_frames(self) -> None: """Test symbolicated_in_app is None when all frames are non-in-app""" data, symbolicator = self._get_test_data_and_symbolicator(in_app_frames=False) result = process_js_stacktraces(symbolicator, data) self.assertIsNotNone(result) # Should process frames and return data self.assertIsNone( result["symbolicated_in_app"] ) # Should be None since no frames are in_app
JavaScriptProcessingTest
python
getsentry__sentry
tests/sentry/integrations/slack/webhooks/options_load/test_dynamic_assignment_dropdown.py
{ "start": 185, "end": 6480 }
class ____(BaseEventTest): def setUp(self) -> None: super().setUp() self.event_data = { "event_id": "a" * 32, "message": "IntegrationError", "fingerprint": ["group-1"], "exception": { "values": [ { "type": "IntegrationError", "value": "Identity not found.", } ] }, } self.original_message: dict = { "type": "message", "text": "[internal] IntegrationError", "blocks": [ { "block_id": "", "type": "section", "text": {"type": "mrkdwn", "text": "IntegrationError", "verbatim": False}, }, { "type": "actions", "elements": [ { "type": "button", "action_id": "resolve_dialog", "text": {"type": "plain_text", "text": "Resolve", "emoji": True}, "value": "resolve_dialog", }, { "type": "button", "action_id": "archive_dialog", "text": {"type": "plain_text", "text": "Archive", "emoji": True}, "value": "archive_dialog", }, { "type": "external_select", "action_id": "assign", "placeholder": { "type": "plain_text", "text": "Select Assignee...", "emoji": True, }, }, ], }, ], } @freeze_time("2021-01-14T12:27:28.303Z") def test_simple(self) -> None: self.team1 = self.create_team(name="aaaa", slug="aaaa") self.team2 = self.create_team(name="aaab", slug="eeee") self.team3 = self.create_team(name="xyz", slug="aaac") self.team4 = self.create_team( name="zzaaazz", slug="zzaaazz" ) # name nor slug doesn't start with substring self.team5 = self.create_team(name="aaad", slug="aaad") # not in project self.project = self.create_project(teams=[self.team1, self.team2, self.team3, self.team4]) self.group = self.create_group(project=self.project) self.original_message["blocks"][0]["block_id"] = orjson.dumps( {"issue": self.group.id} ).decode() self.user1 = self.create_user(email="aaa@testing.com", name="Alice") self.create_member(organization=self.organization, user=self.user1, teams=[self.team4]) self.user2 = self.create_user(email="blah@testing.com", name="AaA") self.create_member(organization=self.organization, user=self.user2, teams=[self.team4]) self.user3 = self.create_user(email="bbb@testing.com", name="aaa") self.create_member(organization=self.organization, user=self.user3, teams=[self.team4]) self.user4 = self.create_user( email="baaa@testing.com", name="Baaa" ) # name nor email doesn't start with substring self.create_member(organization=self.organization, user=self.user4, teams=[self.team4]) self.user5 = self.create_user(email="aaaa@testing.com", name="aaa") self.create_member( organization=self.organization, user=self.user5, teams=[self.team5] ) # not in project self.store_event(data=self.event_data, project_id=self.project.id) resp = self.post_webhook(substring="aaa", original_message=self.original_message) assert resp.status_code == 200 assert len(resp.data["option_groups"][0]["options"]) == 3 assert len(resp.data["option_groups"][1]["options"]) == 3 @freeze_time("2021-01-14T12:27:28.303Z") def test_escapes_special_characters(self) -> None: self.team1 = self.create_team(name="aaaa", slug="aaaa") self.project = self.create_project(teams=[self.team1]) self.group = self.create_group(project=self.project) self.original_message["blocks"][0]["block_id"] = orjson.dumps( {"issue": self.group.id} ).decode() self.user1 = self.create_user(email="aaa@testing.com", name="Alice") self.create_member(organization=self.organization, user=self.user1, teams=[self.team1]) self.store_event(data=self.event_data, project_id=self.project.id) # shouldn't fail resp = self.post_webhook(substring="Al[", original_message=self.original_message) assert resp.status_code == 200 assert len(resp.data["option_groups"]) == 0 def test_non_existent_group(self) -> None: self.original_message["blocks"][0]["block_id"] = orjson.dumps({"issue": 1}).decode() resp = self.post_webhook(substring="bbb", original_message=self.original_message) assert resp.status_code == 400 @freeze_time("2021-01-14T12:27:28.303Z") def test_escapes_characters_in_substring_but_not_string(self) -> None: self.team1 = self.create_team(name="aaaa", slug="aaaa") self.project = self.create_project(teams=[self.team1]) self.group = self.create_group(project=self.project) self.original_message["blocks"][0]["block_id"] = orjson.dumps( {"issue": self.group.id} ).decode() self.user1 = self.create_user(email="aaa@testing.com", name="Alice") self.create_member(organization=self.organization, user=self.user1, teams=[self.team1]) self.store_event(data=self.event_data, project_id=self.project.id) # shouldn't fail even though substring has special characters resp = self.post_webhook( substring="aaa@testing.com", original_message=self.original_message ) assert resp.status_code == 200 assert len(resp.data["option_groups"]) == 1 assert len(resp.data["option_groups"][0]["options"]) == 1
DynamicAssignmentDropdownTest
python
facebook__pyre-check
api/connection.py
{ "start": 1106, "end": 1160 }
class ____(TypedDict): response: Any
PyreQueryResult
python
pandas-dev__pandas
pandas/tests/tseries/offsets/test_month.py
{ "start": 513, "end": 9470 }
class ____: def test_offset_whole_year(self): dates = ( datetime(2007, 12, 31), datetime(2008, 1, 15), datetime(2008, 1, 31), datetime(2008, 2, 15), datetime(2008, 2, 29), datetime(2008, 3, 15), datetime(2008, 3, 31), datetime(2008, 4, 15), datetime(2008, 4, 30), datetime(2008, 5, 15), datetime(2008, 5, 31), datetime(2008, 6, 15), datetime(2008, 6, 30), datetime(2008, 7, 15), datetime(2008, 7, 31), datetime(2008, 8, 15), datetime(2008, 8, 31), datetime(2008, 9, 15), datetime(2008, 9, 30), datetime(2008, 10, 15), datetime(2008, 10, 31), datetime(2008, 11, 15), datetime(2008, 11, 30), datetime(2008, 12, 15), datetime(2008, 12, 31), ) for base, exp_date in zip(dates[:-1], dates[1:], strict=True): assert_offset_equal(SemiMonthEnd(), base, exp_date) # ensure .apply_index works as expected shift = DatetimeIndex(dates[:-1]) with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex result = SemiMonthEnd() + shift exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) offset_cases = [] offset_cases.append( ( SemiMonthEnd(), { datetime(2008, 1, 1): datetime(2008, 1, 15), datetime(2008, 1, 15): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 2, 15), datetime(2006, 12, 14): datetime(2006, 12, 15), datetime(2006, 12, 29): datetime(2006, 12, 31), datetime(2006, 12, 31): datetime(2007, 1, 15), datetime(2007, 1, 1): datetime(2007, 1, 15), datetime(2006, 12, 1): datetime(2006, 12, 15), datetime(2006, 12, 15): datetime(2006, 12, 31), }, ) ) offset_cases.append( ( SemiMonthEnd(day_of_month=20), { datetime(2008, 1, 1): datetime(2008, 1, 20), datetime(2008, 1, 15): datetime(2008, 1, 20), datetime(2008, 1, 21): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 2, 20), datetime(2006, 12, 14): datetime(2006, 12, 20), datetime(2006, 12, 29): datetime(2006, 12, 31), datetime(2006, 12, 31): datetime(2007, 1, 20), datetime(2007, 1, 1): datetime(2007, 1, 20), datetime(2006, 12, 1): datetime(2006, 12, 20), datetime(2006, 12, 15): datetime(2006, 12, 20), }, ) ) offset_cases.append( ( SemiMonthEnd(0), { datetime(2008, 1, 1): datetime(2008, 1, 15), datetime(2008, 1, 16): datetime(2008, 1, 31), datetime(2008, 1, 15): datetime(2008, 1, 15), datetime(2008, 1, 31): datetime(2008, 1, 31), datetime(2006, 12, 29): datetime(2006, 12, 31), datetime(2006, 12, 31): datetime(2006, 12, 31), datetime(2007, 1, 1): datetime(2007, 1, 15), }, ) ) offset_cases.append( ( SemiMonthEnd(0, day_of_month=16), { datetime(2008, 1, 1): datetime(2008, 1, 16), datetime(2008, 1, 16): datetime(2008, 1, 16), datetime(2008, 1, 15): datetime(2008, 1, 16), datetime(2008, 1, 31): datetime(2008, 1, 31), datetime(2006, 12, 29): datetime(2006, 12, 31), datetime(2006, 12, 31): datetime(2006, 12, 31), datetime(2007, 1, 1): datetime(2007, 1, 16), }, ) ) offset_cases.append( ( SemiMonthEnd(2), { datetime(2008, 1, 1): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 2, 29), datetime(2006, 12, 29): datetime(2007, 1, 15), datetime(2006, 12, 31): datetime(2007, 1, 31), datetime(2007, 1, 1): datetime(2007, 1, 31), datetime(2007, 1, 16): datetime(2007, 2, 15), datetime(2006, 11, 1): datetime(2006, 11, 30), }, ) ) offset_cases.append( ( SemiMonthEnd(-1), { datetime(2007, 1, 1): datetime(2006, 12, 31), datetime(2008, 6, 30): datetime(2008, 6, 15), datetime(2008, 12, 31): datetime(2008, 12, 15), datetime(2006, 12, 29): datetime(2006, 12, 15), datetime(2006, 12, 30): datetime(2006, 12, 15), datetime(2007, 1, 1): datetime(2006, 12, 31), }, ) ) offset_cases.append( ( SemiMonthEnd(-1, day_of_month=4), { datetime(2007, 1, 1): datetime(2006, 12, 31), datetime(2007, 1, 4): datetime(2006, 12, 31), datetime(2008, 6, 30): datetime(2008, 6, 4), datetime(2008, 12, 31): datetime(2008, 12, 4), datetime(2006, 12, 5): datetime(2006, 12, 4), datetime(2006, 12, 30): datetime(2006, 12, 4), datetime(2007, 1, 1): datetime(2006, 12, 31), }, ) ) offset_cases.append( ( SemiMonthEnd(-2), { datetime(2007, 1, 1): datetime(2006, 12, 15), datetime(2008, 6, 30): datetime(2008, 5, 31), datetime(2008, 3, 15): datetime(2008, 2, 15), datetime(2008, 12, 31): datetime(2008, 11, 30), datetime(2006, 12, 29): datetime(2006, 11, 30), datetime(2006, 12, 14): datetime(2006, 11, 15), datetime(2007, 1, 1): datetime(2006, 12, 15), }, ) ) @pytest.mark.parametrize("case", offset_cases) def test_offset(self, case): offset, cases = case for base, expected in cases.items(): assert_offset_equal(offset, base, expected) @pytest.mark.parametrize("case", offset_cases) def test_apply_index(self, case): # https://github.com/pandas-dev/pandas/issues/34580 offset, cases = case shift = DatetimeIndex(cases.keys()) exp = DatetimeIndex(cases.values()) with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex result = offset + shift tm.assert_index_equal(result, exp) on_offset_cases = [ (datetime(2007, 12, 31), True), (datetime(2007, 12, 15), True), (datetime(2007, 12, 14), False), (datetime(2007, 12, 1), False), (datetime(2008, 2, 29), True), ] @pytest.mark.parametrize("case", on_offset_cases) def test_is_on_offset(self, case): dt, expected = case assert_is_on_offset(SemiMonthEnd(), dt, expected) @pytest.mark.parametrize("klass", [Series, DatetimeIndex]) def test_vectorized_offset_addition(self, klass): shift = klass( [ Timestamp("2000-01-15 00:15:00", tz="US/Central"), Timestamp("2000-02-15", tz="US/Central"), ], name="a", ) with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex result = shift + SemiMonthEnd() result2 = SemiMonthEnd() + shift exp = klass( [ Timestamp("2000-01-31 00:15:00", tz="US/Central"), Timestamp("2000-02-29", tz="US/Central"), ], name="a", ) tm.assert_equal(result, exp) tm.assert_equal(result2, exp) shift = klass( [ Timestamp("2000-01-01 00:15:00", tz="US/Central"), Timestamp("2000-02-01", tz="US/Central"), ], name="a", ) with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex result = shift + SemiMonthEnd() result2 = SemiMonthEnd() + shift exp = klass( [ Timestamp("2000-01-15 00:15:00", tz="US/Central"), Timestamp("2000-02-15", tz="US/Central"), ], name="a", ) tm.assert_equal(result, exp) tm.assert_equal(result2, exp)
TestSemiMonthEnd
python
huggingface__transformers
tests/models/olmo/test_modeling_olmo.py
{ "start": 5835, "end": 6826 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (OlmoModel, OlmoForCausalLM) if is_torch_available() else () pipeline_model_mapping = ( { "feature-extraction": OlmoModel, "text-generation": OlmoForCausalLM, } if is_torch_available() else {} ) # Need to use `0.8` instead of `0.9` for `test_cpu_offload` # This is because we are hitting edge cases with the causal_mask buffer model_split_percents = [0.5, 0.7, 0.8] def setUp(self): self.model_tester = OlmoModelTester(self) self.config_tester = ConfigTester(self, config_class=OlmoConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @require_torch
OlmoModelTest
python
kamyu104__LeetCode-Solutions
Python/number-of-single-divisor-triplets.py
{ "start": 118, "end": 627 }
class ____(object): def singleDivisorTriplet(self, nums): """ :type nums: List[int] :rtype: int """ def check(a, b, c): return sum((a+b+c)%x == 0 for x in (a, b, c)) == 1 cnt = collections.Counter(nums) return 6*(sum(cnt[a]*cnt[b]*cnt[c] for a, b, c in itertools.combinations(cnt.keys(), 3) if check(a, b, c)) + sum(cnt[a]*(cnt[a]-1)//2*cnt[b] for a, b in itertools.permutations(cnt.keys(), 2) if check(a, a, b)))
Solution
python
networkx__networkx
networkx/classes/tests/test_coreviews.py
{ "start": 3340, "end": 4433 }
class ____(TestAdjacencyView): # node->nbr->key->data def setup_method(self): dd = {"color": "blue", "weight": 1.2} self.kd = {0: dd, 1: {}, 2: {"color": 1}} self.nd = {3: self.kd, 0: {3: dd}, 1: {0: {}}, 2: {3: {"color": 1}}} self.adj = {3: self.nd, 0: {3: {3: dd}}, 1: {}, 2: {3: {8: {}}}} self.adjview = nx.classes.coreviews.MultiAdjacencyView(self.adj) def test_getitem(self): assert self.adjview[1] is not self.adj[1] assert self.adjview[3][0][3] is self.adjview[0][3][3] assert self.adjview[3][2][3]["color"] == 1 pytest.raises(KeyError, self.adjview.__getitem__, 4) def test_copy(self): avcopy = self.adjview.copy() assert avcopy[0] == self.adjview[0] assert avcopy[0] is not self.adjview[0] avcopy[2][3][8]["ht"] = 4 assert avcopy[2] != self.adjview[2] self.adjview[2][3][8]["ht"] = 4 assert avcopy[2] == self.adjview[2] del self.adjview[2][3][8]["ht"] assert not hasattr(self.adjview, "__setitem__")
TestMultiAdjacencyView
python
huggingface__transformers
tests/models/aimv2/test_modeling_aimv2.py
{ "start": 11588, "end": 13675 }
class ____: def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=False): if text_kwargs is None: text_kwargs = {} if vision_kwargs is None: vision_kwargs = {} self.parent = parent self.text_model_tester = Aimv2TextModelTester(parent, **text_kwargs) self.vision_model_tester = Aimv2VisionModelTester(parent, **vision_kwargs) self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test self.is_training = is_training def prepare_config_and_inputs(self): text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs() config = self.get_config() return config, input_ids, attention_mask, pixel_values def get_config(self): return Aimv2Config( text_config=self.text_model_tester.get_config(), vision_config=self.vision_model_tester.get_config(), projection_dim=64, ) def create_and_check_model(self, config, input_ids, attention_mask, pixel_values): model = Aimv2Model(config).to(torch_device).eval() with torch.no_grad(): result = model(input_ids, pixel_values, attention_mask) self.parent.assertEqual( result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size) ) self.parent.assertEqual( result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size) ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, pixel_values = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, } return config, inputs_dict @require_torch
Aimv2ModelTester
python
huggingface__transformers
src/transformers/models/umt5/modeling_umt5.py
{ "start": 70090, "end": 73231 }
class ____(UMT5PreTrainedModel): _keys_to_ignore_on_load_unexpected = ["decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight"] # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.__init__ with T5->UMT5 def __init__(self, config: UMT5Config): super().__init__(config) self.num_labels = config.num_labels self.transformer = UMT5EncoderModel(config) self.dropout = nn.Dropout(config.classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @auto_docstring # Copied from transformers.models.t5.modeling_t5.T5ForTokenClassification.forward with T5->UMT5, t5->umt5 def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]: r""" input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. UMT5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for detail. [What are input IDs?](../glossary#input-ids) To know more on how to prepare `input_ids` for pretraining take a look a [UMT5 Training](./umt5#training). labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.transformer( input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] hidden_states = self.dropout(hidden_states) logits = self.classifier(hidden_states) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits, outputs[2:-1]) return ((loss,) + output) if loss is not None else output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring
UMT5ForTokenClassification
python
apache__airflow
airflow-core/src/airflow/ti_deps/deps/dagrun_exists_dep.py
{ "start": 974, "end": 1449 }
class ____(BaseTIDep): """Determines whether a task's DagRun is in valid state.""" NAME = "Dagrun Running" IGNORABLE = True @provide_session def _get_dep_statuses(self, ti, session, dep_context): dr = ti.get_dagrun(session) if dr.state != DagRunState.RUNNING: yield self._failing_status( reason=f"Task instance's dagrun was not in the 'running' state but in the state '{dr.state}'." )
DagrunRunningDep
python
paramiko__paramiko
tests/test_kex.py
{ "start": 3865, "end": 36976 }
class ____(unittest.TestCase): K = 14730343317708716439807310032871972459448364195094179797249681733965528989482751523943515690110179031004049109375612685505881911274101441415545039654102474376472240501616988799699744135291070488314748284283496055223852115360852283821334858541043710301057312858051901453919067023103730011648890038847384890504 # noqa def setUp(self): self._original_urandom = os.urandom os.urandom = dummy_urandom self._original_generate_key_pair = KexNistp256._generate_key_pair KexNistp256._generate_key_pair = dummy_generate_key_pair if KexCurve25519.is_available(): static_x25519_key = x25519.X25519PrivateKey.from_private_bytes( unhexlify( b"2184abc7eb3e656d2349d2470ee695b570c227340c2b2863b6c9ff427af1f040" # noqa ) ) mock_x25519 = Mock() mock_x25519.generate.return_value = static_x25519_key patcher = patch( "paramiko.kex_curve25519.X25519PrivateKey", mock_x25519 ) patcher.start() self.x25519_patcher = patcher def tearDown(self): os.urandom = self._original_urandom KexNistp256._generate_key_pair = self._original_generate_key_pair if hasattr(self, "x25519_patcher"): self.x25519_patcher.stop() def test_group1_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGroup1(transport) kex.start_kex() x = b"1E000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect ) # fake "reply" msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) H = b"03079780F3D3AD0B3C6DB30C8D21685F367A86D2" self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_group1_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGroup1(transport) kex.start_kex() self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_INIT,), transport._expect ) msg = Message() msg.add_mpint(69) msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) H = b"B16BF34DD10945EDE84E9C1EF24A14BFDC843389" x = b"1F0000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" # noqa self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_gex_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGex(transport) kex.start_kex() x = b"22000004000000080000002000" self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect ) msg = Message() msg.add_mpint(FakeModulusPack.P) msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect ) msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b"A265563F2FA87F1A89BF007EE90D58BE2E4A4BD0" self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_gex_old_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGex(transport) kex.start_kex(_test_old_style=True) x = b"1E00000800" self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect ) msg = Message() msg.add_mpint(FakeModulusPack.P) msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect ) msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b"807F87B269EF7AC5EC7E75676808776A27D5864C" self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_gex_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGex(transport) kex.start_kex() self.assertEqual( ( paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, ), transport._expect, ) msg = Message() msg.add_int(1024) msg.add_int(2048) msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect ) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 # noqa H = b"CE754197C21BF3452863B4F44D0B3951F12516EF" x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_gex_server_with_old_client(self): transport = FakeTransport() transport.server_mode = True kex = KexGex(transport) kex.start_kex() self.assertEqual( ( paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, ), transport._expect, ) msg = Message() msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect ) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 # noqa H = b"B41A06B2E59043CEFC1AE16EC31F1E2D12EC455B" x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_gex_sha256_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGexSHA256(transport) kex.start_kex() x = b"22000004000000080000002000" self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect ) msg = Message() msg.add_mpint(FakeModulusPack.P) msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect ) msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b"AD1A9365A67B4496F05594AD1BF656E3CDA0851289A4C1AFF549FEAE50896DF4" self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_gex_sha256_old_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGexSHA256(transport) kex.start_kex(_test_old_style=True) x = b"1E00000800" self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_GROUP,), transport._expect ) msg = Message() msg.add_mpint(FakeModulusPack.P) msg.add_mpint(FakeModulusPack.G) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_GROUP, msg) x = b"20000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D4" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_REPLY,), transport._expect ) msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REPLY, msg) H = b"518386608B15891AE5237DEE08DCADDE76A0BCEFCE7F6DB3AD66BC41D256DFE5" self.assertEqual(self.K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_gex_sha256_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGexSHA256(transport) kex.start_kex() self.assertEqual( ( paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, ), transport._expect, ) msg = Message() msg.add_int(1024) msg.add_int(2048) msg.add_int(4096) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, msg) x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect ) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 # noqa H = b"CCAC0497CF0ABA1DBF55E1A3995D17F4CC31824B0E8D95CDF8A06F169D050D80" x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_gex_sha256_server_with_old_client(self): transport = FakeTransport() transport.server_mode = True kex = KexGexSHA256(transport) kex.start_kex() self.assertEqual( ( paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST, paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, ), transport._expect, ) msg = Message() msg.add_int(2048) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_REQUEST_OLD, msg) x = b"1F0000008100FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF0000000102" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_gex._MSG_KEXDH_GEX_INIT,), transport._expect ) msg = Message() msg.add_mpint(12345) msg.rewind() kex.parse_next(paramiko.kex_gex._MSG_KEXDH_GEX_INIT, msg) K = 67592995013596137876033460028393339951879041140378510871612128162185209509220726296697886624612526735888348020498716482757677848959420073720160491114319163078862905400020959196386947926388406687288901564192071077389283980347784184487280885335302632305026248574716290537036069329724382811853044654824945750581 # noqa H = b"3DDD2AD840AD095E397BA4D0573972DC60F6461FD38A187CACA6615A5BC8ADBB" x = b"210000000866616B652D6B6579000000807E2DDB1743F3487D6545F04F1C8476092FB912B013626AB5BCEB764257D88BBA64243B9F348DF7B41B8C814A995E00299913503456983FFB9178D3CD79EB6D55522418A8ABF65375872E55938AB99A84A0B5FC8A1ECC66A7C3766E7E0F80B7CE2C9225FC2DD683F4764244B72963BBB383F529DCF0C5D17740B8A2ADBE9208D40000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_kex_nistp256_client(self): K = 91610929826364598472338906427792435253694642563583721654249504912114314269754 # noqa transport = FakeTransport() transport.server_mode = False kex = KexNistp256(transport) kex.start_kex() self.assertEqual( (paramiko.kex_ecdh_nist._MSG_KEXECDH_REPLY,), transport._expect ) # fake reply msg = Message() msg.add_string("fake-host-key") Q_S = unhexlify( "043ae159594ba062efa121480e9ef136203fa9ec6b6e1f8723a321c16e62b945f573f3b822258cbcd094b9fa1c125cbfe5f043280893e66863cc0cb4dccbe70210" # noqa ) msg.add_string(Q_S) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_ecdh_nist._MSG_KEXECDH_REPLY, msg) H = b"BAF7CE243A836037EB5D2221420F35C02B9AB6C957FE3BDE3369307B9612570A" self.assertEqual(K, kex.transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_kex_nistp256_server(self): K = 91610929826364598472338906427792435253694642563583721654249504912114314269754 # noqa transport = FakeTransport() transport.server_mode = True kex = KexNistp256(transport) kex.start_kex() self.assertEqual( (paramiko.kex_ecdh_nist._MSG_KEXECDH_INIT,), transport._expect ) # fake init msg = Message() Q_C = unhexlify( "043ae159594ba062efa121480e9ef136203fa9ec6b6e1f8723a321c16e62b945f573f3b822258cbcd094b9fa1c125cbfe5f043280893e66863cc0cb4dccbe70210" # noqa ) H = b"2EF4957AFD530DD3F05DBEABF68D724FACC060974DA9704F2AEE4C3DE861E7CA" msg.add_string(Q_C) msg.rewind() kex.parse_next(paramiko.kex_ecdh_nist._MSG_KEXECDH_INIT, msg) self.assertEqual(K, transport._K) self.assertTrue(transport._activated) self.assertEqual(H, hexlify(transport._H).upper()) def test_kex_group14_sha256_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGroup14SHA256(transport) kex.start_kex() x = b"1E00000101009850B3A8DE3ECCD3F19644139137C93D9C11BC28ED8BE850908EE294E1D43B88B9295311EFAEF5B736A1B652EBE184CCF36CFB0681C1ED66430088FA448B83619F928E7B9592ED6160EC11D639D51C303603F930F743C646B1B67DA38A1D44598DCE6C3F3019422B898044141420E9A10C29B9C58668F7F20A40F154B2C4768FCF7A9AA7179FB6366A7167EE26DD58963E8B880A0572F641DE0A73DC74C930F7C3A0C9388553F3F8403E40CF8B95FEDB1D366596FCF3FDDEB21A0005ADA650EF1733628D807BE5ACB83925462765D9076570056E39994FB328E3108FE406275758D6BF5F32790EF15D8416BF5548164859E785DB45E7787BB0E727ADE08641ED" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect ) # fake "reply" msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) K = 21526936926159575624241589599003964979640840086252478029709904308461709651400109485351462666820496096345766733042945918306284902585618061272525323382142547359684512114160415969631877620660064043178086464811345023251493620331559440565662862858765724251890489795332144543057725932216208403143759943169004775947331771556537814494448612329251887435553890674764339328444948425882382475260315505741818518926349729970262019325118040559191290279100613049085709127598666890434114956464502529053036826173452792849566280474995114751780998069614898221773345705289637708545219204637224261997310181473787577166103031529148842107599 # noqa H = b"D007C23686BE8A7737F828DC9E899F8EB5AF423F495F138437BE2529C1B8455F" self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_kex_group14_sha256_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGroup14SHA256(transport) kex.start_kex() self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_INIT,), transport._expect ) msg = Message() msg.add_mpint(69) msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) K = 21526936926159575624241589599003964979640840086252478029709904308461709651400109485351462666820496096345766733042945918306284902585618061272525323382142547359684512114160415969631877620660064043178086464811345023251493620331559440565662862858765724251890489795332144543057725932216208403143759943169004775947331771556537814494448612329251887435553890674764339328444948425882382475260315505741818518926349729970262019325118040559191290279100613049085709127598666890434114956464502529053036826173452792849566280474995114751780998069614898221773345705289637708545219204637224261997310181473787577166103031529148842107599 # noqa H = b"15080A19894D489ACD0DA724480E1B08E71293E07EBC25FAD10F263C00B343DC" x = b"1F0000000866616B652D6B657900000101009850B3A8DE3ECCD3F19644139137C93D9C11BC28ED8BE850908EE294E1D43B88B9295311EFAEF5B736A1B652EBE184CCF36CFB0681C1ED66430088FA448B83619F928E7B9592ED6160EC11D639D51C303603F930F743C646B1B67DA38A1D44598DCE6C3F3019422B898044141420E9A10C29B9C58668F7F20A40F154B2C4768FCF7A9AA7179FB6366A7167EE26DD58963E8B880A0572F641DE0A73DC74C930F7C3A0C9388553F3F8403E40CF8B95FEDB1D366596FCF3FDDEB21A0005ADA650EF1733628D807BE5ACB83925462765D9076570056E39994FB328E3108FE406275758D6BF5F32790EF15D8416BF5548164859E785DB45E7787BB0E727ADE08641ED0000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) def test_kex_group16_sha512_client(self): transport = FakeTransport() transport.server_mode = False kex = KexGroup16SHA512(transport) kex.start_kex() x = b"1E0000020100859FF55A23E0F66463561DD8BFC4764C69C05F85665B06EC9E29EF5003A53A8FA890B6A6EB624DEB55A4FB279DE7010A53580A126817E3D235B05A1081662B1500961D0625F0AAD287F1B597CBA9DB9550D9CC26355C4C59F92E613B5C21AC191F152C09A5DB46DCBA5EA58E3CA6A8B0EB7183E27FAC10106022E8521FA91240FB389060F1E1E4A355049D29DCC82921CE6588791743E4B1DEEE0166F7CC5180C3C75F3773342DF95C8C10AAA5D12975257027936B99B3DED6E6E98CF27EADEAEAE04E7F0A28071F578646B985FCE28A59CEB36287CB65759BE0544D4C4018CDF03C9078FE9CA79ECA611CB6966899E6FD29BE0781491C659FE2380E0D99D50D9CFAAB94E61BE311779719C4C43C6D223AD3799C3915A9E55076A21152DBBF911D6594296D6ECDC1B6FA71997CD29DF987B80FCA7F36BB7F19863C72BBBF839746AFBF9A5B407D468C976AA3E36FA118D3EAAD2E08BF6AE219F81F2CE2BE946337F06CC09BBFABE938A4087E413921CBEC1965ED905999B83396ECA226110CDF6EFB80F815F6489AF87561DA3857F13A7705921306D94176231FBB336B17C3724BC17A28BECB910093AB040873D5D760E8C182B88ECCE3E38DDA68CE35BD152DF7550BD908791FCCEDD1FFDF5ED2A57FFAE79599E487A7726D8A3D950B1729A08FBB60EE462A6BBE8BF0F5F0E1358129A37840FE5B3EEB8BF26E99FA222EAE83" # noqa self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_REPLY,), transport._expect ) # fake "reply" msg = Message() msg.add_string("fake-host-key") msg.add_mpint(69) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_REPLY, msg) K = 933242830095376162107925500057692534838883186615567574891154103836907630698358649443101764908667358576734565553213003142941996368306996312915844839972197961603283544950658467545799914435739152351344917376359963584614213874232577733869049670230112638724993540996854599166318001059065780674008011575015459772051180901213815080343343801745386220342919837913506966863570473712948197760657442974564354432738520446202131551650771882909329069340612274196233658123593466135642819578182367229641847749149740891990379052266213711500434128970973602206842980669193719602075489724202241641553472106310932258574377789863734311328542715212248147206865762697424822447603031087553480483833829498375309975229907460562402877655519980113688369262871485777790149373908739910846630414678346163764464587129010141922982925829457954376352735653834300282864445132624993186496129911208133529828461690634463092007726349795944930302881758403402084584307180896465875803621285362317770276493727205689466142632599776710824902573926951951209239626732358074877997756011804454926541386215567756538832824717436605031489511654178384081883801272314328403020205577714999460724519735573055540814037716770051316113795603990199374791348798218428912977728347485489266146775472 # noqa H = b"F6E2BCC846B9B62591EFB86663D55D4769CA06B2EDABE469DF831639B2DDD5A271985011900A724CB2C87F19F347B3632A7C1536AF3D12EE463E6EA75281AF0C" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) def test_kex_group16_sha512_server(self): transport = FakeTransport() transport.server_mode = True kex = KexGroup16SHA512(transport) kex.start_kex() self.assertEqual( (paramiko.kex_group1._MSG_KEXDH_INIT,), transport._expect ) msg = Message() msg.add_mpint(69) msg.rewind() kex.parse_next(paramiko.kex_group1._MSG_KEXDH_INIT, msg) K = 933242830095376162107925500057692534838883186615567574891154103836907630698358649443101764908667358576734565553213003142941996368306996312915844839972197961603283544950658467545799914435739152351344917376359963584614213874232577733869049670230112638724993540996854599166318001059065780674008011575015459772051180901213815080343343801745386220342919837913506966863570473712948197760657442974564354432738520446202131551650771882909329069340612274196233658123593466135642819578182367229641847749149740891990379052266213711500434128970973602206842980669193719602075489724202241641553472106310932258574377789863734311328542715212248147206865762697424822447603031087553480483833829498375309975229907460562402877655519980113688369262871485777790149373908739910846630414678346163764464587129010141922982925829457954376352735653834300282864445132624993186496129911208133529828461690634463092007726349795944930302881758403402084584307180896465875803621285362317770276493727205689466142632599776710824902573926951951209239626732358074877997756011804454926541386215567756538832824717436605031489511654178384081883801272314328403020205577714999460724519735573055540814037716770051316113795603990199374791348798218428912977728347485489266146775472 # noqa H = b"F97BB05A572A663688CA7EA1AA812D3C82EE6C8FA9D4B1D69435783D931157F199909EA38B003E4E4385C8861183CBFF0CF0EF1433A8B3C69AB4DD9420FCC85F" # noqa x = b"1F0000000866616B652D6B65790000020100859FF55A23E0F66463561DD8BFC4764C69C05F85665B06EC9E29EF5003A53A8FA890B6A6EB624DEB55A4FB279DE7010A53580A126817E3D235B05A1081662B1500961D0625F0AAD287F1B597CBA9DB9550D9CC26355C4C59F92E613B5C21AC191F152C09A5DB46DCBA5EA58E3CA6A8B0EB7183E27FAC10106022E8521FA91240FB389060F1E1E4A355049D29DCC82921CE6588791743E4B1DEEE0166F7CC5180C3C75F3773342DF95C8C10AAA5D12975257027936B99B3DED6E6E98CF27EADEAEAE04E7F0A28071F578646B985FCE28A59CEB36287CB65759BE0544D4C4018CDF03C9078FE9CA79ECA611CB6966899E6FD29BE0781491C659FE2380E0D99D50D9CFAAB94E61BE311779719C4C43C6D223AD3799C3915A9E55076A21152DBBF911D6594296D6ECDC1B6FA71997CD29DF987B80FCA7F36BB7F19863C72BBBF839746AFBF9A5B407D468C976AA3E36FA118D3EAAD2E08BF6AE219F81F2CE2BE946337F06CC09BBFABE938A4087E413921CBEC1965ED905999B83396ECA226110CDF6EFB80F815F6489AF87561DA3857F13A7705921306D94176231FBB336B17C3724BC17A28BECB910093AB040873D5D760E8C182B88ECCE3E38DDA68CE35BD152DF7550BD908791FCCEDD1FFDF5ED2A57FFAE79599E487A7726D8A3D950B1729A08FBB60EE462A6BBE8BF0F5F0E1358129A37840FE5B3EEB8BF26E99FA222EAE830000000866616B652D736967" # noqa self.assertEqual(K, transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual(x, hexlify(transport._message.asbytes()).upper()) self.assertTrue(transport._activated) @pytest.mark.skipif("not KexCurve25519.is_available()") def test_kex_c25519_client(self): K = 71294722834835117201316639182051104803802881348227506835068888449366462300724 # noqa transport = FakeTransport() transport.server_mode = False kex = KexCurve25519(transport) kex.start_kex() self.assertEqual( (paramiko.kex_curve25519._MSG_KEXECDH_REPLY,), transport._expect ) # fake reply msg = Message() msg.add_string("fake-host-key") Q_S = unhexlify( "8d13a119452382a1ada8eea4c979f3e63ad3f0c7366786d6c5b54b87219bae49" ) msg.add_string(Q_S) msg.add_string("fake-sig") msg.rewind() kex.parse_next(paramiko.kex_curve25519._MSG_KEXECDH_REPLY, msg) H = b"05B6F6437C0CF38D1A6C5A6F6E2558DEB54E7FC62447EBFB1E5D7407326A5475" self.assertEqual(K, kex.transport._K) self.assertEqual(H, hexlify(transport._H).upper()) self.assertEqual((b"fake-host-key", b"fake-sig"), transport._verify) self.assertTrue(transport._activated) @pytest.mark.skipif("not KexCurve25519.is_available()") def test_kex_c25519_server(self): K = 71294722834835117201316639182051104803802881348227506835068888449366462300724 # noqa transport = FakeTransport() transport.server_mode = True kex = KexCurve25519(transport) kex.start_kex() self.assertEqual( (paramiko.kex_curve25519._MSG_KEXECDH_INIT,), transport._expect ) # fake init msg = Message() Q_C = unhexlify( "8d13a119452382a1ada8eea4c979f3e63ad3f0c7366786d6c5b54b87219bae49" ) H = b"DF08FCFCF31560FEE639D9B6D56D760BC3455B5ADA148E4514181023E7A9B042" msg.add_string(Q_C) msg.rewind() kex.parse_next(paramiko.kex_curve25519._MSG_KEXECDH_INIT, msg) self.assertEqual(K, transport._K) self.assertTrue(transport._activated) self.assertEqual(H, hexlify(transport._H).upper())
KexTest
python
ray-project__ray
rllib/models/tf/recurrent_net.py
{ "start": 963, "end": 5139 }
class ____(TFModelV2): """Helper class to simplify implementing RNN models with TFModelV2. Instead of implementing forward(), you can implement forward_rnn() which takes batches with the time dimension added already. Here is an example implementation for a subclass ``MyRNNClass(RecurrentNetwork)``:: def __init__(self, *args, **kwargs): super(MyModelClass, self).__init__(*args, **kwargs) cell_size = 256 # Define input layers input_layer = tf.keras.layers.Input( shape=(None, obs_space.shape[0])) state_in_h = tf.keras.layers.Input(shape=(256, )) state_in_c = tf.keras.layers.Input(shape=(256, )) seq_in = tf.keras.layers.Input(shape=(), dtype=tf.int32) # Send to LSTM cell lstm_out, state_h, state_c = tf.keras.layers.LSTM( cell_size, return_sequences=True, return_state=True, name="lstm")( inputs=input_layer, mask=tf.sequence_mask(seq_in), initial_state=[state_in_h, state_in_c]) output_layer = tf.keras.layers.Dense(...)(lstm_out) # Create the RNN model self.rnn_model = tf.keras.Model( inputs=[input_layer, seq_in, state_in_h, state_in_c], outputs=[output_layer, state_h, state_c]) self.rnn_model.summary() """ @override(ModelV2) def forward( self, input_dict: Dict[str, TensorType], state: List[TensorType], seq_lens: TensorType, ) -> Tuple[TensorType, List[TensorType]]: """Adds time dimension to batch before sending inputs to forward_rnn(). You should implement forward_rnn() in your subclass.""" # Creating a __init__ function that acts as a passthrough and adding the warning # there led to errors probably due to the multiple inheritance. We encountered # the same error if we add the Deprecated decorator. We therefore add the # deprecation warning here. if log_once("recurrent_network_tf"): deprecation_warning( old="ray.rllib.models.tf.recurrent_net.RecurrentNetwork" ) assert seq_lens is not None flat_inputs = input_dict["obs_flat"] inputs = add_time_dimension( padded_inputs=flat_inputs, seq_lens=seq_lens, framework="tf" ) output, new_state = self.forward_rnn( inputs, state, seq_lens, ) return tf.reshape(output, [-1, self.num_outputs]), new_state def forward_rnn( self, inputs: TensorType, state: List[TensorType], seq_lens: TensorType ) -> Tuple[TensorType, List[TensorType]]: """Call the model with the given input tensors and state. Args: inputs: observation tensor with shape [B, T, obs_size]. state: list of state tensors, each with shape [B, T, size]. seq_lens: 1d tensor holding input sequence lengths. Returns: (outputs, new_state): The model output tensor of shape [B, T, num_outputs] and the list of new state tensors each with shape [B, size]. Sample implementation for the ``MyRNNClass`` example:: def forward_rnn(self, inputs, state, seq_lens): model_out, h, c = self.rnn_model([inputs, seq_lens] + state) return model_out, [h, c] """ raise NotImplementedError("You must implement this for a RNN model") def get_initial_state(self) -> List[TensorType]: """Get the initial recurrent state values for the model. Returns: list of np.array objects, if any Sample implementation for the ``MyRNNClass`` example:: def get_initial_state(self): return [ np.zeros(self.cell_size, np.float32), np.zeros(self.cell_size, np.float32), ] """ raise NotImplementedError("You must implement this for a RNN model") @OldAPIStack
RecurrentNetwork
python
tiangolo__fastapi
docs_src/dependencies/tutorial002_an.py
{ "start": 207, "end": 706 }
class ____: def __init__(self, q: Union[str, None] = None, skip: int = 0, limit: int = 100): self.q = q self.skip = skip self.limit = limit @app.get("/items/") async def read_items(commons: Annotated[CommonQueryParams, Depends(CommonQueryParams)]): response = {} if commons.q: response.update({"q": commons.q}) items = fake_items_db[commons.skip : commons.skip + commons.limit] response.update({"items": items}) return response
CommonQueryParams
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/auto_materialize_rule.py
{ "start": 1277, "end": 11763 }
class ____(ABC): """An AutoMaterializeRule defines a bit of logic which helps determine if a materialization should be kicked off for a given asset partition. Each rule can have one of two decision types, `MATERIALIZE` (indicating that an asset partition should be materialized) or `SKIP` (indicating that the asset partition should not be materialized). Materialize rules are evaluated first, and skip rules operate over the set of candidates that are produced by the materialize rules. Other than that, there is no ordering between rules. """ @property @abstractmethod def decision_type(self) -> "AutoMaterializeDecisionType": """The decision type of the rule (either `MATERIALIZE` or `SKIP`).""" ... @property @abstractmethod def description(self) -> str: """A human-readable description of this rule. As a basic guideline, this string should complete the sentence: 'Indicates an asset should be (materialize/skipped) when ____'. """ ... def to_asset_condition(self) -> "RuleCondition": """Converts this AutoMaterializeRule into an AssetCondition.""" from dagster._core.definitions.declarative_automation.legacy.rule_condition import ( RuleCondition, ) return RuleCondition(rule=self) @abstractmethod def evaluate_for_asset(self, context: "AutomationContext") -> "AutomationResult": """The core evaluation function for the rule. This function takes in a context object and returns a mapping from evaluated rules to the set of asset partitions that the rule applies to. """ ... @public @staticmethod def materialize_on_required_for_freshness() -> "MaterializeOnRequiredForFreshnessRule": """(Deprecated) Materialize an asset partition if it is required to satisfy a freshness policy of this asset or one of its downstream assets. Note: This rule has no effect on partitioned assets. """ from dagster._core.definitions.auto_materialize_rule_impls import ( MaterializeOnRequiredForFreshnessRule, ) return MaterializeOnRequiredForFreshnessRule() @public @staticmethod def materialize_on_cron( cron_schedule: str, timezone: str = "UTC", all_partitions: bool = False ) -> "MaterializeOnCronRule": """Materialize an asset partition if it has not been materialized since the latest cron schedule tick. For assets with a time component to their partitions_def, this rule will request all partitions that have been missed since the previous tick. Args: cron_schedule (str): A cron schedule string (e.g. "`0 * * * *`") indicating the ticks for which this rule should fire. timezone (str): The timezone in which this cron schedule should be evaluated. Defaults to "UTC". all_partitions (bool): If True, this rule fires for all partitions of this asset on each cron tick. If False, this rule fires only for the last partition of this asset. Defaults to False. """ check.param_invariant( is_valid_cron_string(cron_schedule), "cron_schedule", "must be a valid cron string" ) check.param_invariant( timezone in pytz.all_timezones_set, "timezone", "must be a valid timezone" ) from dagster._core.definitions.auto_materialize_rule_impls import MaterializeOnCronRule return MaterializeOnCronRule( cron_schedule=cron_schedule, timezone=timezone, all_partitions=all_partitions ) @public @staticmethod def materialize_on_parent_updated( updated_parent_filter: Optional["AutoMaterializeAssetPartitionsFilter"] = None, ) -> "MaterializeOnParentUpdatedRule": """Materialize an asset partition if one of its parents has been updated more recently than it has. Note: For time-partitioned or dynamic-partitioned assets downstream of an unpartitioned asset, this rule will only fire for the most recent partition of the downstream. Args: updated_parent_filter (Optional[AutoMaterializeAssetPartitionsFilter]): Filter to apply to updated parents. If a parent was updated but does not pass the filter criteria, then it won't count as updated for the sake of this rule. """ from dagster._core.definitions.auto_materialize_rule_impls import ( MaterializeOnParentUpdatedRule, ) return MaterializeOnParentUpdatedRule(updated_parent_filter=updated_parent_filter) @public @staticmethod def materialize_on_missing() -> "MaterializeOnMissingRule": """Materialize an asset partition if it has never been materialized before. This rule will not fire for non-root assets unless that asset's parents have been updated. """ from dagster._core.definitions.auto_materialize_rule_impls import MaterializeOnMissingRule return MaterializeOnMissingRule() @public @staticmethod def skip_on_parent_missing() -> "SkipOnParentMissingRule": """Skip materializing an asset partition if one of its parent asset partitions has never been materialized (for regular assets) or observed (for observable source assets). """ from dagster._core.definitions.auto_materialize_rule_impls import SkipOnParentMissingRule return SkipOnParentMissingRule() @public @staticmethod def skip_on_parent_outdated() -> "SkipOnParentOutdatedRule": """Skip materializing an asset partition if any of its parents has not incorporated the latest data from its ancestors. """ from dagster._core.definitions.auto_materialize_rule_impls import SkipOnParentOutdatedRule return SkipOnParentOutdatedRule() @public @staticmethod def skip_on_not_all_parents_updated( require_update_for_all_parent_partitions: bool = False, ) -> "SkipOnNotAllParentsUpdatedRule": """Skip materializing an asset partition if any of its parents have not been updated since the asset's last materialization. Args: require_update_for_all_parent_partitions (Optional[bool]): Applies only to an unpartitioned asset or an asset partition that depends on more than one partition in any upstream asset. If true, requires all upstream partitions in each upstream asset to be materialized since the downstream asset's last materialization in order to update it. If false, requires at least one upstream partition in each upstream asset to be materialized since the downstream asset's last materialization in order to update it. Defaults to false. """ from dagster._core.definitions.auto_materialize_rule_impls import ( SkipOnNotAllParentsUpdatedRule, ) return SkipOnNotAllParentsUpdatedRule(require_update_for_all_parent_partitions) @staticmethod def skip_on_not_all_parents_updated_since_cron( cron_schedule: str, timezone: str = "UTC" ) -> "SkipOnNotAllParentsUpdatedSinceCronRule": """Skip materializing an asset partition if any of its parents have not been updated since the latest tick of the given cron schedule. Args: cron_schedule (str): A cron schedule string (e.g. "`0 * * * *`"). timezone (str): The timezone in which this cron schedule should be evaluated. Defaults to "UTC". """ from dagster._core.definitions.auto_materialize_rule_impls import ( SkipOnNotAllParentsUpdatedSinceCronRule, ) return SkipOnNotAllParentsUpdatedSinceCronRule( cron_schedule=cron_schedule, timezone=timezone ) @public @staticmethod def skip_on_required_but_nonexistent_parents() -> "SkipOnRequiredButNonexistentParentsRule": """Skip an asset partition if it depends on parent partitions that do not exist. For example, imagine a downstream asset is time-partitioned, starting in 2022, but has a time-partitioned parent which starts in 2023. This rule will skip attempting to materialize downstream partitions from before 2023, since the parent partitions do not exist. """ from dagster._core.definitions.auto_materialize_rule_impls import ( SkipOnRequiredButNonexistentParentsRule, ) return SkipOnRequiredButNonexistentParentsRule() @public @staticmethod def skip_on_backfill_in_progress( all_partitions: bool = False, ) -> "SkipOnBackfillInProgressRule": """Skip an asset's partitions if targeted by an in-progress backfill. Args: all_partitions (bool): If True, skips all partitions of the asset being backfilled, regardless of whether the specific partition is targeted by a backfill. If False, skips only partitions targeted by a backfill. Defaults to False. """ from dagster._core.definitions.auto_materialize_rule_impls import ( SkipOnBackfillInProgressRule, ) return SkipOnBackfillInProgressRule(all_partitions) @staticmethod def skip_on_run_in_progress() -> "SkipOnRunInProgressRule": from dagster._core.definitions.auto_materialize_rule_impls import SkipOnRunInProgressRule return SkipOnRunInProgressRule() def to_snapshot(self) -> "AutoMaterializeRuleSnapshot": """Returns a serializable snapshot of this rule for historical evaluations.""" from dagster._core.definitions.auto_materialize_rule_evaluation import ( AutoMaterializeRuleSnapshot, ) return AutoMaterializeRuleSnapshot( class_name=self.__class__.__name__, description=self.description, decision_type=self.decision_type, ) def __eq__(self, other) -> bool: # override the default NamedTuple __eq__ method to factor in types return type(self) == type(other) and super().__eq__(other) def __hash__(self) -> int: # override the default NamedTuple __hash__ method to factor in types return hash(hash(type(self).__name__) + super().__hash__())
AutoMaterializeRule
python
tensorflow__tensorflow
tensorflow/python/framework/file_system_test.py
{ "start": 1100, "end": 1820 }
class ____(test.TestCase): def setUp(self): file_system_library = resource_loader.get_path_to_datafile( "test_file_system.so") load_library.load_file_system_library(file_system_library) @test_util.run_deprecated_v1 def testBasic(self): with self.cached_session() as sess: reader = io_ops.WholeFileReader("test_reader") queue = data_flow_ops.FIFOQueue(99, [dtypes.string], shapes=()) queue.enqueue_many([["test://foo"]]).run() queue.close().run() key, value = self.evaluate(reader.read(queue)) self.assertEqual(key, compat.as_bytes("test://foo")) self.assertEqual(value, compat.as_bytes("AAAAAAAAAA")) if __name__ == "__main__": test.main()
FileSystemTest
python
getsentry__sentry
src/sentry/api/endpoints/organization_stats_summary.py
{ "start": 4817, "end": 4968 }
class ____(TypedDict): # this response is pretty dynamic, leaving generic id: str slug: str stats: list[dict[str, Any]]
_ProjectSummaryStats
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 26735, "end": 28604 }
class ____(QuantizedLayer): def __init__( self, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): super().__init__( nbits=nbits, axis_key=axis_key, axis_value=axis_value, q_group_size=q_group_size, residual_length=residual_length, ) if not is_hqq_available(): raise ImportError("You need to install `hqq` to use `HQQQuantizedLayer`") if self.nbits not in [1, 2, 3, 4, 8]: raise ValueError( f"`nbits` for `HQQ` backend has to be one of [`1`, `2`, `3`, `4`, `8`] but got {self.nbits}" ) if self.axis_key not in [0, 1]: raise ValueError(f"`axis_key` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_key}") if self.axis_value not in [0, 1]: raise ValueError(f"`axis_value` for `HQQ` backend has to be one of [`0`, `1`] but got {self.axis_value}") self.quantizer = HQQQuantizer def _quantize(self, tensor, axis): qtensor, meta = self.quantizer.quantize( tensor, axis=axis, device=self.keys.device, compute_dtype=self.keys.dtype, nbits=self.nbits, group_size=self.q_group_size, ) meta["compute_dtype"] = self.keys.dtype self.quantizer.cuda(qtensor, meta=meta, device=self.keys.device) # Move to device and cast to dtype meta["scale"] = meta["scale"].to(qtensor.device) meta["zero"] = meta["zero"].to(qtensor.device) return qtensor, meta def _dequantize(self, qtensor): quant_tensor, meta = qtensor tensor = self.quantizer.dequantize(quant_tensor, meta) return tensor
HQQQuantizedLayer
python
aimacode__aima-python
learning.py
{ "start": 13137, "end": 14488 }
class ____: """ A fork of a decision tree holds an attribute to test, and a dict of branches, one for each of the attribute's values. """ def __init__(self, attr, attr_name=None, default_child=None, branches=None): """Initialize by saying what attribute this node tests.""" self.attr = attr self.attr_name = attr_name or attr self.default_child = default_child self.branches = branches or {} def __call__(self, example): """Given an example, classify it using the attribute and the branches.""" attr_val = example[self.attr] if attr_val in self.branches: return self.branches[attr_val](example) else: # return default class when attribute is unknown return self.default_child(example) def add(self, val, subtree): """Add a branch. If self.attr = val, go to the given subtree.""" self.branches[val] = subtree def display(self, indent=0): name = self.attr_name print('Test', name) for (val, subtree) in self.branches.items(): print(' ' * 4 * indent, name, '=', val, '==>', end=' ') subtree.display(indent + 1) def __repr__(self): return 'DecisionFork({0!r}, {1!r}, {2!r})'.format(self.attr, self.attr_name, self.branches)
DecisionFork
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-objectbox/llama_index/vector_stores/objectbox/base.py
{ "start": 887, "end": 9085 }
class ____(BasePydanticVectorStore): """ ObjectBox vector store. In this vector store, embeddings are stored within a ObjectBox `Box` (collection). During query time, the index uses ObjectBox to query for the top-K most similar nodes. Args: embedding_dimensions (int): Number of elements in the embedding to be stored distance_type (objectbox.model.properties.VectorDistanceType): Distance metric to be used for vector search db_directory (str): File path where ObjectBox database files will be stored clear_db (bool): Whether to delete any existing database on `db_directory` do_log (bool): enable/disable logging Examples: `pip install llama-index-vector-stores-objectbox` ```python from llama_index.vector_stores.objectbox import ObjectBoxVectorStore from objectbox import VectorDistanceType vector_store = ObjectBoxVectorStore( embedding_dim, distance_type=VectorDistanceType.COSINE, db_directory="obx_data", clear_db=False, do_log=True ) ``` """ stores_text: bool = True embedding_dimensions: int distance_type: VectorDistanceType = VectorDistanceType.EUCLIDEAN db_directory: Optional[str] = None clear_db: Optional[bool] = False do_log: Optional[bool] = False _store: Store = PrivateAttr() _entity_class: Entity = PrivateAttr() _box: Box = PrivateAttr() def __init__( self, embedding_dimensions: int, distance_type: VectorDistanceType = VectorDistanceType.EUCLIDEAN, db_directory: Optional[str] = None, clear_db: Optional[bool] = False, do_log: Optional[bool] = False, **data: Any, ): super().__init__( embedding_dimensions=embedding_dimensions, distance_type=distance_type, db_directory=db_directory, clear_db=clear_db, do_log=do_log, **data, ) self._entity_class = self._create_entity_class() self._store = self._create_box_store() self._box = self._store.box(self._entity_class) @property def client(self) -> Any: return self._box def add(self, nodes: List[BaseNode], **kwargs: Any) -> List[str]: ids: list[str] = [] start = time.perf_counter() with self._store.write_tx(): for node in nodes: if node.embedding is None: _logger.info("A node with no embedding was found ") continue self._box.put( self._entity_class( node_id=node.node_id, doc_id=node.ref_doc_id if node.ref_doc_id is not None else "", text=node.get_content(metadata_mode=MetadataMode.NONE), metadata=node.metadata, embeddings=node.embedding, ) ) ids.append(node.node_id) if self.do_log: end = time.perf_counter() _logger.info( f"ObjectBox stored {len(ids)} nodes in {end - start} seconds" ) return ids def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None: self._box.query(self._entity_class.doc_id.equals(ref_doc_id)).build().remove() def delete_nodes( self, node_ids: Optional[List[str]] = None, filters: Optional[MetadataFilters] = None, **delete_kwargs: Any, ) -> None: if filters is not None: raise NotImplementedError( "ObjectBox does not yet support delete_nodes() with metadata filters - contact us if you need this feature" ) if node_ids is not None: query_obj = self._box.query( self._entity_class.node_id.equals("node_id").alias("node_id") ).build() for node_id in node_ids: query_obj.set_parameter_alias_string("node_id", node_id) query_obj.remove() def get_nodes( self, node_ids: Optional[List[str]] = None, filters: Optional[MetadataFilters] = None, ) -> List[BaseNode]: if filters is not None: raise NotImplementedError( "ObjectBox does not yet support get_nodes() with metadata filters - contact us if you need this feature" ) if node_ids is not None: retrieved_nodes: list[BaseNode] = [] with self._store.read_tx(): query_obj = self._box.query( self._entity_class.node_id.equals("node_id").alias("node_id") ).build() for node_id in node_ids: try: query_obj.set_parameter_alias_string("node_id", node_id) entities = query_obj.find() if len(entities) == 0: _logger.info(f"No entity with id = {node_id} was found") continue retrieved_nodes.append( TextNode( text=entities[0].text, id_=entities[0].node_id, metadata=entities[0].metadata, ) ) except ValueError: raise ValueError(f"Invalid node id: {node_id}") return retrieved_nodes else: raise ValueError("node_ids cannot be None") def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult: if query.filters is not None: raise NotImplementedError( "ObjectBox does not yet support query() with metadata filters - contact us if you need this feature" ) query_embedding = query.query_embedding n_results = query.similarity_top_k nodes: list[TextNode] = [] similarities: list[float] = [] ids: list[str] = [] start = time.perf_counter() query: Query = self._box.query( self._entity_class.embeddings.nearest_neighbor(query_embedding, n_results) ).build() results: list[tuple[Entity, float]] = query.find_with_scores() end = time.perf_counter() if self.do_log: _logger.info( f"ObjectBox retrieved {len(results)} vectors in {end - start} seconds" ) for entity, score in results: node = TextNode( text=entity.text, id_=entity.node_id, metadata=entity.metadata ) ids.append(entity.node_id) nodes.append(node) similarities.append(score) return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids) def count(self) -> int: return self._box.count() def clear(self) -> None: self._box.remove_all() def close(self): self._store.close() def _create_entity_class(self) -> Entity: """Dynamically define an Entity class according to the parameters.""" @Entity() class VectorEntity: id = Id() node_id = String() doc_id = String() text = String() metadata = Property(dict, type=PropertyType.flex) embeddings = Float32Vector( index=HnswIndex( dimensions=self.embedding_dimensions, distance_type=self.distance_type, ) ) return VectorEntity def _create_box_store(self) -> Store: """Registering the VectorEntity model and setting up objectbox database.""" db_path = DIRECTORY if self.db_directory is None else self.db_directory if self.clear_db and os.path.exists(db_path): shutil.rmtree(db_path) model = Model() model.entity(self._entity_class) return Store(model=model, directory=db_path)
ObjectBoxVectorStore
python
airbytehq__airbyte
airbyte-integrations/connectors/source-linnworks/source_linnworks/streams.py
{ "start": 2355, "end": 2909 }
class ____(LinnworksStream): # https://apps.linnworks.net/Api/Method/Inventory-GetStockLocations # Response: List<StockLocation> https://apps.linnworks.net/Api/Class/linnworks-spa-commondata-Inventory-ClassBase-StockLocation # Allows 150 calls per minute primary_key = "StockLocationIntId" use_cache = True def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return "/api/Inventory/GetStockLocations"
StockLocations
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_stackdriver.py
{ "start": 3132, "end": 4187 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook") def test_execute(self, mock_hook): operator = StackdriverListAlertPoliciesOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER) mock_hook.return_value.list_alert_policies.return_value = [AlertPolicy(name="test-name")] result = operator.execute(context=mock.MagicMock()) mock_hook.return_value.list_alert_policies.assert_called_once_with( project_id=None, filter_=TEST_FILTER, format_=None, order_by=None, page_size=None, retry=DEFAULT, timeout=None, metadata=(), ) assert result == [ { "combiner": 0, "conditions": [], "display_name": "", "name": "test-name", "notification_channels": [], "severity": 0, "user_labels": {}, } ]
TestStackdriverListAlertPoliciesOperator
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/settings.py
{ "start": 12193, "end": 13383 }
class ____(ParameterRandomizationSettings): min_value: float = attr.ib() max_value: float = 1.0 def __str__(self) -> str: """ Helper method to output sampler stats to console. """ return f"Uniform sampler: min={self.min_value}, max={self.max_value}" @min_value.default def _min_value_default(self): return 0.0 @min_value.validator def _check_min_value(self, attribute, value): if self.min_value > self.max_value: raise TrainerConfigError( "Minimum value is greater than maximum value in uniform sampler." ) def apply(self, key: str, env_channel: EnvironmentParametersChannel) -> None: """ Helper method to send sampler settings over EnvironmentParametersChannel Calls the uniform sampler type set method. :param key: environment parameter to be sampled :param env_channel: The EnvironmentParametersChannel to communicate sampler settings to environment """ env_channel.set_uniform_sampler_parameters( key, self.min_value, self.max_value, self.seed ) @attr.s(auto_attribs=True)
UniformSettings
python
rapidsai__cudf
python/cudf/cudf/core/buffer/spill_manager.py
{ "start": 6059, "end": 16227 }
class ____: """Manager of spillable buffers. This class implements tracking of all known spillable buffers, on-demand spilling of said buffers, and (optionally) maintains a memory usage limit. When `device_memory_limit=<limit-in-bytes>`, the manager will try keep the device memory usage below the specified limit by spilling of spillable buffers continuously, which will introduce a modest overhead. Notice, this is a soft limit. The memory usage might exceed the limit if too many buffers are unspillable. Parameters ---------- device_memory_limit: int, optional If not None, this is the device memory limit in bytes that triggers device to host spilling. The global manager sets this to the value of `CUDF_SPILL_DEVICE_LIMIT` or None. statistic_level: int, optional If not 0, enables statistics at the specified level. See SpillStatistics for the different levels. """ _buffers: weakref.WeakValueDictionary[int, SpillableBufferOwner] statistics: SpillStatistics def __init__( self, *, device_memory_limit: int | None = None, statistic_level: int = 0, ) -> None: self._lock = threading.Lock() self._buffers = weakref.WeakValueDictionary() self._id_counter = 0 self._device_memory_limit = device_memory_limit self.statistics = SpillStatistics(statistic_level) def _out_of_memory_handle(self, nbytes: int, *, retry_once=True) -> bool: """Try to handle an out-of-memory error by spilling This can by used as the callback function to RMM's `FailureCallbackResourceAdaptor` Parameters ---------- nbytes : int Number of bytes to try to spill. retry_once : bool, optional If True, call `gc.collect()` and retry once. Return ------ bool True if any buffers were freed otherwise False. Warning ------- In order to avoid deadlock, this function should not lock already locked buffers. """ # Let's try to spill device memory spilled = self.spill_device_memory(nbytes=nbytes) if spilled > 0: return True # Ask RMM to retry the allocation if retry_once: # Let's collect garbage and try one more time gc.collect() return self._out_of_memory_handle(nbytes, retry_once=False) # TODO: write to log instead of stdout print( # noqa: T201 f"[WARNING] RMM allocation of {format_bytes(nbytes)} bytes " "failed, spill-on-demand couldn't find any device memory to " f"spill:\n{self!r}\ntraceback:\n{get_traceback()}\n" f"{self.statistics}" ) return False # Since we didn't find anything to spill, we give up def add(self, buffer: SpillableBufferOwner) -> None: """Add buffer to the set of managed buffers The manager keeps a weak reference to the buffer Parameters ---------- buffer : SpillableBufferOwner The buffer to manage """ if buffer.size > 0 and not buffer.exposed: with self._lock: self._buffers[self._id_counter] = buffer self._id_counter += 1 self.spill_to_device_limit() def buffers( self, order_by_access_time: bool = False ) -> tuple[SpillableBufferOwner, ...]: """Get all managed buffers Parameters ---------- order_by_access_time : bool, optional Order the buffer by access time (ascending order) Return ------ tuple Tuple of buffers """ with self._lock: ret = tuple(self._buffers.values()) if order_by_access_time: ret = tuple(sorted(ret, key=lambda b: b.last_accessed)) return ret @_spill_cudf_nvtx_annotate def spill_device_memory(self, nbytes: int) -> int: """Try to spill device memory This function is safe to call doing spill-on-demand since it does not lock buffers already locked. Parameters ---------- nbytes : int Number of bytes to try to spill Return ------ int Number of actually bytes spilled. """ spilled = 0 for buf in self.buffers(order_by_access_time=True): if buf.lock.acquire(blocking=False): try: if not buf.is_spilled and buf.spillable: buf.spill(target="cpu") spilled += buf.size if spilled >= nbytes: break finally: buf.lock.release() return spilled def spill_to_device_limit(self, device_limit: int | None = None) -> int: """Try to spill device memory until device limit Notice, by default this is a no-op. Parameters ---------- device_limit : int, optional Limit in bytes. If None, the value of the environment variable `CUDF_SPILL_DEVICE_LIMIT` is used. If this is not set, the method does nothing and returns 0. Return ------ int The number of bytes spilled. """ limit = ( self._device_memory_limit if device_limit is None else device_limit ) if limit is None: return 0 unspilled = sum( buf.size for buf in self.buffers() if not buf.is_spilled ) return self.spill_device_memory(nbytes=unspilled - limit) def __repr__(self) -> str: spilled = sum(buf.size for buf in self.buffers() if buf.is_spilled) unspilled = sum( buf.size for buf in self.buffers() if not buf.is_spilled ) unspillable = 0 for buf in self.buffers(): if not (buf.is_spilled or buf.spillable): unspillable += buf.size unspillable_ratio = unspillable / unspilled if unspilled else 0 dev_limit = "N/A" if self._device_memory_limit is not None: dev_limit = format_bytes(self._device_memory_limit) return ( f"<SpillManager device_memory_limit={dev_limit} | " f"{format_bytes(spilled)} spilled | " f"{format_bytes(unspilled)} ({unspillable_ratio:.0%}) " f"unspilled (unspillable)>" ) # The global manager has three states: # - Uninitialized # - Initialized to None (spilling disabled) # - Initialized to a SpillManager instance (spilling enabled) _global_manager_uninitialized: bool = True _global_manager: SpillManager | None = None def set_global_manager(manager: SpillManager | None) -> None: """Set the global manager, which if None disables spilling""" global _global_manager, _global_manager_uninitialized if _global_manager is not None: gc.collect() buffers = _global_manager.buffers() if len(buffers) > 0: warnings.warn(f"overwriting non-empty manager: {buffers}") _global_manager = manager _global_manager_uninitialized = False def get_global_manager() -> SpillManager | None: """Get the global manager or None if spilling is disabled""" global _global_manager_uninitialized if _global_manager_uninitialized: if get_option("spill"): manager = SpillManager( device_memory_limit=get_option("spill_device_limit"), statistic_level=get_option("spill_stats"), ) set_global_manager(manager) if get_option("spill_on_demand"): set_spill_on_demand_globally() else: set_global_manager(None) return _global_manager def set_spill_on_demand_globally() -> None: """Enable spill on demand in the current global spill manager. Warning: this modifies the current RMM memory resource. A memory resource to handle out-of-memory errors is pushed onto the RMM memory resource stack. Raises ------ ValueError If no global spill manager exists (spilling is disabled). ValueError If a failure callback resource is already in the resource stack. """ manager = get_global_manager() if manager is None: raise ValueError( "Cannot enable spill on demand with no global spill manager" ) mr = rmm.mr.get_current_device_resource() if any( isinstance(m, rmm.mr.FailureCallbackResourceAdaptor) for m in get_rmm_memory_resource_stack(mr) ): raise ValueError( "Spill on demand (or another failure callback resource) " "is already registered" ) rmm.mr.set_current_device_resource( rmm.mr.FailureCallbackResourceAdaptor( mr, manager._out_of_memory_handle ) ) @contextmanager def spill_on_demand_globally(): """Context to enable spill on demand temporarily. Warning: this modifies the current RMM memory resource. A memory resource to handle out-of-memory errors is pushed onto the RMM memory resource stack when entering the context and popped again when exiting. Raises ------ ValueError If no global spill manager exists (spilling is disabled). ValueError If a failure callback resource is already in the resource stack. ValueError If the RMM memory source stack was changed while in the context. """ set_spill_on_demand_globally() # Save the new memory resource stack for later cleanup mr_stack = get_rmm_memory_resource_stack( rmm.mr.get_current_device_resource() ) try: yield finally: mr = rmm.mr.get_current_device_resource() if mr_stack != get_rmm_memory_resource_stack(mr): raise ValueError( "RMM memory source stack was changed while in the context" ) rmm.mr.set_current_device_resource(mr_stack[1])
SpillManager
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/storage.py
{ "start": 69, "end": 242 }
class ____(BuildMediaFileSystemStorage): internal_redirect_root_path = "proxito" def exists(self, *args, **kargs): return True
BuildMediaFileSystemStorageTest
python
mlflow__mlflow
dev/clint/src/clint/rules/temp_dir_in_test.py
{ "start": 84, "end": 560 }
class ____(Rule): def _message(self) -> str: return "Do not use `tempfile.TemporaryDirectory` in test directly. Use `tmp_path` fixture (https://docs.pytest.org/en/stable/reference/reference.html#tmp-path)." @staticmethod def check(node: ast.Call, resolver: Resolver) -> bool: """ Returns True if the call is to tempfile.TemporaryDirectory(). """ return resolver.resolve(node) == ["tempfile", "TemporaryDirectory"]
TempDirInTest
python
django__django
tests/admin_changelist/admin.py
{ "start": 4882, "end": 5134 }
class ____(admin.ModelAdmin): search_fields = ("name",) def get_search_fields(self, request): search_fields = super().get_search_fields(request) search_fields += ("age",) return search_fields
DynamicSearchFieldsChildAdmin
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_tensor.py
{ "start": 113104, "end": 126878 }
class ____: """Encoding of a static type for a `RaggedTensor`. Use this type to express/declare that an output must have the type of `RaggedTensor`. """ def __init__(self, dtype, ragged_rank, row_splits_dtype=dtypes.int64): """Initializes a RaggedTensorType object. Args: dtype: data type of the `RaggedTensor`'s inner values. ragged_rank: ragged_rank of the declared `RaggedTensor`. row_splits_dtype: data type for the `RaggedTensor`'s row splits. One of: `tf.int32` or `tf.int64`. """ row_splits_dtype = dtypes.as_dtype(row_splits_dtype) self._dtype = dtype self._ragged_rank = ragged_rank self._row_splits_dtype = row_splits_dtype dtype = property(lambda self: self._dtype) ragged_rank = property(lambda self: self._ragged_rank) row_splits_dtype = property(lambda self: self._row_splits_dtype) def __repr__(self): return "RaggedTensorType(%r, %r, %r)" % (self.dtype, self.ragged_rank, self.row_splits_dtype) # =============================================================================== # Helper Functions # =============================================================================== def _assert_sparse_indices_are_ragged_right(indices): """Checks that the given SparseTensor.indices tensor is ragged-right. Example: `indices = [[0, 0], [0, 1], [2, 0], [3, 1]]` is not ragged right because the entry `[3, 1]` skips a cell. Args: indices: The SparseTensor indices to check. Returns: A list of control dependency op tensors. """ index_prefix = indices[:, :-1] index_suffix = indices[:, -1] # Check whether each index is starting a new row in the innermost dimension # (prefix[i] != prefix[i-1]) or continuing a row (prefix[i] == prefix[i-1]). # (Note: this skips the first index; we will check that separately below.) index_prefix_changed = math_ops.reduce_any( math_ops.not_equal(index_prefix[1:], index_prefix[:-1]), axis=1) # Check two cases: # * For indices that start a new row: index_suffix[i] must be zero. # * For indices that continue a row: index_suffix[i] must be equal to # index_suffix[i-1]+1. index_ok = array_ops.where( index_prefix_changed, math_ops.equal(index_suffix[1:], 0), math_ops.equal(index_suffix[1:], index_suffix[:-1] + 1)) # Also check that the very first index didn't skip any cells. The first # index starts a new row (by definition), so its suffix should be zero. sparse_indices_are_ragged_right = math_ops.logical_and( math_ops.reduce_all(math_ops.equal(index_suffix[:1], 0)), math_ops.reduce_all(index_ok)) message = [ "SparseTensor is not right-ragged", "SparseTensor.indices =", indices ] return [control_flow_assert.Assert(sparse_indices_are_ragged_right, message)] @ops.RegisterGradient("RaggedTensorToSparse") def _ragged_tensor_to_sparse_gradient(op, unused_sparse_indices_grad, sparse_values_grad, unused_sparse_shape_grad): """Gradient for RaggedTensorToSparse.""" op_inputs_nested_row_splits = op.inputs[:-1] op_inputs_flat_values = op.inputs[-1] # No gradient for the RaggedTensor's nested_row_splits. nested_row_splits_gradient = [None] * len(op_inputs_nested_row_splits) # Gradient for the RaggedTensor's flat_values is formed by reshaping # the gradient for the SparseTensor's values. flat_values_shape = array_ops.shape(op_inputs_flat_values) flat_values_gradient = array_ops.reshape(sparse_values_grad, flat_values_shape) return nested_row_splits_gradient + [flat_values_gradient] def _assert_monotonic_increasing(tensor, message=None): return check_ops.assert_non_negative( tensor[1:] - tensor[:-1], message=message) def _assert_zero(tensor, message=None): return check_ops.assert_equal( tensor, constant_op.constant(0, dtype=tensor.dtype), message=message) def _nrows(tensor, out_type=dtypes.int32): if isinstance(tensor, RaggedTensor): return tensor.nrows(out_type=out_type) else: return array_ops.shape(tensor, out_type=out_type)[0] def merge_dims(value, outer_axis, inner_axis): """Merges value[outer_axis...inner_axis] into a single dimension. See `RaggedTensor.merge_dims()` for more details. This helper differs from `RaggedTensor.merge_dims()` in that `value` may be a dense or ragged tensor. Args: value: A `RaggedTensor` or `Tensor` outer_axis: `int` inner_axis: `int` Returns: A flattened `RaggedTensor` or `Tensor`. """ if outer_axis == inner_axis: return value # Flatten outer dimensions of a RaggedTensor by just taking its values. while outer_axis == 0 and isinstance(value, RaggedTensor): value = value.values inner_axis -= 1 if inner_axis == 0: return value # Flatten non-Ragged tensors using tf.reshape(). if not isinstance(value, RaggedTensor): if value.shape.is_fully_defined(): old_shape = value.shape.as_list() new_shape = old_shape[:outer_axis] + [-1] + old_shape[inner_axis + 1:] else: old_shape = array_ops.shape(value) new_shape = array_ops.concat( [old_shape[:outer_axis], [-1], old_shape[inner_axis + 1:]], axis=0) return array_ops.reshape(value, new_shape) # Handle outer_axis>1 via recursion. if outer_axis > 1: return value.with_values( merge_dims(value.values, outer_axis - 1, inner_axis - 1)) # At this point, we know outer_axis == 1, and value is a RaggedTensor. # So we need to flatten the values and build a corresponding splits tensor. new_values = value.values new_splits = value.row_splits for axis in range(outer_axis, inner_axis): if isinstance(new_values, RaggedTensor): # Flatten a single ragged dimension. new_splits = array_ops.gather(new_values.row_splits, new_splits) new_values = new_values.values else: # Flatten all remaining dense dimensions. shape_split = inner_axis - axis + 1 if new_values.shape.is_fully_defined(): old_shape = new_values.shape.as_list() new_shape = [-1] + old_shape[shape_split:] flat_size = _prod(old_shape[1:shape_split]) else: old_shape = array_ops.shape(new_values) new_shape = array_ops.concat([[-1], old_shape[shape_split:]], axis=0) flat_size = math_ops.cast( math_ops.reduce_prod(old_shape[1:shape_split]), new_splits.dtype) new_values = array_ops.reshape(new_values, new_shape) new_splits = new_splits * flat_size break return RaggedTensor.from_row_splits(new_values, new_splits) def _prod(lst): """Returns the product of the numbers in a list.""" return functools.reduce(operator.mul, lst, 1) def _get_row_partition_type_tensor_pairs_tail(partition): """Gets a row partition type tensor pair for the tail. If value_rowid is defined, then it is used. Otherwise, row_splits are used. Args: partition: a RowPartition. Returns: A list of (row_partition_type, row_partition_tensor) pairs. """ if partition._has_precomputed_value_rowids(): # pylint: disable=protected-access return ("VALUE_ROWIDS", partition.value_rowids()) else: return ("ROW_SPLITS", partition.row_splits()) def _get_row_partition_type_tensor_pairs(rt_input): """Gets a list of the row partitions for rt_input. If value_rowids are defined, then they are used. Otherwise, row_splits are used. If the outermost level has value_rowids defined, then nrows is also added. Args: rt_input: a ragged tensor. Returns: A list of (row_partition_type, row_partition_tensor) pairs. """ partitions = rt_input._nested_row_partitions # pylint: disable=protected-access tail = [_get_row_partition_type_tensor_pairs_tail(x) for x in partitions[1:]] if partitions[0]._value_rowids is not None: # pylint: disable=protected-access return [("FIRST_DIM_SIZE", partitions[0].nrows()), ("VALUE_ROWIDS", partitions[0].value_rowids())] + tail else: return [("ROW_SPLITS", partitions[0].row_splits())] + tail def _shape_as_tensor(shape, dtype): """Takes shape and coerces it to a shape as a tensor. If the object is already a tensor, simply passes it on (result is guaranteed to be int64 or int32, but not necessarily dtype). If not, creates a tensor of type dtype. Result is either a scalar equal to -1 if the shape is unknown_rank. Otherwise, it is a vector, where unknown dimensions are represented with a value of -1. In C++, see TensorShapeFromTensor for parsing shapes in kernels, and InferenceContext::MakeShapeFromShapeTensorTreatScalarAsUnknownShape, for use in the shape inference function. Args: shape: input to coerce from TensorShape, Tensor, None, List[Optional[Int]], Tuple[Optional[Int]]. dtype: tf.int64 or tf.int32 Returns: a scalar or vector tensor of dtype tf.int32 or tf.int64. """ if dtype != dtypes.int64 and dtype != dtypes.int32: raise ValueError(f"Expected int64 or int32 for dtype: got {dtype}.") if isinstance(shape, tensor_lib.Tensor): if shape.dtype != dtypes.int64 and shape.dtype != dtypes.int32: return math_ops.cast(shape, dtype) return shape shape = tensor_shape.as_shape(shape) if not shape: # Imply rank is unknown using a -1 scalar. return constant_op.constant(-1, dtype=dtype) shape = [(-1 if x is None else x) for x in shape.as_list()] # At this point, shape is List[Int]. return constant_op.constant(shape, dtype=dtype) def _nvals_uniform_row_length(values, uniform_row_length): """Get the number of values for uniform row length constructor.""" const_nvals = tensor_shape.dimension_at_index(values.shape, 0).value if const_nvals is not None: nvals = constant_op.constant(const_nvals, uniform_row_length.dtype) elif isinstance(values, RaggedTensor): nvals = values.nrows(out_type=uniform_row_length.dtype) else: nvals = array_ops.shape(values, out_type=uniform_row_length.dtype)[0] return nvals def _get_optional_partition_dtype(values): """Returns the partition dtype, or None if None exists.""" if isinstance(values, RaggedTensor): # pylint: disable=protected-access return values._row_partition.dtype return None _SUPPORTED_RAGGED_VALUE_TYPES = (tensor_lib.Tensor, RaggedTensor) # TODO(edloper): Consider whether we should change the registry to be on # TypeSpecs rather than ValueTypes. def _add_supported_value_type(cls): """Register the `cls` as supported value type of RaggedTenosr. The cls must be a subclass of CompositeTensor, and must support: - Spec: The Spec must be a `BatchableTypeSpec` - Properties: - x.shape - x.dtype - Methods: - x.__getitem__(idx) (method: returns a supported value type) - x.set_shape(shape) - Ops: - tf.shape(x) -- tf.shape(x)[0] must be a tf.Tensor. - tf.tile(x) - assert_rank_at_least(x) - tf.ones_like(x) - tf.gather(params=x, indices=Tensor) - tf.add(x, y) - tf.boolean_mask(x, ...) - @TODO(edloper): Complete this list Note: the following RaggedTensor, RaggedTensorSpec methods & ops are not currently supported unless `rt.values` is a RaggedTensor or a tf.Tensor: - rt.to_tensor() - rt.to_sparse_tensor() - rt._to_variant() - rt._from_variant() - tf.ragged.cross([rt]) - tf.gather(params=x, indices=rt) # rt used for indices - RaggedTensorSpec methods: - _batch - _unbatch - _to_tensor_list - _to_batched_tensor_list - _from_compatible_tensor_list Args: cls: The type to be added to supported value types. """ if not issubclass(cls, composite_tensor.CompositeTensor): raise ValueError(f"cls ({cls}) must be a subclass of CompositeTensor.") if not hasattr(cls, "shape"): raise ValueError("cls must support the `shape` property.") if not hasattr(cls, "dtype"): raise ValueError("cls must support the `dtype` property.") global _SUPPORTED_RAGGED_VALUE_TYPES _SUPPORTED_RAGGED_VALUE_TYPES += (cls,) def _is_supported_ragged_values_type(value): return isinstance(value, _SUPPORTED_RAGGED_VALUE_TYPES) def _assert_is_supported_ragged_values_type(value): if not _is_supported_ragged_values_type(value): ok_types = ", ".join(cls.__name__ for cls in _SUPPORTED_RAGGED_VALUE_TYPES) raise TypeError(f"type(values) must be one of: {ok_types}, got {value}.") def _formatter(x): """Separate Numpy array elements with comma.""" if isinstance(x, np.ndarray): if x.size != 0: return np.array2string(x, separator=", ") else: # When x.size==0, np.array2string always returns `[]`. This isn't always # what we want. E.g., if `x.shape=[0, 3]`, then we want `[[], [], []]`. return repr(x.tolist()) else: return str(x) # Type annotation indicating that a value is ragged. Includes RaggedTensor # as well as the (deprecated) RaggedTensorValue class from TF 1.x. Ragged = typing.Union[RaggedTensor, ragged_tensor_value.RaggedTensorValue] # Type annotation indicating that a value is a ragged tensor, a dense tensor, # or a value that can be converted to a tensor (e.g. np.array). # TODO(edloper): Add Variable to TensorLike, and remove it from here. RaggedOrDense = typing.Union[Ragged, core_types.TensorLike] # RaggedTensor must import ragged_ops to ensure that all dispatched ragged ops # are registered. Ragged ops import RaggedTensor, so import at bottom of the # file to avoid a partially-initialized module error. from tensorflow.python.ops.ragged import ragged_ops # pylint: disable=unused-import, g-bad-import-order, g-import-not-at-top
RaggedTensorType
python
ansible__ansible
test/units/modules/test_uri.py
{ "start": 357, "end": 1822 }
class ____: def test_main_no_args(self): """Module must fail if called with no args.""" with pytest.raises(SystemExit), \ patch_module_args(): uri.main() def test_main_no_force(self, mocker): """The "force" parameter to fetch_url() must be absent or false when the module is called without "force".""" resp = MagicMock() resp.headers.get_content_type.return_value = "text/html" info = {"url": "http://example.com/", "status": 200} with patch.object(uri, "fetch_url", return_value=(resp, info)) as fetch_url, \ patch_module_args({"url": "http://example.com/"}): with pytest.raises(SystemExit): uri.main() fetch_url.assert_called_once() assert not fetch_url.call_args[1].get("force") def test_main_force(self): """The "force" parameter to fetch_url() must be true when the module is called with "force".""" resp = MagicMock() resp.headers.get_content_type.return_value = "text/html" info = {"url": "http://example.com/", "status": 200} with patch.object(uri, "fetch_url", return_value=(resp, info)) as fetch_url, \ patch_module_args({"url": "http://example.com/", "force": True}): with pytest.raises(SystemExit): uri.main() fetch_url.assert_called_once() assert fetch_url.call_args[1].get("force")
TestUri
python
keras-team__keras
keras/src/losses/losses.py
{ "start": 26905, "end": 34225 }
class ____(LossFunctionWrapper): """Computes focal cross-entropy loss between true labels and predictions. Binary cross-entropy loss is often used for binary (0 or 1) classification tasks. The loss function requires the following inputs: - `y_true` (true label): This is either 0 or 1. - `y_pred` (predicted value): This is the model's prediction, i.e, a single floating-point value which either represents a [logit](https://en.wikipedia.org/wiki/Logit), (i.e, value in [-inf, inf] when `from_logits=True`) or a probability (i.e, value in `[0., 1.]` when `from_logits=False`). According to [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf), it helps to apply a "focal factor" to down-weight easy examples and focus more on hard examples. By default, the focal tensor is computed as follows: `focal_factor = (1 - output) ** gamma` for class 1 `focal_factor = output ** gamma` for class 0 where `gamma` is a focusing parameter. When `gamma=0`, this function is equivalent to the binary crossentropy loss. Args: apply_class_balancing: A bool, whether to apply weight balancing on the binary classes 0 and 1. alpha: A weight balancing factor for class 1, default is `0.25` as mentioned in reference [Lin et al., 2018]( https://arxiv.org/pdf/1708.02002.pdf). The weight for class 0 is `1.0 - alpha`. gamma: A focusing parameter used to compute the focal factor, default is `2.0` as mentioned in the reference [Lin et al., 2018](https://arxiv.org/pdf/1708.02002.pdf). from_logits: Whether to interpret `y_pred` as a tensor of [logit](https://en.wikipedia.org/wiki/Logit) values. By default, we assume that `y_pred` are probabilities (i.e., values in `[0, 1]`). label_smoothing: Float in `[0, 1]`. When `0`, no smoothing occurs. When > `0`, we compute the loss between the predicted labels and a smoothed version of the true labels, where the smoothing squeezes the labels towards `0.5`. Larger values of `label_smoothing` correspond to heavier smoothing. axis: The axis along which to compute crossentropy (the features axis). Defaults to `-1`. reduction: Type of reduction to apply to the loss. In almost all cases this should be `"sum_over_batch_size"`. Supported options are `"sum"`, `"sum_over_batch_size"`, `"mean"`, `"mean_with_sample_weight"` or `None`. `"sum"` sums the loss, `"sum_over_batch_size"` and `"mean"` sum the loss and divide by the sample size, and `"mean_with_sample_weight"` sums the loss and divides by the sum of the sample weights. `"none"` and `None` perform no aggregation. Defaults to `"sum_over_batch_size"`. name: Optional name for the loss instance. dtype: The dtype of the loss's computations. Defaults to `None`, which means using `keras.backend.floatx()`. `keras.backend.floatx()` is a `"float32"` unless set to different value (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is provided, then the `compute_dtype` will be utilized. Examples: With the `compile()` API: ```python model.compile( loss=keras.losses.BinaryFocalCrossentropy( gamma=2.0, from_logits=True), ... ) ``` As a standalone function: >>> # Example 1: (batch_size = 1, number of samples = 4) >>> y_true = np.array([0, 1, 0, 0]) >>> y_pred = np.array([-18.6, 0.51, 2.94, -12.8]) >>> loss = keras.losses.BinaryFocalCrossentropy( ... gamma=2, from_logits=True) >>> loss(y_true, y_pred) 0.691 >>> # Apply class weight >>> loss = keras.losses.BinaryFocalCrossentropy( ... apply_class_balancing=True, gamma=2, from_logits=True) >>> loss(y_true, y_pred) 0.51 >>> # Example 2: (batch_size = 2, number of samples = 4) >>> y_true = np.array([[0, 1], [0, 0]]) >>> y_pred = np.array([[-18.6, 0.51], [2.94, -12.8]]) >>> # Using default 'auto'/'sum_over_batch_size' reduction type. >>> loss = keras.losses.BinaryFocalCrossentropy( ... gamma=3, from_logits=True) >>> loss(y_true, y_pred) 0.647 >>> # Apply class weight >>> loss = keras.losses.BinaryFocalCrossentropy( ... apply_class_balancing=True, gamma=3, from_logits=True) >>> loss(y_true, y_pred) 0.482 >>> # Using 'sample_weight' attribute with focal effect >>> loss = keras.losses.BinaryFocalCrossentropy( ... gamma=3, from_logits=True) >>> loss(y_true, y_pred, sample_weight=[0.8, 0.2]) 0.133 >>> # Apply class weight >>> loss = keras.losses.BinaryFocalCrossentropy( ... apply_class_balancing=True, gamma=3, from_logits=True) >>> loss(y_true, y_pred, sample_weight=[0.8, 0.2]) 0.097 >>> # Using 'sum' reduction` type. >>> loss = keras.losses.BinaryFocalCrossentropy( ... gamma=4, from_logits=True, ... reduction="sum") >>> loss(y_true, y_pred) 1.222 >>> # Apply class weight >>> loss = keras.losses.BinaryFocalCrossentropy( ... apply_class_balancing=True, gamma=4, from_logits=True, ... reduction="sum") >>> loss(y_true, y_pred) 0.914 >>> # Using 'none' reduction type. >>> loss = keras.losses.BinaryFocalCrossentropy( ... gamma=5, from_logits=True, ... reduction=None) >>> loss(y_true, y_pred) array([0.0017 1.1561], dtype=float32) >>> # Apply class weight >>> loss = keras.losses.BinaryFocalCrossentropy( ... apply_class_balancing=True, gamma=5, from_logits=True, ... reduction=None) >>> loss(y_true, y_pred) array([0.0004 0.8670], dtype=float32) """ def __init__( self, apply_class_balancing=False, alpha=0.25, gamma=2.0, from_logits=False, label_smoothing=0.0, axis=-1, reduction="sum_over_batch_size", name="binary_focal_crossentropy", dtype=None, ): super().__init__( binary_focal_crossentropy, name=name, reduction=reduction, dtype=dtype, apply_class_balancing=apply_class_balancing, alpha=alpha, gamma=gamma, from_logits=from_logits, label_smoothing=label_smoothing, axis=axis, ) self.from_logits = from_logits self.label_smoothing = label_smoothing self.axis = axis self.apply_class_balancing = apply_class_balancing self.alpha = alpha self.gamma = gamma def get_config(self): config = Loss.get_config(self) config.update( { "from_logits": self.from_logits, "label_smoothing": self.label_smoothing, "axis": self.axis, "apply_class_balancing": self.apply_class_balancing, "alpha": self.alpha, "gamma": self.gamma, } ) return config @keras_export("keras.losses.CategoricalCrossentropy")
BinaryFocalCrossentropy
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image43.py
{ "start": 315, "end": 1336 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image43.xlsx") # Despite a lot of effort and testing I can't match Excel's # calculations exactly for EMF files. The differences are are small # (<1%) and in general aren't visible. The following ignore the # elements where these differences occur until the they can be # resolved. This issue doesn't occur for any other image type. self.ignore_elements = { "xl/drawings/drawing1.xml": ["<xdr:rowOff>", "<xdr:colOff>", "<a:ext cx="] } def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_image("E9", self.image_dir + "red_32x32.emf") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
test/engine/test_pool.py
{ "start": 59414, "end": 64761 }
class ____(PoolTestBase): def _fixture(self, **kw): dbapi = Mock() return ( dbapi, pool.QueuePool(creator=lambda: dbapi.connect("foo.db"), **kw), ) def _engine_fixture(self, **kw): dbapi = Mock() return dbapi, create_engine( "postgresql://", module=dbapi, creator=lambda: dbapi.connect("foo.db"), _initialize=False, ) @testing.combinations("detach", "invalidate", "return") def test_custom(self, extra_step): dbapi, p = self._fixture(reset_on_return=None) @event.listens_for(p, "reset") def custom_reset(dbapi_conn, record, reset_state): dbapi_conn.special_reset_method(reset_state) c1 = p.connect() if extra_step == "detach": c1.detach() elif extra_step == "invalidate": c1.invalidate() c1.close() special_event = mock.call.special_reset_method( PoolResetState( transaction_was_reset=False, terminate_only=extra_step == "detach", asyncio_safe=True, ) ) if extra_step == "detach": expected = [special_event, mock.call.close()] elif extra_step == "invalidate": expected = [mock.call.close()] else: expected = [special_event] eq_(dbapi.connect().mock_calls, expected) assert not dbapi.connect().rollback.called assert not dbapi.connect().commit.called @testing.combinations(True, False, argnames="assert_w_event") @testing.combinations(True, False, argnames="use_engine_transaction") def test_custom_via_engine(self, assert_w_event, use_engine_transaction): dbapi, engine = self._engine_fixture(reset_on_return=None) if assert_w_event: @event.listens_for(engine, "reset") def custom_reset(dbapi_conn, record, reset_state): dbapi_conn.special_reset_method(reset_state) c1 = engine.connect() if use_engine_transaction: c1.begin() c1.close() assert dbapi.connect().rollback.called if assert_w_event: special_event = mock.call.special_reset_method( PoolResetState( transaction_was_reset=use_engine_transaction, terminate_only=False, asyncio_safe=True, ) ) if use_engine_transaction: expected = [mock.call.rollback(), special_event] else: expected = [special_event, mock.call.rollback()] eq_(dbapi.connect().mock_calls, expected) @testing.combinations(True, False, argnames="assert_w_event") def test_plain_rollback(self, assert_w_event): dbapi, p = self._fixture(reset_on_return="rollback") if assert_w_event: @event.listens_for(p, "reset") def custom_reset(dbapi_conn, record, reset_state): dbapi_conn.special_reset_method(reset_state) c1 = p.connect() c1.close() assert dbapi.connect().rollback.called assert not dbapi.connect().commit.called if assert_w_event: special_event = mock.call.special_reset_method( PoolResetState( transaction_was_reset=False, terminate_only=False, asyncio_safe=True, ) ) expected = [special_event, mock.call.rollback()] eq_(dbapi.connect().mock_calls, expected) @testing.combinations(True, False, argnames="assert_w_event") @testing.combinations(True, False, argnames="use_engine_transaction") def test_plain_rollback_via_engine( self, assert_w_event, use_engine_transaction ): dbapi, engine = self._engine_fixture(reset_on_return="rollback") if assert_w_event: @event.listens_for(engine, "reset") def custom_reset(dbapi_conn, record, reset_state): dbapi_conn.special_reset_method(reset_state) c1 = engine.connect() if use_engine_transaction: c1.begin() c1.close() assert dbapi.connect().rollback.called if assert_w_event: special_event = mock.call.special_reset_method( PoolResetState( transaction_was_reset=use_engine_transaction, terminate_only=False, asyncio_safe=True, ) ) if use_engine_transaction: expected = [mock.call.rollback(), special_event] else: expected = [special_event, mock.call.rollback()] eq_(dbapi.connect().mock_calls, expected) def test_plain_commit(self): dbapi, p = self._fixture(reset_on_return="commit") c1 = p.connect() c1.close() assert not dbapi.connect().rollback.called assert dbapi.connect().commit.called def test_plain_none(self): dbapi, p = self._fixture(reset_on_return=None) c1 = p.connect() c1.close() assert not dbapi.connect().rollback.called assert not dbapi.connect().commit.called
ResetOnReturnTest
python
dask__dask
dask/tests/test_typing.py
{ "start": 1084, "end": 2459 }
class ____(DaskCollection): def __init__(self, based_on: DaskCollection) -> None: self.based_on = based_on def __dask_graph__(self) -> Graph: return self.based_on.__dask_graph__() def __dask_keys__(self) -> NestedKeys: return self.based_on.__dask_keys__() def __dask_postcompute__(self) -> tuple[PostComputeCallable, tuple]: return finalize, () def __dask_postpersist__(self) -> tuple[PostPersistCallable, tuple]: return self.based_on.__dask_postpersist__() def __dask_tokenize__(self) -> Hashable: return tokenize(self.based_on) __dask_scheduler__ = staticmethod(dask.threaded.get) __dask_optimize__ = globalmethod( dont_optimize, key="hlgcollection_optim", falsey=dont_optimize, ) def compute(self, **kwargs) -> Any: return dask.compute(self, **kwargs) def persist(self, **kwargs) -> Inheriting: return Inheriting(self.based_on.persist(**kwargs)) def visualize( self, filename: str = "mydask", format: str | None = None, optimize_graph: bool = False, **kwargs: Any, ) -> DisplayObject | None: return dask.visualize( self, filename=filename, format=format, optimize_graph=optimize_graph, **kwargs, )
Inheriting
python
Netflix__metaflow
metaflow/packaging_sys/__init__.py
{ "start": 24901, "end": 31994 }
class ____(MetaflowCodeContent, version_id=1): _code_dir = ".mf_code" _other_dir = ".mf_meta" _info_file = "INFO" _config_file = "CONFIG" _dist_info_file = "DIST_INFO" def __init_subclass__(cls, **kwargs) -> None: # Important to add this here to prevent the subclass of MetaflowCodeContentV1Base from # also calling __init_subclass__ in MetaflowCodeContent (which would create a problem) return None def __init__(self, code_dir: str, other_dir: str) -> None: self._code_dir = code_dir self._other_dir = other_dir @classmethod def _get_otherfile_path( cls, mfcontent_info: Optional[Dict[str, Any]], filename: str, in_archive: bool ) -> str: if in_archive: return os.path.join(cls._other_dir, filename) return os.path.join(get_metaflow_root(), "..", cls._other_dir, filename) @classmethod def _get_codefile_path( cls, mfcontent_info: Optional[Dict[str, Any]], filename: str, in_archive: bool ) -> str: if in_archive: return os.path.join(cls._code_dir, filename) return os.path.join(get_metaflow_root(), filename) @classmethod def get_info_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional[Dict[str, Any]]: path_to_file = cls._get_otherfile_path( mfcontent_info, cls._info_file, in_archive=False ) if os.path.isfile(path_to_file): with open(path_to_file, "r", encoding="utf-8") as f: return json.load(f) return None @classmethod def get_config_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional[Dict[str, Any]]: path_to_file = cls._get_otherfile_path( mfcontent_info, cls._config_file, in_archive=False ) if os.path.isfile(path_to_file): with open(path_to_file, "r", encoding="utf-8") as f: return json.load(f) return None @classmethod def get_filename_impl( cls, mfcontent_info: Optional[Dict[str, Any]], filename: str, content_type: ContentType, ) -> Optional[str]: if content_type == ContentType.CODE_CONTENT: path_to_file = cls._get_codefile_path( mfcontent_info, filename, in_archive=False ) elif content_type in (ContentType.OTHER_CONTENT, ContentType.MODULE_CONTENT): path_to_file = cls._get_otherfile_path( mfcontent_info, filename, in_archive=False ) else: raise ValueError( f"Invalid content type {content_type} for filename {filename}" ) if os.path.isfile(path_to_file): return path_to_file return None @classmethod def get_distribution_finder_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional["metaflow.extension_support.metadata.DistributionFinder"]: path_to_file = cls._get_otherfile_path( mfcontent_info, cls._dist_info_file, in_archive=False ) if os.path.isfile(path_to_file): with open(path_to_file, "r", encoding="utf-8") as f: return PackagedDistributionFinder(json.load(f)) return None @classmethod def get_archive_info_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: info_file = packaging_backend.cls_get_member( archive, cls._get_otherfile_path(mfcontent_info, cls._info_file, in_archive=True), ) if info_file: return json.loads(info_file) return None @classmethod def get_archive_config_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: config_file = packaging_backend.cls_get_member( archive, cls._get_otherfile_path(mfcontent_info, cls._config_file, in_archive=True), ) if config_file: return json.loads(config_file) return None @classmethod def get_archive_filename_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, filename: str, content_type: ContentType, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> str: if content_type == ContentType.CODE_CONTENT: path_to_file = cls._get_codefile_path( mfcontent_info, filename, in_archive=False ) elif content_type in (ContentType.OTHER_CONTENT, ContentType.MODULE_CONTENT): path_to_file = cls._get_otherfile_path( mfcontent_info, filename, in_archive=False ) else: raise ValueError( f"Invalid content type {content_type} for filename {filename}" ) if packaging_backend.cls_has_member(archive, path_to_file): # The file is present in the archive return path_to_file return None @classmethod def get_archive_content_members_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, content_types: Optional[int] = None, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> List[Any]: to_return = [] module_content = set(mfcontent_info.get("module_files", [])) for member in packaging_backend.cls_list_members(archive): filename = packaging_backend.cls_member_name(member) if filename.startswith(cls._other_dir) and ( content_types & ContentType.OTHER_CONTENT.value ): to_return.append(member) elif filename.startswith(cls._code_dir): # Special case for marker which is a other content even if in code. if filename == MFCONTENT_MARKER: if content_types & ContentType.OTHER_CONTENT.value: to_return.append(member) else: continue # Here it is either module or code if os.path.join(cls._code_dir, filename) in module_content: if content_types & ContentType.MODULE_CONTENT.value: to_return.append(member) elif content_types & ContentType.CODE_CONTENT.value: to_return.append(member) else: if content_types & ContentType.USER_CONTENT.value: # Everything else is user content to_return.append(member) return to_return @classmethod def get_post_extract_env_vars_impl(cls, dest_dir: str) -> Dict[str, str]: return {"PYTHONPATH": f"{dest_dir}/{cls._code_dir}"}
MetaflowCodeContentV1Base
python
ray-project__ray
rllib/utils/metrics/metrics_logger.py
{ "start": 65156, "end": 65398 }
class ____: def acquire(self, blocking=True, timeout=-1): return True def release(self): pass def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): pass
_DummyRLock
python
python-openxml__python-docx
tests/styles/test_style.py
{ "start": 450, "end": 2919 }
class ____: def it_constructs_the_right_type_of_style(self, factory_fixture): style_elm, StyleCls_, style_ = factory_fixture style = StyleFactory(style_elm) StyleCls_.assert_called_once_with(style_elm) assert style is style_ # fixtures ------------------------------------------------------- @pytest.fixture(params=["paragraph", "character", "table", "numbering"]) def factory_fixture( self, request, paragraph_style_, ParagraphStyle_, character_style_, CharacterStyle_, table_style_, _TableStyle_, numbering_style_, _NumberingStyle_, ): type_attr_val = request.param StyleCls_, style_mock = { "paragraph": (ParagraphStyle_, paragraph_style_), "character": (CharacterStyle_, character_style_), "table": (_TableStyle_, table_style_), "numbering": (_NumberingStyle_, numbering_style_), }[request.param] style_cxml = "w:style{w:type=%s}" % type_attr_val style_elm = element(style_cxml) return style_elm, StyleCls_, style_mock # fixture components ----------------------------------- @pytest.fixture def ParagraphStyle_(self, request, paragraph_style_): return class_mock( request, "docx.styles.style.ParagraphStyle", return_value=paragraph_style_ ) @pytest.fixture def paragraph_style_(self, request): return instance_mock(request, ParagraphStyle) @pytest.fixture def CharacterStyle_(self, request, character_style_): return class_mock( request, "docx.styles.style.CharacterStyle", return_value=character_style_ ) @pytest.fixture def character_style_(self, request): return instance_mock(request, CharacterStyle) @pytest.fixture def _TableStyle_(self, request, table_style_): return class_mock(request, "docx.styles.style._TableStyle", return_value=table_style_) @pytest.fixture def table_style_(self, request): return instance_mock(request, _TableStyle) @pytest.fixture def _NumberingStyle_(self, request, numbering_style_): return class_mock( request, "docx.styles.style._NumberingStyle", return_value=numbering_style_ ) @pytest.fixture def numbering_style_(self, request): return instance_mock(request, _NumberingStyle)
DescribeStyleFactory
python
django__django
django/core/exceptions.py
{ "start": 519, "end": 647 }
class ____(Exception): """The query returned multiple objects when only one was expected.""" pass
MultipleObjectsReturned
python
RaRe-Technologies__gensim
gensim/models/poincare.py
{ "start": 30392, "end": 36861 }
class ____: """Compute Poincare distances, gradients and loss for a training batch. Store intermediate state to avoid recomputing multiple times. """ def __init__(self, vectors_u, vectors_v, indices_u, indices_v, regularization_coeff=1.0): """ Initialize instance with sets of vectors for which distances are to be computed. Parameters ---------- vectors_u : numpy.array Vectors of all nodes `u` in the batch. Expected shape (batch_size, dim). vectors_v : numpy.array Vectors of all positively related nodes `v` and negatively sampled nodes `v'`, for each node `u` in the batch. Expected shape (1 + neg_size, dim, batch_size). indices_u : list of int List of node indices for each of the vectors in `vectors_u`. indices_v : list of lists of int Nested list of lists, each of which is a list of node indices for each of the vectors in `vectors_v` for a specific node `u`. regularization_coeff : float, optional Coefficient to use for l2-regularization """ self.vectors_u = vectors_u.T[np.newaxis, :, :] # (1, dim, batch_size) self.vectors_v = vectors_v # (1 + neg_size, dim, batch_size) self.indices_u = indices_u self.indices_v = indices_v self.regularization_coeff = regularization_coeff self.poincare_dists = None self.euclidean_dists = None self.norms_u = None self.norms_v = None self.alpha = None self.beta = None self.gamma = None self.gradients_u = None self.distance_gradients_u = None self.gradients_v = None self.distance_gradients_v = None self.loss = None self._distances_computed = False self._gradients_computed = False self._distance_gradients_computed = False self._loss_computed = False def compute_all(self): """Convenience method to perform all computations.""" self.compute_distances() self.compute_distance_gradients() self.compute_gradients() self.compute_loss() def compute_distances(self): """Compute and store norms, euclidean distances and poincare distances between input vectors.""" if self._distances_computed: return euclidean_dists = np.linalg.norm(self.vectors_u - self.vectors_v, axis=1) # (1 + neg_size, batch_size) norms_u = np.linalg.norm(self.vectors_u, axis=1) # (1, batch_size) norms_v = np.linalg.norm(self.vectors_v, axis=1) # (1 + neg_size, batch_size) alpha = 1 - norms_u ** 2 # (1, batch_size) beta = 1 - norms_v ** 2 # (1 + neg_size, batch_size) gamma = 1 + 2 * ( (euclidean_dists ** 2) / (alpha * beta) ) # (1 + neg_size, batch_size) poincare_dists = np.arccosh(gamma) # (1 + neg_size, batch_size) exp_negative_distances = np.exp(-poincare_dists) # (1 + neg_size, batch_size) Z = exp_negative_distances.sum(axis=0) # (batch_size) self.euclidean_dists = euclidean_dists self.poincare_dists = poincare_dists self.exp_negative_distances = exp_negative_distances self.Z = Z self.gamma = gamma self.norms_u = norms_u self.norms_v = norms_v self.alpha = alpha self.beta = beta self.gamma = gamma self._distances_computed = True def compute_gradients(self): """Compute and store gradients of loss function for all input vectors.""" if self._gradients_computed: return self.compute_distances() self.compute_distance_gradients() # (1 + neg_size, dim, batch_size) gradients_v = -self.exp_negative_distances[:, np.newaxis, :] * self.distance_gradients_v gradients_v /= self.Z # (1 + neg_size, dim, batch_size) gradients_v[0] += self.distance_gradients_v[0] gradients_v[0] += self.regularization_coeff * 2 * self.vectors_v[0] # (1 + neg_size, dim, batch_size) gradients_u = -self.exp_negative_distances[:, np.newaxis, :] * self.distance_gradients_u gradients_u /= self.Z # (1 + neg_size, dim, batch_size) gradients_u = gradients_u.sum(axis=0) # (dim, batch_size) gradients_u += self.distance_gradients_u[0] assert not np.isnan(gradients_u).any() assert not np.isnan(gradients_v).any() self.gradients_u = gradients_u self.gradients_v = gradients_v self._gradients_computed = True def compute_distance_gradients(self): """Compute and store partial derivatives of poincare distance d(u, v) w.r.t all u and all v.""" if self._distance_gradients_computed: return self.compute_distances() euclidean_dists_squared = self.euclidean_dists ** 2 # (1 + neg_size, batch_size) # (1 + neg_size, 1, batch_size) c_ = (4 / (self.alpha * self.beta * np.sqrt(self.gamma ** 2 - 1)))[:, np.newaxis, :] # (1 + neg_size, 1, batch_size) u_coeffs = ((euclidean_dists_squared + self.alpha) / self.alpha)[:, np.newaxis, :] distance_gradients_u = u_coeffs * self.vectors_u - self.vectors_v # (1 + neg_size, dim, batch_size) distance_gradients_u *= c_ # (1 + neg_size, dim, batch_size) nan_gradients = self.gamma == 1 # (1 + neg_size, batch_size) if nan_gradients.any(): distance_gradients_u.swapaxes(1, 2)[nan_gradients] = 0 self.distance_gradients_u = distance_gradients_u # (1 + neg_size, 1, batch_size) v_coeffs = ((euclidean_dists_squared + self.beta) / self.beta)[:, np.newaxis, :] distance_gradients_v = v_coeffs * self.vectors_v - self.vectors_u # (1 + neg_size, dim, batch_size) distance_gradients_v *= c_ # (1 + neg_size, dim, batch_size) if nan_gradients.any(): distance_gradients_v.swapaxes(1, 2)[nan_gradients] = 0 self.distance_gradients_v = distance_gradients_v self._distance_gradients_computed = True def compute_loss(self): """Compute and store loss value for the given batch of examples.""" if self._loss_computed: return self.compute_distances() self.loss = -np.log(self.exp_negative_distances[0] / self.Z).sum() # scalar self._loss_computed = True
PoincareBatch
python
pytorch__pytorch
torchgen/model.py
{ "start": 78246, "end": 78745 }
class ____(Type): name: BaseTy def __str__(self) -> str: return f"{self.name.name}" def is_base_ty_like(self, base_ty: BaseTy) -> bool: return self.name == base_ty def is_nullable(self) -> bool: return False def is_list_like(self) -> ListType | None: return None def is_symint_like(self) -> bool: return self.name == BaseTy.SymInt # Optional types may be specified, or may also be validly given None @dataclass(frozen=True)
BaseType
python
python__mypy
mypy/checkexpr.py
{ "start": 292720, "end": 293129 }
class ____(types.BoolTypeQuery): """Visitor for querying whether a type has an erased component.""" def __init__(self) -> None: super().__init__(types.ANY_STRATEGY) def visit_erased_type(self, t: ErasedType) -> bool: return True def has_uninhabited_component(t: Type | None) -> bool: return t is not None and t.accept(HasUninhabitedComponentsQuery())
HasErasedComponentsQuery
python
numpy__numpy
numpy/matrixlib/tests/test_multiarray.py
{ "start": 89, "end": 555 }
class ____: def test_type(self): x = np.array([1, 2, 3]) assert_(isinstance(x.view(np.matrix), np.matrix)) def test_keywords(self): x = np.array([(1, 2)], dtype=[('a', np.int8), ('b', np.int8)]) # We must be specific about the endianness here: y = x.view(dtype='<i2', type=np.matrix) assert_array_equal(y, [[513]]) assert_(isinstance(y, np.matrix)) assert_equal(y.dtype, np.dtype('<i2'))
TestView
python
spyder-ide__spyder
spyder/plugins/statusbar/widgets/status.py
{ "start": 383, "end": 752 }
class ____(BaseTimerStatus): """Status bar widget for system memory usage.""" ID = 'memory_status' def get_value(self): """Return memory usage.""" text = '%d%%' % memory_usage() return 'Mem ' + text.rjust(3) def get_tooltip(self): """Return the widget tooltip text.""" return _('Global memory usage')
MemoryStatus
python
eventlet__eventlet
tests/db_pool_test.py
{ "start": 13844, "end": 15040 }
class ____: dummy_table_sql = """CREATE TEMPORARY TABLE test_table ( row_id INTEGER PRIMARY KEY AUTO_INCREMENT, value_int INTEGER, value_float FLOAT, value_string VARCHAR(200), value_uuid CHAR(36), value_binary BLOB, value_binary_string VARCHAR(200) BINARY, value_enum ENUM('Y','N'), created TIMESTAMP ) ENGINE=InnoDB;""" @tests.skip_unless(mysql_requirement) def setUp(self): self._dbmodule = MySQLdb self._auth = tests.get_database_auth()['MySQLdb'] super().setUp() def tearDown(self): super().tearDown() def create_db(self): auth = self._auth.copy() try: self.drop_db() except Exception: pass dbname = 'test%s' % os.getpid() db = self._dbmodule.connect(**auth).cursor() db.execute("create database " + dbname) db.close() self._auth['db'] = dbname del db def drop_db(self): db = self._dbmodule.connect(**self._auth).cursor() db.execute("drop database IF EXISTS " + self._auth['db']) db.close() del db
MysqlConnectionPool
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/atrous_conv2d_test.py
{ "start": 7413, "end": 9430 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testAtrousConv2DTransposeForward(self): with self.session(): # Input: [batch, height, width, input_depth] height = 9 for width in [9, 10]: # Test both odd and even width. x_shape = [2, height, width, 2] x = np.arange(np.prod(x_shape), dtype=np.float32).reshape(x_shape) # Filter: [kernel_height, kernel_width, input_depth, output_depth] for kernel_height in range(1, 4): for kernel_width in range(1, 4): f_shape = [kernel_height, kernel_width, 2, 2] f = np.arange(np.prod(f_shape), dtype=np.float32).reshape(f_shape) for rate in range(1, 4): f_up = _upsample_filters(f, rate) kernel_height_up = (kernel_height + (kernel_height - 1) * (rate - 1)) kernel_width_up = kernel_width + (kernel_width - 1) * (rate - 1) for padding in ["SAME", "VALID"]: if padding == "SAME": y_shape = [2, height, width, 2] else: y_shape = [ 2, height + kernel_height_up - 1, width + kernel_width_up - 1, 2 ] y1 = nn_ops.atrous_conv2d_transpose(x, f, y_shape, rate, padding) y2 = nn_ops.conv2d_transpose( x, f_up, y_shape, strides=[1, 1, 1, 1], padding=padding) self.assertAllClose(y1, y2, rtol=1e-3, atol=1e-3) def testAtrousConv2DTransposeInvalid(self): with self.session(): with self.assertRaises((errors.InvalidArgumentError, ValueError)): op = nn_ops.atrous_conv2d_transpose( value=np.ones((10, 1, 1, 1)), filters=np.ones((1, 1, 1, 1)), rate=1356819205, padding="SAME", output_shape=[1, 1, 1, 1]) self.evaluate(op)
AtrousConv2DTransposeTest
python
milvus-io__pymilvus
tests/test_grpc_handler.py
{ "start": 12702, "end": 19534 }
class ____: def test_create_collection_sync(self, channel: Any, client_thread: Any) -> None: handler = GrpcHandler(channel=channel) schema = CollectionSchema([ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True), FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128) ]) create_future = client_thread.submit( handler.create_collection, collection_name="test_collection", fields=schema, timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["CreateCollection"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = create_future.result() assert result is None def test_create_collection_async(self, channel: Any, client_thread: Any) -> None: handler = GrpcHandler(channel=channel) schema = CollectionSchema([ FieldSchema(name="id", dtype=DataType.INT64, is_primary=True), FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=128) ]) create_future = client_thread.submit( handler.create_collection, collection_name="test_collection", fields=schema, timeout=10, _async=True ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["CreateCollection"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = create_future.result() assert result is not None # Should return a future object def test_drop_collection(self, channel: Any, client_thread: Any) -> None: """Test drop_collection""" handler = GrpcHandler(channel=channel) drop_future = client_thread.submit( handler.drop_collection, collection_name="test_collection", timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["DropCollection"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = drop_future.result() assert result is None def test_add_collection_field(self, channel: Any, client_thread: Any) -> None: """Test add_collection_field""" handler = GrpcHandler(channel=channel) field_schema = FieldSchema(name="new_field", dtype=DataType.INT64) add_field_future = client_thread.submit( handler.add_collection_field, collection_name="test_collection", field_schema=field_schema, timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["AddCollectionField"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = add_field_future.result() assert result is None def test_alter_collection_properties(self, channel: Any, client_thread: Any) -> None: """Test alter_collection_properties""" handler = GrpcHandler(channel=channel) properties = {"prop1": "value1", "prop2": "value2"} alter_future = client_thread.submit( handler.alter_collection_properties, collection_name="test_collection", properties=properties, timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["AlterCollection"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = alter_future.result() assert result is None def test_alter_collection_field_properties(self, channel: Any, client_thread: Any) -> None: """Test alter_collection_field_properties""" handler = GrpcHandler(channel=channel) field_params = {"param1": "value1"} alter_field_future = client_thread.submit( handler.alter_collection_field_properties, collection_name="test_collection", field_name="test_field", field_params=field_params, timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["AlterCollectionField"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = alter_field_future.result() assert result is None def test_drop_collection_properties(self, channel: Any, client_thread: Any) -> None: handler = GrpcHandler(channel=channel) property_keys = ["prop1", "prop2"] drop_props_future = client_thread.submit( handler.drop_collection_properties, collection_name="test_collection", property_keys=property_keys, timeout=10 ) (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["AlterCollection"] ) rpc.send_initial_metadata(()) expected_result = common_pb2.Status(code=0) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") result = drop_props_future.result() assert result is None def test_has_collection_compatibility(self, channel: Any, client_thread: Any) -> None: """Test has_collection with Milvus < 2.3.2 compatibility""" handler = GrpcHandler(channel=channel) has_collection_future = client_thread.submit(handler.has_collection, "fake") (invocation_metadata, request, rpc) = channel.take_unary_unary( descriptor.methods_by_name["DescribeCollection"] ) rpc.send_initial_metadata(()) # Test compatibility with older Milvus versions expected_result = milvus_pb2.DescribeCollectionResponse( status=common_pb2.Status( error_code=common_pb2.UnexpectedError, reason="can't find collection fake" ), ) rpc.terminate(expected_result, (), grpc.StatusCode.OK, "") got_result = has_collection_future.result() assert got_result is False
TestGrpcHandlerCollectionOperations
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/test_given_models.py
{ "start": 7082, "end": 8095 }
class ____(TestCase): @given(from_model(UserSpecifiedAutoId)) def test_user_specified_auto_id(self, user_specified_auto_id): self.assertIsInstance(user_specified_auto_id, UserSpecifiedAutoId) self.assertIsNotNone(user_specified_auto_id.pk) if django.VERSION >= (5, 0, 0): from tests.django.toystore.models import Pizza class TestModelWithGeneratedField(TestCase): @given(from_model(Pizza)) def test_create_pizza(self, pizza): """ Strategies are not inferred for GeneratedField. """ # Check we generate valid objects. pizza.full_clean() # Refresh the instance from the database to make sure the # generated fields are populated correctly. pizza.refresh_from_db() # Check the expected types of the generated fields. self.assertIsInstance(pizza.slice_area, float) self.assertIsInstance(pizza.total_area, float)
TestUserSpecifiedAutoId
python
fsspec__filesystem_spec
fsspec/asyn.py
{ "start": 7893, "end": 31954 }
class ____(AbstractFileSystem): """Async file operations, default implementations Passes bulk operations to asyncio.gather for concurrent operation. Implementations that have concurrent batch operations and/or async methods should inherit from this class instead of AbstractFileSystem. Docstrings are copied from the un-underscored method in AbstractFileSystem, if not given. """ # note that methods do not have docstring here; they will be copied # for _* methods and inferred for overridden methods. async_impl = True mirror_sync_methods = True disable_throttling = False def __init__(self, *args, asynchronous=False, loop=None, batch_size=None, **kwargs): self.asynchronous = asynchronous self._pid = os.getpid() if not asynchronous: self._loop = loop or get_loop() else: self._loop = None self.batch_size = batch_size super().__init__(*args, **kwargs) @property def loop(self): if self._pid != os.getpid(): raise RuntimeError("This class is not fork-safe") return self._loop async def _rm_file(self, path, **kwargs): if ( inspect.iscoroutinefunction(self._rm) and type(self)._rm is not AsyncFileSystem._rm ): return await self._rm(path, recursive=False, batch_size=1, **kwargs) raise NotImplementedError async def _rm(self, path, recursive=False, batch_size=None, **kwargs): # TODO: implement on_error batch_size = batch_size or self.batch_size path = await self._expand_path(path, recursive=recursive) return await _run_coros_in_chunks( [self._rm_file(p, **kwargs) for p in reversed(path)], batch_size=batch_size, nofiles=True, ) async def _cp_file(self, path1, path2, **kwargs): raise NotImplementedError async def _mv_file(self, path1, path2): await self._cp_file(path1, path2) await self._rm_file(path1) async def _copy( self, path1, path2, recursive=False, on_error=None, maxdepth=None, batch_size=None, **kwargs, ): if on_error is None and recursive: on_error = "ignore" elif on_error is None: on_error = "raise" if isinstance(path1, list) and isinstance(path2, list): # No need to expand paths when both source and destination # are provided as lists paths1 = path1 paths2 = path2 else: source_is_str = isinstance(path1, str) paths1 = await self._expand_path( path1, maxdepth=maxdepth, recursive=recursive ) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories paths1 = [ p for p in paths1 if not (trailing_sep(p) or await self._isdir(p)) ] if not paths1: return source_is_file = len(paths1) == 1 dest_is_dir = isinstance(path2, str) and ( trailing_sep(path2) or await self._isdir(path2) ) exists = source_is_str and ( (has_magic(path1) and source_is_file) or (not has_magic(path1) and dest_is_dir and not trailing_sep(path1)) ) paths2 = other_paths( paths1, path2, exists=exists, flatten=not source_is_str, ) batch_size = batch_size or self.batch_size coros = [self._cp_file(p1, p2, **kwargs) for p1, p2 in zip(paths1, paths2)] result = await _run_coros_in_chunks( coros, batch_size=batch_size, return_exceptions=True, nofiles=True ) for ex in filter(is_exception, result): if on_error == "ignore" and isinstance(ex, FileNotFoundError): continue raise ex async def _pipe_file(self, path, value, mode="overwrite", **kwargs): raise NotImplementedError async def _pipe(self, path, value=None, batch_size=None, **kwargs): if isinstance(path, str): path = {path: value} batch_size = batch_size or self.batch_size return await _run_coros_in_chunks( [self._pipe_file(k, v, **kwargs) for k, v in path.items()], batch_size=batch_size, nofiles=True, ) async def _process_limits(self, url, start, end): """Helper for "Range"-based _cat_file""" size = None suff = False if start is not None and start < 0: # if start is negative and end None, end is the "suffix length" if end is None: end = -start start = "" suff = True else: size = size or (await self._info(url))["size"] start = size + start elif start is None: start = 0 if not suff: if end is not None and end < 0: if start is not None: size = size or (await self._info(url))["size"] end = size + end elif end is None: end = "" if isinstance(end, numbers.Integral): end -= 1 # bytes range is inclusive return f"bytes={start}-{end}" async def _cat_file(self, path, start=None, end=None, **kwargs): raise NotImplementedError async def _cat( self, path, recursive=False, on_error="raise", batch_size=None, **kwargs ): paths = await self._expand_path(path, recursive=recursive) coros = [self._cat_file(path, **kwargs) for path in paths] batch_size = batch_size or self.batch_size out = await _run_coros_in_chunks( coros, batch_size=batch_size, nofiles=True, return_exceptions=True ) if on_error == "raise": ex = next(filter(is_exception, out), False) if ex: raise ex if ( len(paths) > 1 or isinstance(path, list) or paths[0] != self._strip_protocol(path) ): return { k: v for k, v in zip(paths, out) if on_error != "omit" or not is_exception(v) } else: return out[0] async def _cat_ranges( self, paths, starts, ends, max_gap=None, batch_size=None, on_error="return", **kwargs, ): """Get the contents of byte ranges from one or more files Parameters ---------- paths: list A list of of filepaths on this filesystems starts, ends: int or list Bytes limits of the read. If using a single int, the same value will be used to read all the specified files. """ # TODO: on_error if max_gap is not None: # use utils.merge_offset_ranges raise NotImplementedError if not isinstance(paths, list): raise TypeError if not isinstance(starts, Iterable): starts = [starts] * len(paths) if not isinstance(ends, Iterable): ends = [ends] * len(paths) if len(starts) != len(paths) or len(ends) != len(paths): raise ValueError coros = [ self._cat_file(p, start=s, end=e, **kwargs) for p, s, e in zip(paths, starts, ends) ] batch_size = batch_size or self.batch_size return await _run_coros_in_chunks( coros, batch_size=batch_size, nofiles=True, return_exceptions=True ) async def _put_file(self, lpath, rpath, mode="overwrite", **kwargs): raise NotImplementedError async def _put( self, lpath, rpath, recursive=False, callback=DEFAULT_CALLBACK, batch_size=None, maxdepth=None, **kwargs, ): """Copy file(s) from local. Copies a specific file or tree of files (if recursive=True). If rpath ends with a "/", it will be assumed to be a directory, and target files will go within. The put_file method will be called concurrently on a batch of files. The batch_size option can configure the amount of futures that can be executed at the same time. If it is -1, then all the files will be uploaded concurrently. The default can be set for this instance by passing "batch_size" in the constructor, or for all instances by setting the "gather_batch_size" key in ``fsspec.config.conf``, falling back to 1/8th of the system limit . """ if isinstance(lpath, list) and isinstance(rpath, list): # No need to expand paths when both source and destination # are provided as lists rpaths = rpath lpaths = lpath else: source_is_str = isinstance(lpath, str) if source_is_str: lpath = make_path_posix(lpath) fs = LocalFileSystem() lpaths = fs.expand_path(lpath, recursive=recursive, maxdepth=maxdepth) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories lpaths = [p for p in lpaths if not (trailing_sep(p) or fs.isdir(p))] if not lpaths: return source_is_file = len(lpaths) == 1 dest_is_dir = isinstance(rpath, str) and ( trailing_sep(rpath) or await self._isdir(rpath) ) rpath = self._strip_protocol(rpath) exists = source_is_str and ( (has_magic(lpath) and source_is_file) or (not has_magic(lpath) and dest_is_dir and not trailing_sep(lpath)) ) rpaths = other_paths( lpaths, rpath, exists=exists, flatten=not source_is_str, ) is_dir = {l: os.path.isdir(l) for l in lpaths} rdirs = [r for l, r in zip(lpaths, rpaths) if is_dir[l]] file_pairs = [(l, r) for l, r in zip(lpaths, rpaths) if not is_dir[l]] await asyncio.gather(*[self._makedirs(d, exist_ok=True) for d in rdirs]) batch_size = batch_size or self.batch_size coros = [] callback.set_size(len(file_pairs)) for lfile, rfile in file_pairs: put_file = callback.branch_coro(self._put_file) coros.append(put_file(lfile, rfile, **kwargs)) return await _run_coros_in_chunks( coros, batch_size=batch_size, callback=callback ) async def _get_file(self, rpath, lpath, **kwargs): raise NotImplementedError async def _get( self, rpath, lpath, recursive=False, callback=DEFAULT_CALLBACK, maxdepth=None, **kwargs, ): """Copy file(s) to local. Copies a specific file or tree of files (if recursive=True). If lpath ends with a "/", it will be assumed to be a directory, and target files will go within. Can submit a list of paths, which may be glob-patterns and will be expanded. The get_file method will be called concurrently on a batch of files. The batch_size option can configure the amount of futures that can be executed at the same time. If it is -1, then all the files will be uploaded concurrently. The default can be set for this instance by passing "batch_size" in the constructor, or for all instances by setting the "gather_batch_size" key in ``fsspec.config.conf``, falling back to 1/8th of the system limit . """ if isinstance(lpath, list) and isinstance(rpath, list): # No need to expand paths when both source and destination # are provided as lists rpaths = rpath lpaths = lpath else: source_is_str = isinstance(rpath, str) # First check for rpath trailing slash as _strip_protocol removes it. source_not_trailing_sep = source_is_str and not trailing_sep(rpath) rpath = self._strip_protocol(rpath) rpaths = await self._expand_path( rpath, recursive=recursive, maxdepth=maxdepth ) if source_is_str and (not recursive or maxdepth is not None): # Non-recursive glob does not copy directories rpaths = [ p for p in rpaths if not (trailing_sep(p) or await self._isdir(p)) ] if not rpaths: return lpath = make_path_posix(lpath) source_is_file = len(rpaths) == 1 dest_is_dir = isinstance(lpath, str) and ( trailing_sep(lpath) or LocalFileSystem().isdir(lpath) ) exists = source_is_str and ( (has_magic(rpath) and source_is_file) or (not has_magic(rpath) and dest_is_dir and source_not_trailing_sep) ) lpaths = other_paths( rpaths, lpath, exists=exists, flatten=not source_is_str, ) [os.makedirs(os.path.dirname(lp), exist_ok=True) for lp in lpaths] batch_size = kwargs.pop("batch_size", self.batch_size) coros = [] callback.set_size(len(lpaths)) for lpath, rpath in zip(lpaths, rpaths): get_file = callback.branch_coro(self._get_file) coros.append(get_file(rpath, lpath, **kwargs)) return await _run_coros_in_chunks( coros, batch_size=batch_size, callback=callback ) async def _isfile(self, path): try: return (await self._info(path))["type"] == "file" except: # noqa: E722 return False async def _isdir(self, path): try: return (await self._info(path))["type"] == "directory" except OSError: return False async def _size(self, path): return (await self._info(path)).get("size", None) async def _sizes(self, paths, batch_size=None): batch_size = batch_size or self.batch_size return await _run_coros_in_chunks( [self._size(p) for p in paths], batch_size=batch_size ) async def _exists(self, path, **kwargs): try: await self._info(path, **kwargs) return True except FileNotFoundError: return False async def _info(self, path, **kwargs): raise NotImplementedError async def _ls(self, path, detail=True, **kwargs): raise NotImplementedError async def _walk(self, path, maxdepth=None, on_error="omit", **kwargs): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") path = self._strip_protocol(path) full_dirs = {} dirs = {} files = {} detail = kwargs.pop("detail", False) try: listing = await self._ls(path, detail=True, **kwargs) except (FileNotFoundError, OSError) as e: if on_error == "raise": raise elif callable(on_error): on_error(e) if detail: yield path, {}, {} else: yield path, [], [] return for info in listing: # each info name must be at least [path]/part , but here # we check also for names like [path]/part/ pathname = info["name"].rstrip("/") name = pathname.rsplit("/", 1)[-1] if info["type"] == "directory" and pathname != path: # do not include "self" path full_dirs[name] = pathname dirs[name] = info elif pathname == path: # file-like with same name as give path files[""] = info else: files[name] = info if detail: yield path, dirs, files else: yield path, list(dirs), list(files) if maxdepth is not None: maxdepth -= 1 if maxdepth < 1: return for d in dirs: async for _ in self._walk( full_dirs[d], maxdepth=maxdepth, detail=detail, **kwargs ): yield _ async def _glob(self, path, maxdepth=None, **kwargs): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") import re seps = (os.path.sep, os.path.altsep) if os.path.altsep else (os.path.sep,) ends_with_sep = path.endswith(seps) # _strip_protocol strips trailing slash path = self._strip_protocol(path) append_slash_to_dirname = ends_with_sep or path.endswith( tuple(sep + "**" for sep in seps) ) idx_star = path.find("*") if path.find("*") >= 0 else len(path) idx_qmark = path.find("?") if path.find("?") >= 0 else len(path) idx_brace = path.find("[") if path.find("[") >= 0 else len(path) min_idx = min(idx_star, idx_qmark, idx_brace) detail = kwargs.pop("detail", False) if not has_magic(path): if await self._exists(path, **kwargs): if not detail: return [path] else: return {path: await self._info(path, **kwargs)} else: if not detail: return [] # glob of non-existent returns empty else: return {} elif "/" in path[:min_idx]: min_idx = path[:min_idx].rindex("/") root = path[: min_idx + 1] depth = path[min_idx + 1 :].count("/") + 1 else: root = "" depth = path[min_idx + 1 :].count("/") + 1 if "**" in path: if maxdepth is not None: idx_double_stars = path.find("**") depth_double_stars = path[idx_double_stars:].count("/") + 1 depth = depth - depth_double_stars + maxdepth else: depth = None allpaths = await self._find( root, maxdepth=depth, withdirs=True, detail=True, **kwargs ) pattern = glob_translate(path + ("/" if ends_with_sep else "")) pattern = re.compile(pattern) out = { p: info for p, info in sorted(allpaths.items()) if pattern.match( p + "/" if append_slash_to_dirname and info["type"] == "directory" else p ) } if detail: return out else: return list(out) async def _du(self, path, total=True, maxdepth=None, **kwargs): sizes = {} # async for? for f in await self._find(path, maxdepth=maxdepth, **kwargs): info = await self._info(f) sizes[info["name"]] = info["size"] if total: return sum(sizes.values()) else: return sizes async def _find(self, path, maxdepth=None, withdirs=False, **kwargs): path = self._strip_protocol(path) out = {} detail = kwargs.pop("detail", False) # Add the root directory if withdirs is requested # This is needed for posix glob compliance if withdirs and path != "" and await self._isdir(path): out[path] = await self._info(path) # async for? async for _, dirs, files in self._walk(path, maxdepth, detail=True, **kwargs): if withdirs: files.update(dirs) out.update({info["name"]: info for name, info in files.items()}) if not out and (await self._isfile(path)): # walk works on directories, but find should also return [path] # when path happens to be a file out[path] = {} names = sorted(out) if not detail: return names else: return {name: out[name] for name in names} async def _expand_path(self, path, recursive=False, maxdepth=None): if maxdepth is not None and maxdepth < 1: raise ValueError("maxdepth must be at least 1") if isinstance(path, str): out = await self._expand_path([path], recursive, maxdepth) else: out = set() path = [self._strip_protocol(p) for p in path] for p in path: # can gather here if has_magic(p): bit = set(await self._glob(p, maxdepth=maxdepth)) out |= bit if recursive: # glob call above expanded one depth so if maxdepth is defined # then decrement it in expand_path call below. If it is zero # after decrementing then avoid expand_path call. if maxdepth is not None and maxdepth <= 1: continue out |= set( await self._expand_path( list(bit), recursive=recursive, maxdepth=maxdepth - 1 if maxdepth is not None else None, ) ) continue elif recursive: rec = set(await self._find(p, maxdepth=maxdepth, withdirs=True)) out |= rec if p not in out and (recursive is False or (await self._exists(p))): # should only check once, for the root out.add(p) if not out: raise FileNotFoundError(path) return sorted(out) async def _mkdir(self, path, create_parents=True, **kwargs): pass # not necessary to implement, may not have directories async def _makedirs(self, path, exist_ok=False): pass # not necessary to implement, may not have directories async def open_async(self, path, mode="rb", **kwargs): if "b" not in mode or kwargs.get("compression"): raise ValueError raise NotImplementedError def mirror_sync_methods(obj): """Populate sync and async methods for obj For each method will create a sync version if the name refers to an async method (coroutine) and there is no override in the child class; will create an async method for the corresponding sync method if there is no implementation. Uses the methods specified in - async_methods: the set that an implementation is expected to provide - default_async_methods: that can be derived from their sync version in AbstractFileSystem - AsyncFileSystem: async-specific default coroutines """ from fsspec import AbstractFileSystem for method in async_methods + dir(AsyncFileSystem): if not method.startswith("_"): continue smethod = method[1:] if private.match(method): isco = inspect.iscoroutinefunction(getattr(obj, method, None)) unsync = getattr(getattr(obj, smethod, False), "__func__", None) is_default = unsync is getattr(AbstractFileSystem, smethod, "") if isco and is_default: mth = sync_wrapper(getattr(obj, method), obj=obj) setattr(obj, smethod, mth) if not mth.__doc__: mth.__doc__ = getattr( getattr(AbstractFileSystem, smethod, None), "__doc__", "" )
AsyncFileSystem
python
redis__redis-py
redis/auth/token.py
{ "start": 128, "end": 579 }
class ____(ABC): @abstractmethod def is_expired(self) -> bool: pass @abstractmethod def ttl(self) -> float: pass @abstractmethod def try_get(self, key: str) -> str: pass @abstractmethod def get_value(self) -> str: pass @abstractmethod def get_expires_at_ms(self) -> float: pass @abstractmethod def get_received_at_ms(self) -> float: pass
TokenInterface
python
pytorch__pytorch
torch/testing/_comparison.py
{ "start": 12668, "end": 12835 }
class ____(Exception): # noqa: B903 """Exception to be raised during the construction of a :class:`Pair` in case it doesn't support the inputs."""
UnsupportedInputs
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 259368, "end": 262777 }
class ____(TestPydap): @contextlib.contextmanager def create_dap2_datasets(self, **kwargs): # in pydap 3.5.0, urls defaults to dap2. url = "http://test.opendap.org/opendap/data/nc/bears.nc" actual = open_dataset(url, engine="pydap", **kwargs) # pydap <3.5.6 converts to unicode dtype=|U. Not what # xarray expects. Thus force to bytes dtype. pydap >=3.5.6 # does not convert to unicode. https://github.com/pydap/pydap/issues/510 actual["bears"].values = actual["bears"].values.astype("S") with open_example_dataset("bears.nc") as expected: yield actual, expected def output_grid_deprecation_warning_dap2dataset(self): with pytest.warns(DeprecationWarning, match="`output_grid` is deprecated"): with self.create_dap2_datasets(output_grid=True) as (actual, expected): assert_equal(actual, expected) def create_dap4_dataset(self, **kwargs): url = "dap4://test.opendap.org/opendap/data/nc/bears.nc" actual = open_dataset(url, engine="pydap", **kwargs) with open_example_dataset("bears.nc") as expected: # workaround to restore string which is converted to byte # only needed for pydap <3.5.6 https://github.com/pydap/pydap/issues/510 expected["bears"].values = expected["bears"].values.astype("S") yield actual, expected def test_session(self) -> None: from requests import Session session = Session() # blank requests.Session object with mock.patch("pydap.client.open_url") as mock_func: xr.backends.PydapDataStore.open("http://test.url", session=session) mock_func.assert_called_with( url="http://test.url", application=None, session=session, output_grid=False, timeout=120, verify=True, user_charset=None, ) @requires_pydap @network @pytest.mark.parametrize("protocol", ["dap2", "dap4"]) def test_batchdap4_downloads(tmpdir, protocol) -> None: """Test that in dap4, all dimensions are downloaded at once""" import pydap from pydap.net import create_session _version_ = Version(pydap.__version__) # Create a session with pre-set params in pydap backend, to cache urls cache_name = tmpdir / "debug" session = create_session(use_cache=True, cache_kwargs={"cache_name": cache_name}) session.cache.clear() url = "https://test.opendap.org/opendap/hyrax/data/nc/coads_climatology.nc" ds = open_dataset( url.replace("https", protocol), session=session, engine="pydap", decode_times=False, ) if protocol == "dap4": if _version_ > Version("3.5.5"): # total downloads are: # 1 dmr + 1 dap (all dimensions at once) assert len(session.cache.urls()) == 2 # now load the rest of the variables ds.load() # each non-dimension array is downloaded with an individual https requests assert len(session.cache.urls()) == 2 + 4 else: assert len(session.cache.urls()) == 4 ds.load() assert len(session.cache.urls()) == 4 + 4 elif protocol == "dap2": # das + dds + 3 dods urls for dimensions alone assert len(session.cache.urls()) == 5
TestPydapOnline
python
plotly__plotly.py
plotly/graph_objs/indicator/_delta.py
{ "start": 233, "end": 8798 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator" _path_str = "indicator.delta" _valid_props = { "decreasing", "font", "increasing", "position", "prefix", "reference", "relative", "suffix", "valueformat", } @property def decreasing(self): """ The 'decreasing' property is an instance of Decreasing that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.delta.Decreasing` - A dict of string/value properties that will be passed to the Decreasing constructor Returns ------- plotly.graph_objs.indicator.delta.Decreasing """ return self["decreasing"] @decreasing.setter def decreasing(self, val): self["decreasing"] = val @property def font(self): """ Set the font used to display the delta The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.delta.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.indicator.delta.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def increasing(self): """ The 'increasing' property is an instance of Increasing that may be specified as: - An instance of :class:`plotly.graph_objs.indicator.delta.Increasing` - A dict of string/value properties that will be passed to the Increasing constructor Returns ------- plotly.graph_objs.indicator.delta.Increasing """ return self["increasing"] @increasing.setter def increasing(self, val): self["increasing"] = val @property def position(self): """ Sets the position of delta with respect to the number. The 'position' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'bottom', 'left', 'right'] Returns ------- Any """ return self["position"] @position.setter def position(self, val): self["position"] = val @property def prefix(self): """ Sets a prefix appearing before the delta. The 'prefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["prefix"] @prefix.setter def prefix(self, val): self["prefix"] = val @property def reference(self): """ Sets the reference value to compute the delta. By default, it is set to the current value. The 'reference' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["reference"] @reference.setter def reference(self, val): self["reference"] = val @property def relative(self): """ Show relative change The 'relative' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["relative"] @relative.setter def relative(self, val): self["relative"] = val @property def suffix(self): """ Sets a suffix appearing next to the delta. The 'suffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["suffix"] @suffix.setter def suffix(self, val): self["suffix"] = val @property def valueformat(self): """ Sets the value formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. The 'valueformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["valueformat"] @valueformat.setter def valueformat(self, val): self["valueformat"] = val @property def _prop_descriptions(self): return """\ decreasing :class:`plotly.graph_objects.indicator.delta.Decreasing ` instance or dict with compatible properties font Set the font used to display the delta increasing :class:`plotly.graph_objects.indicator.delta.Increasing ` instance or dict with compatible properties position Sets the position of delta with respect to the number. prefix Sets a prefix appearing before the delta. reference Sets the reference value to compute the delta. By default, it is set to the current value. relative Show relative change suffix Sets a suffix appearing next to the delta. valueformat Sets the value formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. """ def __init__( self, arg=None, decreasing=None, font=None, increasing=None, position=None, prefix=None, reference=None, relative=None, suffix=None, valueformat=None, **kwargs, ): """ Construct a new Delta object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.Delta` decreasing :class:`plotly.graph_objects.indicator.delta.Decreasing ` instance or dict with compatible properties font Set the font used to display the delta increasing :class:`plotly.graph_objects.indicator.delta.Increasing ` instance or dict with compatible properties position Sets the position of delta with respect to the number. prefix Sets a prefix appearing before the delta. reference Sets the reference value to compute the delta. By default, it is set to the current value. relative Show relative change suffix Sets a suffix appearing next to the delta. valueformat Sets the value formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. Returns ------- Delta """ super().__init__("delta") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.indicator.Delta constructor must be a dict or an instance of :class:`plotly.graph_objs.indicator.Delta`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("decreasing", arg, decreasing) self._set_property("font", arg, font) self._set_property("increasing", arg, increasing) self._set_property("position", arg, position) self._set_property("prefix", arg, prefix) self._set_property("reference", arg, reference) self._set_property("relative", arg, relative) self._set_property("suffix", arg, suffix) self._set_property("valueformat", arg, valueformat) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Delta
python
pytorch__pytorch
torch/_functorch/_aot_autograd/aot_autograd_result.py
{ "start": 10228, "end": 10950 }
class ____: fn: Callable[[dict[Any, Any], str], torch.nn.Module] args: tuple[Any, ...] def __init__(self, gm: torch.fx.GraphModule): self.fn, self.args = gm.__reduce__() def deserialize(self) -> torch.fx.GraphModule: gm = self.fn(*self.args) assert isinstance(gm, torch.fx.GraphModule) return gm def serialize_graph_module(gm: torch.fx.GraphModule) -> SerializedGraphModule: # NOTE: mutates the graph module gm.meta = {} for node in gm.graph.nodes: node.meta = {} return SerializedGraphModule(gm) TForward = TypeVar("TForward", bound=InductorOutput) TBackward = TypeVar("TBackward", bound=GenericCompiledBackward) @dataclass
SerializedGraphModule
python
apache__airflow
devel-common/src/tests_common/test_utils/perf/perf_kit/repeat_and_time.py
{ "start": 910, "end": 2190 }
class ____: """Timing result.""" def __init__(self): self.start_time = 0 self.end_time = 0 self.value = 0 @contextlib.contextmanager def timing(repeat_count: int = 1): """ Measure code execution time. :param repeat_count: If passed, the result will be divided by the value. """ result = TimingResult() result.start_time = time.monotonic() try: yield result finally: end_time = time.monotonic() diff = (end_time - result.start_time) * 1000.0 result.end_time = end_time if repeat_count == 1: result.value = diff print(f"Loop time: {diff:.3f} ms") else: average_time = diff / repeat_count result.value = average_time print(f"Average time: {average_time:.3f} ms") def repeat(repeat_count=5): """ Decorate functions that repeats many times. :param repeat_count: The repeat count """ def repeat_decorator(f): @functools.wraps(f) def wrap(*args, **kwargs): last_result = None for _ in range(repeat_count): last_result = f(*args, **kwargs) return last_result return wrap return repeat_decorator
TimingResult
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 3747, "end": 3907 }
class ____(models.Model): session = models.CharField(max_length=200, null=True, default=None) class Meta: abstract = True
SessionsHistoricalModel
python
getsentry__sentry
tests/snuba/tagstore/test_tagstore_backend.py
{ "start": 52097, "end": 54048 }
class ____(TestCase, SnubaTestCase): def setUp(self) -> None: super().setUp() self.ts = SnubaTagStorage() def run_test(self, query, expected_releases, environment=None, project=None): if project is None: project = self.project assert list( self.ts.get_tag_value_paginator( project.id, environment.id if environment else None, RELEASE_STAGE_ALIAS, query=query, ).get_result(10) ) == [ TagValue( key=RELEASE_STAGE_ALIAS, value=r.version, times_seen=None, first_seen=None, last_seen=None, ) for r in expected_releases ] def test_release_stage(self) -> None: replaced_release = self.create_release( version="replaced_release", environments=[self.environment], adopted=timezone.now(), unadopted=timezone.now(), ) adopted_release = self.create_release( version="adopted_release", environments=[self.environment], adopted=timezone.now() ) not_adopted_release = self.create_release( version="not_adopted_release", environments=[self.environment] ) env_2 = self.create_environment() project_2 = self.create_project() self.run_test(ReleaseStages.ADOPTED, [adopted_release], environment=self.environment) self.run_test( ReleaseStages.LOW_ADOPTION, [not_adopted_release], environment=self.environment ) self.run_test(ReleaseStages.REPLACED, [replaced_release], environment=self.environment) self.run_test(ReleaseStages.ADOPTED, [], environment=env_2) self.run_test(ReleaseStages.ADOPTED, [], project=project_2, environment=self.environment)
GetTagValuePaginatorForProjectsReleaseStageTest
python
getsentry__sentry
src/sentry/api/endpoints/organization_artifactbundle_assemble.py
{ "start": 838, "end": 7856 }
class ____(OrganizationReleasesBaseEndpoint): owner = ApiOwner.OWNERS_INGEST publish_status = { "POST": ApiPublishStatus.PRIVATE, } def post(self, request: Request, organization) -> Response: """ Assembles an artifact bundle and stores the debug ids in the database. """ with sentry_sdk.start_span(op="artifact_bundle.assemble"): schema = { "type": "object", "properties": { # The version pattern has been extracted from the url definition of OrganizationReleaseAssembleEndpoint. "version": {"type": "string", "pattern": "^[^/]+$"}, "dist": {"type": "string"}, "projects": {"type": "array", "items": {"type": "string"}}, "checksum": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, "chunks": { "type": "array", "items": {"type": "string", "pattern": "^[0-9a-f]{40}$"}, }, }, "required": ["checksum", "chunks", "projects"], "additionalProperties": False, } error_messages = { "version": 'The version field cannot be empty and cannot contain any "/" characters.', "dist": "The dist field must be a string.", "projects": "The projects field is required and must be provided as an array of strings.", "checksum": "The checksum field is required and must be a 40-character hexadecimal string.", "chunks": "The chunks field is required and must be provided as an array of 40-character hexadecimal strings.", } try: data = orjson.loads(request.body) jsonschema.validate(data, schema) except jsonschema.ValidationError as e: error_message = e.message # Get the field from the path if available if e.path: if field := e.path[0]: error_message = error_messages.get(str(field), error_message) return Response({"error": error_message}, status=400) except Exception: return Response({"error": "Invalid json body"}, status=400) input_projects = data.get("projects", []) if len(input_projects) == 0: return Response({"error": "You need to specify at least one project"}, status=400) input_project_slug = set() input_project_id = set() for project in input_projects: # IDs are always numeric, slugs cannot be numeric if str(project).isdecimal(): input_project_id.add(project) else: input_project_slug.add(project) with sentry_sdk.start_span(op="artifact_bundle.assemble.find_projects"): project_ids = Project.objects.filter( (Q(id__in=input_project_id) | Q(slug__in=input_project_slug)), organization=organization, status=ObjectStatus.ACTIVE, ).values_list("id", flat=True) if len(project_ids) != len(input_projects): return Response({"error": "One or more projects are invalid"}, status=400) with sentry_sdk.start_span(op="artifact_bundle.assemble.check_release_permission"): if not self.has_release_permission( request, organization, project_ids=set(project_ids) ): raise ResourceDoesNotExist checksum = data.get("checksum") chunks = data.get("chunks", []) # We check if all requested chunks have been uploaded. missing_chunks = find_missing_chunks(organization.id, set(chunks)) # In case there are some missing chunks, we will tell the client which chunks we require. if missing_chunks: return Response( { "state": ChunkFileState.NOT_FOUND, "missingChunks": missing_chunks, } ) # We want to check the current state of the assemble status. state, detail = get_assemble_status( AssembleTask.ARTIFACT_BUNDLE, organization.id, checksum ) if state == ChunkFileState.OK: return Response({"state": state, "detail": None, "missingChunks": []}, status=200) elif state is not None: # In case we have some state into the cache, we will not perform any assembly task again and rather we will # return. This might cause issues with CLI because it might have uploaded the same bundle chunks two times # in a row but only the first call the assemble started the assembly task, all subsequent calls will get # an assemble status. return Response({"state": state, "detail": detail, "missingChunks": []}) # There is neither a known file nor a cached state, so we will # have to create a new file. Assure that there are checksums. # If not, we assume this is a poll and report NOT_FOUND if not chunks: return Response( {"state": ChunkFileState.NOT_FOUND, "missingChunks": []}, status=200 ) set_assemble_status( AssembleTask.ARTIFACT_BUNDLE, organization.id, checksum, ChunkFileState.CREATED ) from sentry.tasks.assemble import assemble_artifacts version = data.get("version") dist = data.get("dist") if not version and dist: return Response( {"error": "You need to specify a release together with a dist"}, status=400 ) with sentry_sdk.start_span(op="artifact_bundle.assemble.start_assemble_artifacts"): assemble_artifacts.apply_async( kwargs={ "org_id": organization.id, "project_ids": list(project_ids), # We don't perform any validation of the version, since the user might bind a bundle to a specific # release version without actually having created the release object itself. "version": version, "dist": dist, "checksum": checksum, "chunks": chunks, } ) if is_org_auth_token_auth(request.auth): update_org_auth_token_last_used(request.auth, list(project_ids)) return Response({"state": ChunkFileState.CREATED, "missingChunks": []}, status=200)
OrganizationArtifactBundleAssembleEndpoint
python
django-import-export__django-import-export
tests/core/tests/test_base_formats.py
{ "start": 2017, "end": 2291 }
class ____(TestCase): def setUp(self): self.format = base_formats.TablibFormat() def test_get_format_for_undefined_TABLIB_MODULE_raises_AttributeError(self): with self.assertRaises(AttributeError): self.format.get_format()
TablibFormatTest
python
django__django
tests/check_framework/test_caches.py
{ "start": 5144, "end": 6218 }
class ____(SimpleTestCase): def test_absolute_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": pathlib.Path.cwd() / "cache", }, } ): self.assertEqual(check_file_based_cache_is_absolute(None), []) def test_relative_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "cache", }, } ): self.assertEqual( check_file_based_cache_is_absolute(None), [ Warning( "Your 'default' cache LOCATION path is relative. Use an " "absolute path instead.", id="caches.W003", ), ], )
CheckCacheAbsolutePath
python
doocs__leetcode
solution/2000-2099/2068.Check Whether Two Strings are Almost Equivalent/Solution.py
{ "start": 0, "end": 216 }
class ____: def checkAlmostEquivalent(self, word1: str, word2: str) -> bool: cnt = Counter(word1) for c in word2: cnt[c] -= 1 return all(abs(x) <= 3 for x in cnt.values())
Solution
python
PyCQA__isort
tests/unit/test_regressions.py
{ "start": 40866, "end": 40894 }
class ____: ... @final
Foo
python
nedbat__coveragepy
tests/test_arcs.py
{ "start": 12282, "end": 23941 }
class ____(CoverageTest): """Arc-measuring tests involving loops.""" def test_loop(self) -> None: self.check_coverage( """\ for i in range(10): a = i assert a == 9 """, branchz="12 13", branchz_missing="", ) self.check_coverage( """\ a = -1 for i in range(0): a = i assert a == -1 """, branchz="23 24", branchz_missing="23", ) def test_nested_loop(self) -> None: self.check_coverage( """\ for i in range(3): for j in range(3): a = i + j assert a == 4 """, branchz="12 14 23 21", branchz_missing="", ) def test_break(self) -> None: self.check_coverage( """\ for i in range(10): a = i break # 3 a = 99 assert a == 0 # 5 """, branchz="12 15", branchz_missing="15", ) def test_continue(self) -> None: self.check_coverage( """\ for i in range(10): a = i continue # 3 a = 99 assert a == 9 # 5 """, branchz="12 15", branchz_missing="", ) def test_nested_breaks(self) -> None: self.check_coverage( """\ for i in range(3): for j in range(3): a = i + j break # 4 if i == 2: break assert a == 2 and i == 2 # 7 """, branchz="12 17 23 25 51 56", branchz_missing="17 25", ) def test_if_1(self) -> None: self.check_coverage( """\ a = 1 if not not 1: a = 3 else: a = 5 assert a == 3 """, lines=[1, 2, 3, 6], branchz="", branchz_missing="", ) def test_while_1(self) -> None: # With "while 1", the loop knows it's constant. self.check_coverage( """\ a, i = 1, 0 while 1: if i >= 3: a = 4 break i += 1 assert a == 4 and i == 3 """, branchz="34 36", branchz_missing="", ) def test_while_true(self) -> None: self.check_coverage( """\ a, i = 1, 0 while True: if i >= 3: a = 4 break i += 1 assert a == 4 and i == 3 """, lines=[1, 2, 3, 4, 5, 6, 7], branchz="34 36", branchz_missing="", ) def test_while_false(self) -> None: self.check_coverage( """\ a, i = 1, 0 while False: 1/0 assert a == 1 and i == 0 """, lines=[1, 2, 4], branchz="", branchz_missing="", ) def test_while_not_false(self) -> None: self.check_coverage( """\ a, i = 1, 0 while not False: if i >= 3: a = 4 break i += 1 assert a == 4 and i == 3 """, branchz="34 36", branchz_missing="", ) def test_zero_coverage_while_loop(self) -> None: # https://github.com/coveragepy/coveragepy/issues/502 self.make_file("main.py", "print('done')") self.make_file( "zero.py", """\ def method(self): while True: return 1 """, ) cov = coverage.Coverage(source=["."], branch=True) self.start_import_stop(cov, "main") assert self.stdout() == "done\n" expected = "zero.py 3 3 0 0 0% 1-3" report = self.get_report(cov, show_missing=True) squeezed = self.squeezed_lines(report) assert expected in squeezed[3] def test_bug_496_continue_in_constant_while(self) -> None: # https://github.com/coveragepy/coveragepy/issues/496 self.check_coverage( """\ up = iter('ta') while True: char = next(up) if char == 't': continue i = "line 6" break """, branchz="45 46", branchz_missing="", ) def test_missing_while_body(self) -> None: self.check_coverage( """\ a = 3; b = 0 if 0: while a > 0: a -= 1 assert a == 3 and b == 0 """, branchz="", branchz_missing="", ) def test_for_if_else_for(self) -> None: self.check_coverage( """\ def branches_2(l): if l: for e in l: a = 4 else: a = 6 def branches_3(l): for x in l: if x: for e in l: a = 12 else: a = 14 branches_2([0,1]) branches_3([0,1]) """, branchz="23 26 34 3. 9A 9-8 AB AE BC B9", branchz_missing="26", ) def test_for_else(self) -> None: self.check_coverage( """\ def forelse(seq): for n in seq: if n > 5: break else: print('None of the values were greater than 5') print('Done') forelse([1,2]) """, branchz="23 26 34 32", branchz_missing="34", ) self.check_coverage( """\ def forelse(seq): for n in seq: if n > 5: break else: print('None of the values were greater than 5') print('Done') forelse([1,6]) """, branchz="23 26 34 32", branchz_missing="26", ) def test_split_for(self) -> None: self.check_coverage( """\ a = 0 for (i ) in [1,2,3,4,5]: a += i assert a == 15 """, lines=[1, 2, 4, 5], branchz="24 25", ) def test_while_else(self) -> None: self.check_coverage( """\ def whileelse(seq): while seq: n = seq.pop() if n > 4: break else: n = 99 return n assert whileelse([1, 2]) == 99 """, branchz="23 27 45 42", branchz_missing="45", ) self.check_coverage( """\ def whileelse(seq): while seq: n = seq.pop() if n > 4: break else: n = 99 return n assert whileelse([1, 5]) == 5 """, branchz="23 27 45 42", branchz_missing="27 42", ) def test_confusing_for_loop_bug_175(self) -> None: self.check_coverage( """\ o = [(1,2), (3,4)] o = [a for a in o] for tup in o: x = tup[0] y = tup[1] """, branchz="34 3.", branchz_missing="", ) self.check_coverage( """\ o = [(1,2), (3,4)] for tup in [a for a in o]: x = tup[0] y = tup[1] """, branchz="23 2.", branchz_missing="", ) def test_incorrect_loop_exit_bug_1175(self) -> None: self.check_coverage( """\ def wrong_loop(x): if x: for i in [3, 33]: print(i+4) else: pass wrong_loop(8) """, branchz="23 26 34 3.", branchz_missing="26", ) # https://bugs.python.org/issue44672 def test_incorrect_if_bug_1175(self) -> None: self.check_coverage( """\ def wrong_loop(x): if x: if x: print(4) else: pass wrong_loop(8) """, branchz="23 26 34 3.", branchz_missing="26 3.", ) def test_generator_expression(self) -> None: # Generator expression: self.check_coverage( """\ o = ((1,2), (3,4)) o = (a for a in o) for tup in o: x = tup[0] y = tup[1] """, branchz="34 3.", branchz_missing="", ) def test_generator_expression_another_way(self) -> None: # https://bugs.python.org/issue44450 # Generator expression: self.check_coverage( """\ o = ((1,2), (3,4)) o = (a for a in o) for tup in o: x = tup[0] y = tup[1] """, branchz="56 5.", branchz_missing="", ) def test_other_comprehensions(self) -> None: # Set comprehension: self.check_coverage( """\ o = ((1,2), (3,4)) o = {a for a in o} for tup in o: x = tup[0] y = tup[1] """, branchz="34 3.", branchz_missing="", ) # Dict comprehension: self.check_coverage( """\ o = ((1,2), (3,4)) o = {a:1 for a in o} for tup in o: x = tup[0] y = tup[1] """, branchz="34 3.", branchz_missing="", ) def test_multiline_dict_comp(self) -> None: # Multiline dict comp: self.check_coverage( """\ # comment d = \\ { i: str(i) for i in range(9) } x = 11 """, branchz="", branchz_missing="", ) # Multi dict comp: self.check_coverage( """\ # comment d = \\ { (i, j): str(i+j) for i in range(9) for j in range(13) } x = 15 """, branchz="", branchz_missing="", )
LoopArcTest
python
django__django
tests/admin_widgets/tests.py
{ "start": 39790, "end": 40084 }
class ____(AdminSeleniumTestCase): available_apps = ["admin_widgets"] + AdminSeleniumTestCase.available_apps def setUp(self): self.u1 = User.objects.create_superuser( username="super", password="secret", email="super@example.com" )
AdminWidgetSeleniumTestCase
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_dataproc.py
{ "start": 6282, "end": 8651 }
class ____: def create_batch(self, state: int): batch = mock.Mock() batch.state = mock.Mock() batch.state = state return batch @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_succeeded(self, mock_hook): batch = self.create_batch(Batch.State.SUCCEEDED) mock_hook.return_value.get_batch.return_value = batch sensor = DataprocBatchSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, batch_id="batch_id", poke_interval=10, gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) ret = sensor.poke(context={}) mock_hook.return_value.get_batch.assert_called_once_with( batch_id="batch_id", region=GCP_LOCATION, project_id=GCP_PROJECT ) assert ret @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_cancelled( self, mock_hook, ): batch = self.create_batch(Batch.State.CANCELLED) mock_hook.return_value.get_batch.return_value = batch sensor = DataprocBatchSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, batch_id="batch_id", gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) with pytest.raises(AirflowException, match="Batch was cancelled."): sensor.poke(context={}) mock_hook.return_value.get_batch.assert_called_once_with( batch_id="batch_id", region=GCP_LOCATION, project_id=GCP_PROJECT ) @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_error( self, mock_hook, ): batch = self.create_batch(Batch.State.FAILED) mock_hook.return_value.get_batch.return_value = batch sensor = DataprocBatchSensor( task_id=TASK_ID, region=GCP_LOCATION, project_id=GCP_PROJECT, batch_id="batch_id", gcp_conn_id=GCP_CONN_ID, timeout=TIMEOUT, ) with pytest.raises(AirflowException, match="Batch failed"): sensor.poke(context={}) mock_hook.return_value.get_batch.assert_called_once_with( batch_id="batch_id", region=GCP_LOCATION, project_id=GCP_PROJECT )
TestDataprocBatchSensor
python
pytorch__pytorch
torch/_inductor/autotune_process.py
{ "start": 17334, "end": 18515 }
class ____: def do_bench( self, fn, *input_tensors: torch.Tensor, out: Optional[torch.Tensor] = None, ) -> float: device_idx_set = OrderedSet( tensor.device.index for tensor in [*input_tensors, out] if isinstance(tensor, torch.Tensor) and is_gpu(tensor.device.type) and tensor.device.index is not None ) assert len(device_idx_set) <= 1, f"Can not mix devices {device_idx_set}" device_type = next( ( tensor.device.type for tensor in input_tensors if is_gpu(tensor.device.type) ), "cuda", ) device_interface = get_interface_for_device(device_type) if len(device_idx_set) == 1: device_idx = next(iter(device_idx_set)) else: device_idx = device_interface.current_device() with device_interface.device(device_idx): # type: ignore[attr-defined] res = benchmarker.benchmark_gpu(fn) device_interface.synchronize() # shake out any CUDA errors return res
GPUDeviceBenchmarkMixin
python
scikit-learn__scikit-learn
sklearn/linear_model/_stochastic_gradient.py
{ "start": 2387, "end": 17141 }
class ____(SparseCoefMixin, BaseEstimator, metaclass=ABCMeta): """Base class for SGD classification and regression.""" _parameter_constraints: dict = { "fit_intercept": ["boolean"], "max_iter": [Interval(Integral, 1, None, closed="left")], "tol": [Interval(Real, 0, None, closed="left"), None], "shuffle": ["boolean"], "verbose": ["verbose"], "random_state": ["random_state"], "warm_start": ["boolean"], "average": [Interval(Integral, 0, None, closed="neither"), "boolean"], "eta0": [Interval(Real, 0, None, closed="neither")], } def __init__( self, loss, *, penalty="l2", alpha=0.0001, l1_ratio=0.15, fit_intercept=True, max_iter=1000, tol=1e-3, shuffle=True, verbose=0, epsilon=0.1, random_state=None, learning_rate="optimal", eta0=0.01, power_t=0.5, early_stopping=False, validation_fraction=0.1, n_iter_no_change=5, warm_start=False, average=False, ): self.loss = loss self.penalty = penalty self.learning_rate = learning_rate self.epsilon = epsilon self.alpha = alpha self.l1_ratio = l1_ratio self.fit_intercept = fit_intercept self.shuffle = shuffle self.random_state = random_state self.verbose = verbose self.eta0 = eta0 self.power_t = power_t self.early_stopping = early_stopping self.validation_fraction = validation_fraction self.n_iter_no_change = n_iter_no_change self.warm_start = warm_start self.average = average self.max_iter = max_iter self.tol = tol @abstractmethod def fit(self, X, y): """Fit model.""" def _more_validate_params(self, for_partial_fit=False): """Validate input params.""" if self.early_stopping and for_partial_fit: raise ValueError("early_stopping should be False with partial_fit") if self.learning_rate == "optimal" and self.alpha == 0: raise ValueError( "alpha must be > 0 since " "learning_rate is 'optimal'. alpha is used " "to compute the optimal learning rate." ) # TODO: Consider whether pa1 and pa2 could also work for other losses. if self.learning_rate in ("pa1", "pa2"): if is_classifier(self): if self.loss != "hinge": msg = ( f"Learning rate '{self.learning_rate}' only works with loss " "'hinge'." ) raise ValueError(msg) elif self.loss != "epsilon_insensitive": msg = ( f"Learning rate '{self.learning_rate}' only works with loss " "'epsilon_insensitive'." ) raise ValueError(msg) if self.penalty == "elasticnet" and self.l1_ratio is None: raise ValueError("l1_ratio must be set when penalty is 'elasticnet'") # raises ValueError if not registered self._get_penalty_type(self.penalty) self._get_learning_rate_type(self.learning_rate) def _get_l1_ratio(self): if self.l1_ratio is None: # plain_sgd expects a float. Any value is fine since at this point # penalty can't be "elsaticnet" so l1_ratio is not used. return 0.0 return self.l1_ratio def _get_loss_function(self, loss): """Get concrete ``LossFunction`` object for str ``loss``.""" loss_ = self.loss_functions[loss] loss_class, args = loss_[0], loss_[1:] if loss in ("huber", "epsilon_insensitive", "squared_epsilon_insensitive"): args = (self.epsilon,) return loss_class(*args) def _get_learning_rate_type(self, learning_rate): return LEARNING_RATE_TYPES[learning_rate] def _get_penalty_type(self, penalty): penalty = str(penalty).lower() return PENALTY_TYPES[penalty] def _allocate_parameter_mem( self, n_classes, n_features, input_dtype, coef_init=None, intercept_init=None, one_class=0, ): """Allocate mem for parameters; initialize if provided.""" if n_classes > 2: # allocate coef_ for multi-class if coef_init is not None: coef_init = np.asarray(coef_init, dtype=input_dtype, order="C") if coef_init.shape != (n_classes, n_features): raise ValueError("Provided ``coef_`` does not match dataset. ") self.coef_ = coef_init else: self.coef_ = np.zeros( (n_classes, n_features), dtype=input_dtype, order="C" ) # allocate intercept_ for multi-class if intercept_init is not None: intercept_init = np.asarray( intercept_init, order="C", dtype=input_dtype ) if intercept_init.shape != (n_classes,): raise ValueError("Provided intercept_init does not match dataset.") self.intercept_ = intercept_init else: self.intercept_ = np.zeros(n_classes, dtype=input_dtype, order="C") else: # allocate coef_ if coef_init is not None: coef_init = np.asarray(coef_init, dtype=input_dtype, order="C") coef_init = coef_init.ravel() if coef_init.shape != (n_features,): raise ValueError("Provided coef_init does not match dataset.") self.coef_ = coef_init else: self.coef_ = np.zeros(n_features, dtype=input_dtype, order="C") # allocate intercept_ if intercept_init is not None: intercept_init = np.asarray(intercept_init, dtype=input_dtype) if intercept_init.shape != (1,) and intercept_init.shape != (): raise ValueError("Provided intercept_init does not match dataset.") if one_class: self.offset_ = intercept_init.reshape( 1, ) else: self.intercept_ = intercept_init.reshape( 1, ) else: if one_class: self.offset_ = np.zeros(1, dtype=input_dtype, order="C") else: self.intercept_ = np.zeros(1, dtype=input_dtype, order="C") # initialize average parameters if self.average > 0: self._standard_coef = self.coef_ self._average_coef = np.zeros( self.coef_.shape, dtype=input_dtype, order="C" ) if one_class: self._standard_intercept = 1 - self.offset_ else: self._standard_intercept = self.intercept_ self._average_intercept = np.zeros( self._standard_intercept.shape, dtype=input_dtype, order="C" ) def _make_validation_split(self, y, sample_mask): """Split the dataset between training set and validation set. Parameters ---------- y : ndarray of shape (n_samples, ) Target values. sample_mask : ndarray of shape (n_samples, ) A boolean array indicating whether each sample should be included for validation set. Returns ------- validation_mask : ndarray of shape (n_samples, ) Equal to True on the validation set, False on the training set. """ n_samples = y.shape[0] validation_mask = np.zeros(n_samples, dtype=np.bool_) if not self.early_stopping: # use the full set for training, with an empty validation set return validation_mask if is_classifier(self): splitter_type = StratifiedShuffleSplit else: splitter_type = ShuffleSplit cv = splitter_type( test_size=self.validation_fraction, random_state=self.random_state ) idx_train, idx_val = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) if not np.any(sample_mask[idx_val]): raise ValueError( "The sample weights for validation set are all zero, consider using a" " different random state." ) if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: raise ValueError( "Splitting %d samples into a train set and a validation set " "with validation_fraction=%r led to an empty set (%d and %d " "samples). Please either change validation_fraction, increase " "number of samples, or disable early_stopping." % ( n_samples, self.validation_fraction, idx_train.shape[0], idx_val.shape[0], ) ) validation_mask[idx_val] = True return validation_mask def _make_validation_score_cb( self, validation_mask, X, y, sample_weight, classes=None ): if not self.early_stopping: return None return _ValidationScoreCallback( self, X[validation_mask], y[validation_mask], sample_weight[validation_mask], classes=classes, ) def _prepare_fit_binary(est, y, i, input_dtype, label_encode=True): """Initialization for fit_binary. Returns y, coef, intercept, average_coef, average_intercept. """ y_i = np.ones(y.shape, dtype=input_dtype, order="C") if label_encode: # y in {0, 1} y_i[y != est.classes_[i]] = 0.0 else: # y in {-1, +1} y_i[y != est.classes_[i]] = -1.0 average_intercept = 0 average_coef = None if len(est.classes_) == 2: if not est.average: coef = est.coef_.ravel() intercept = est.intercept_[0] else: coef = est._standard_coef.ravel() intercept = est._standard_intercept[0] average_coef = est._average_coef.ravel() average_intercept = est._average_intercept[0] else: if not est.average: coef = est.coef_[i] intercept = est.intercept_[i] else: coef = est._standard_coef[i] intercept = est._standard_intercept[i] average_coef = est._average_coef[i] average_intercept = est._average_intercept[i] return y_i, coef, intercept, average_coef, average_intercept def fit_binary( est, i, X, y, alpha, learning_rate, max_iter, pos_weight, neg_weight, sample_weight, validation_mask=None, random_state=None, ): """Fit a single binary classifier. The i'th class is considered the "positive" class. Parameters ---------- est : Estimator object The estimator to fit i : int Index of the positive class X : numpy array or sparse matrix of shape [n_samples,n_features] Training data y : numpy array of shape [n_samples, ] Target values alpha : float The regularization parameter learning_rate : str The learning rate. Accepted values are 'constant', 'optimal', 'invscaling', 'pa1' and 'pa2'. max_iter : int The maximum number of iterations (epochs) pos_weight : float The weight of the positive class neg_weight : float The weight of the negative class sample_weight : numpy array of shape [n_samples, ] The weight of each sample validation_mask : numpy array of shape [n_samples, ], default=None Precomputed validation mask in case _fit_binary is called in the context of a one-vs-rest reduction. random_state : int, RandomState instance, default=None If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. """ # if average is not true, average_coef, and average_intercept will be # unused label_encode = isinstance(est._loss_function_, CyHalfBinomialLoss) y_i, coef, intercept, average_coef, average_intercept = _prepare_fit_binary( est, y, i, input_dtype=X.dtype, label_encode=label_encode ) assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] random_state = check_random_state(random_state) dataset, intercept_decay = make_dataset( X, y_i, sample_weight, random_state=random_state ) penalty_type = est._get_penalty_type(est.penalty) learning_rate_type = est._get_learning_rate_type(learning_rate) if validation_mask is None: validation_mask = est._make_validation_split(y_i, sample_mask=sample_weight > 0) classes = np.array([-1, 1], dtype=y_i.dtype) validation_score_cb = est._make_validation_score_cb( validation_mask, X, y_i, sample_weight, classes=classes ) # numpy mtrand expects a C long which is a signed 32 bit integer under # Windows seed = random_state.randint(MAX_INT) tol = est.tol if est.tol is not None else -np.inf _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) coef, intercept, average_coef, average_intercept, n_iter_ = _plain_sgd( coef, intercept, average_coef, average_intercept, est._loss_function_, penalty_type, alpha, est._get_l1_ratio(), dataset, validation_mask, est.early_stopping, validation_score_cb, int(est.n_iter_no_change), max_iter, tol, int(est.fit_intercept), int(est.verbose), int(est.shuffle), seed, pos_weight, neg_weight, learning_rate_type, est.eta0, est.power_t, 0, est.t_, intercept_decay, est.average, ) if est.average: if len(est.classes_) == 2: est._average_intercept[0] = average_intercept else: est._average_intercept[i] = average_intercept return coef, intercept, n_iter_ def _get_plain_sgd_function(input_dtype): return _plain_sgd32 if input_dtype == np.float32 else _plain_sgd64
BaseSGD