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
catalyst-team__catalyst
catalyst/core/callback.py
{ "start": 2756, "end": 4054 }
class ____(ICallback): """ An abstraction that lets you customize your experiment run logic. Args: order: flag from ``CallbackOrder`` To give users maximum flexibility and extensibility Catalyst supports callback execution anywhere in the training loop: .. code:: bash -- experiment start ---- epoch start ------ loader start -------- batch start ---------- batch handler (Runner logic) -------- batch end ------ loader end ---- epoch end -- experiment end exception – if an Exception was raised Abstraction, please check out implementations for more details: - :py:mod:`catalyst.callbacks.criterion.CriterionCallback` - :py:mod:`catalyst.callbacks.optimizer.OptimizerCallback` - :py:mod:`catalyst.callbacks.scheduler.SchedulerCallback` - :py:mod:`catalyst.callbacks.checkpoint.CheckpointCallback` .. note:: To learn more about Catalyst Core concepts, please check out - :py:mod:`catalyst.core.runner.IRunner` - :py:mod:`catalyst.core.engine.Engine` - :py:mod:`catalyst.core.callback.Callback` """ def __init__(self, order: int): """Init.""" self.order = order
Callback
python
plotly__plotly.py
codegen/utils.py
{ "start": 32793, "end": 34485 }
class ____(PlotlyNode): def __init__(self, array_node, plotly_schema): """ Create node that represents element defaults properties (e.g. layout.annotationdefaults). Construct as a wrapper around the corresponding array property node (e.g. layout.annotations) Parameters ---------- array_node: PlotlyNode """ super().__init__( plotly_schema, node_path=array_node.node_path, parent=array_node.parent ) assert array_node.is_array self.array_node = array_node self.element_node = array_node.children[0].children[0] @property def node_data(self): return {} @property def description(self): array_property_path = self.parent_path_str + "." + self.array_node.name_property if isinstance(self.array_node, TraceNode): data_path = "data." else: data_path = "" defaults_property_path = ( "layout.template." + data_path + self.parent_path_str + "." + self.plotly_name ) return f"""\ When used in a template (as {defaults_property_path}), sets the default property values to use for elements of {array_property_path}""" @property def name_base_datatype(self): return self.element_node.name_base_datatype @property def root_name(self): return self.array_node.root_name @property def plotly_name(self): return self.element_node.plotly_name + "defaults" @property def name_datatype_class(self): return self.element_node.name_datatype_class
ElementDefaultsNode
python
huggingface__transformers
src/transformers/models/qwen3_vl/modeling_qwen3_vl.py
{ "start": 11723, "end": 15962 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Qwen3VLTextConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.config = config self.rope_type = self.config.rope_parameters["rope_type"] rope_init_fn: Callable = self.compute_default_rope_parameters if self.rope_type != "default": rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type] inv_freq, self.attention_scaling = rope_init_fn(self.config, device) self.register_buffer("inv_freq", inv_freq, persistent=False) self.original_inv_freq = inv_freq self.mrope_section = config.rope_parameters.get("mrope_section", [24, 20, 20]) @staticmethod def compute_default_rope_parameters( config: Optional[Qwen3VLTextConfig] = None, device: Optional["torch.device"] = None, seq_len: Optional[int] = None, ) -> tuple["torch.Tensor", float]: """ Computes the inverse frequencies according to the original RoPE implementation Args: config ([`~transformers.PreTrainedConfig`]): The model configuration. device (`torch.device`): The device to use for initialization of the inverse frequencies. seq_len (`int`, *optional*): The current sequence length. Unused for this type of RoPE. Returns: Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE). """ base = config.rope_parameters["rope_theta"] dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads attention_factor = 1.0 # Unused in this type of RoPE # Compute the inverse frequencies inv_freq = 1.0 / ( base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim) ) return inv_freq, attention_factor @torch.no_grad() @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope) def forward(self, x, position_ids): # In contrast to other models, Qwen3VL has different position ids for the grids # So we expand the inv_freq to shape (3, ...) if position_ids.ndim == 2: position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1) inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1) position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions) device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): # Force float32 freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3) freqs = self.apply_interleaved_mrope(freqs, self.mrope_section) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() * self.attention_scaling sin = emb.sin() * self.attention_scaling return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype) def apply_interleaved_mrope(self, freqs, mrope_section): """Apply interleaved MRoPE to 3D rotary embeddings. Reorganizes frequency layout from chunked [TTT...HHH...WWW] to interleaved [THWTHWTHW...TT], preserving frequency continuity. args: x: (3, bs, seq_len, head_dim // 2) mrope_section: (3,) returns: x_t: (bs, seq_len, head_dim // 2) """ freqs_t = freqs[0] # just overwrite the first dimension T for dim, offset in enumerate((1, 2), start=1): # H, W length = mrope_section[dim] * 3 idx = slice(offset, length, 3) freqs_t[..., idx] = freqs[dim, ..., idx] return freqs_t @use_kernel_forward_from_hub("RMSNorm")
Qwen3VLTextRotaryEmbedding
python
mlflow__mlflow
tests/paddle/test_paddle_model_export.py
{ "start": 1271, "end": 11465 }
class ____(NamedTuple): model: Any inference_dataframe: Any def get_dataset(): X, y = load_diabetes(return_X_y=True) min_max_scaler = preprocessing.MinMaxScaler() X_min_max = min_max_scaler.fit_transform(X) X_normalized = preprocessing.scale(X_min_max, with_std=False) X_train, X_test, y_train, y_test = train_test_split( X_normalized, y, test_size=0.2, random_state=42 ) y_train = y_train.reshape(-1, 1) y_test = y_test.reshape(-1, 1) return np.concatenate((X_train, y_train), axis=1), np.concatenate((X_test, y_test), axis=1) @pytest.fixture def pd_model(): class Regressor(paddle.nn.Layer): def __init__(self, in_features): super().__init__() self.fc_ = Linear(in_features=in_features, out_features=1) @paddle.jit.to_static def forward(self, inputs): return self.fc_(inputs) training_data, test_data = get_dataset() model = Regressor(training_data.shape[1] - 1) model.train() opt = paddle.optimizer.SGD(learning_rate=0.01, parameters=model.parameters()) EPOCH_NUM = 10 BATCH_SIZE = 10 for _ in range(EPOCH_NUM): np.random.shuffle(training_data) mini_batches = [ training_data[k : k + BATCH_SIZE] for k in range(0, len(training_data), BATCH_SIZE) ] for mini_batch in mini_batches: x = np.array(mini_batch[:, :-1]).astype("float32") y = np.array(mini_batch[:, -1:]).astype("float32") house_features = paddle.to_tensor(x) prices = paddle.to_tensor(y) predicts = model(house_features) loss = F.square_error_cost(predicts, label=prices) avg_loss = paddle.mean(loss) avg_loss.backward() opt.step() opt.clear_grad() np_test_data = np.array(test_data).astype("float32") return ModelWithData(model=model, inference_dataframe=np_test_data[:, :-1]) @pytest.fixture(scope="module") def pd_model_signature(): return ModelSignature( inputs=Schema([TensorSpec(np.dtype("float32"), (-1, 10))]), # The _PaddleWrapper class casts numpy prediction outputs into a Pandas DataFrame. outputs=Schema([ColSpec(name=0, type=DataType.float)]), ) @pytest.fixture def model_path(tmp_path): return os.path.join(tmp_path, "model") @pytest.fixture def pd_custom_env(tmp_path): conda_env = os.path.join(tmp_path, "conda_env.yml") _mlflow_conda_env(conda_env, additional_pip_deps=["paddle", "pytest"]) return conda_env def test_model_save_load(pd_model, model_path): mlflow.paddle.save_model(pd_model=pd_model.model, path=model_path) reloaded_pd_model = mlflow.paddle.load_model(model_uri=model_path) reloaded_pyfunc = pyfunc.load_model(model_uri=model_path) np.testing.assert_array_almost_equal( pd_model.model(paddle.to_tensor(pd_model.inference_dataframe)), reloaded_pyfunc.predict(pd_model.inference_dataframe), decimal=5, ) np.testing.assert_array_almost_equal( reloaded_pd_model(paddle.to_tensor(pd_model.inference_dataframe)), reloaded_pyfunc.predict(pd_model.inference_dataframe), decimal=5, ) def test_model_load_from_remote_uri_succeeds(pd_model, model_path, mock_s3_bucket): mlflow.paddle.save_model(pd_model=pd_model.model, path=model_path) artifact_root = f"s3://{mock_s3_bucket}" artifact_path = "model" artifact_repo = S3ArtifactRepository(artifact_root) artifact_repo.log_artifacts(model_path, artifact_path=artifact_path) model_uri = artifact_root + "/" + artifact_path reloaded_model = mlflow.paddle.load_model(model_uri=model_uri) np.testing.assert_array_almost_equal( pd_model.model(paddle.to_tensor(pd_model.inference_dataframe)), reloaded_model(paddle.to_tensor(pd_model.inference_dataframe)), decimal=5, ) def test_model_log(pd_model, model_path, tmp_path): model = pd_model.model try: artifact_path = "model" conda_env = os.path.join(tmp_path, "conda_env.yaml") _mlflow_conda_env(conda_env, additional_pip_deps=["paddle"]) model_info = mlflow.paddle.log_model(model, name=artifact_path, conda_env=conda_env) reloaded_pd_model = mlflow.paddle.load_model(model_uri=model_info.model_uri) np.testing.assert_array_almost_equal( model(paddle.to_tensor(pd_model.inference_dataframe)), reloaded_pd_model(paddle.to_tensor(pd_model.inference_dataframe)), decimal=5, ) model_path = _download_artifact_from_uri(artifact_uri=model_info.model_uri) model_config = Model.load(os.path.join(model_path, "MLmodel")) assert pyfunc.FLAVOR_NAME in model_config.flavors assert pyfunc.ENV in model_config.flavors[pyfunc.FLAVOR_NAME] env_path = model_config.flavors[pyfunc.FLAVOR_NAME][pyfunc.ENV]["conda"] assert os.path.exists(os.path.join(model_path, env_path)) finally: mlflow.end_run() def test_log_model_calls_register_model(pd_model): artifact_path = "model" register_model_patch = mock.patch("mlflow.tracking._model_registry.fluent._register_model") with mlflow.start_run(), register_model_patch: model_info = mlflow.paddle.log_model( pd_model.model, name=artifact_path, registered_model_name="AdsModel1", ) assert_register_model_called_with_local_model_path( register_model_mock=mlflow.tracking._model_registry.fluent._register_model, model_uri=model_info.model_uri, registered_model_name="AdsModel1", ) def test_log_model_no_registered_model_name(pd_model): artifact_path = "model" register_model_patch = mock.patch("mlflow.tracking._model_registry.fluent._register_model") with mlflow.start_run(), register_model_patch: mlflow.paddle.log_model(pd_model.model, name=artifact_path) mlflow.tracking._model_registry.fluent._register_model.assert_not_called() def test_model_save_persists_specified_conda_env_in_mlflow_model_directory( pd_model, model_path, pd_custom_env ): mlflow.paddle.save_model(pd_model=pd_model.model, path=model_path, conda_env=pd_custom_env) pyfunc_conf = _get_flavor_configuration(model_path=model_path, flavor_name=pyfunc.FLAVOR_NAME) saved_conda_env_path = os.path.join(model_path, pyfunc_conf[pyfunc.ENV]["conda"]) assert os.path.exists(saved_conda_env_path) assert saved_conda_env_path != pd_custom_env with open(pd_custom_env) as f: pd_custom_env_parsed = yaml.safe_load(f) with open(saved_conda_env_path) as f: saved_conda_env_parsed = yaml.safe_load(f) assert saved_conda_env_parsed == pd_custom_env_parsed def test_model_save_accepts_conda_env_as_dict(pd_model, model_path): conda_env = dict(mlflow.paddle.get_default_conda_env()) conda_env["dependencies"].append("pytest") mlflow.paddle.save_model(pd_model=pd_model.model, path=model_path, conda_env=conda_env) pyfunc_conf = _get_flavor_configuration(model_path=model_path, flavor_name=pyfunc.FLAVOR_NAME) saved_conda_env_path = os.path.join(model_path, pyfunc_conf[pyfunc.ENV]["conda"]) assert os.path.exists(saved_conda_env_path) with open(saved_conda_env_path) as f: saved_conda_env_parsed = yaml.safe_load(f) assert saved_conda_env_parsed == conda_env def test_signature_and_examples_are_saved_correctly(pd_model, pd_model_signature): test_dataset = pd_model.inference_dataframe example_ = test_dataset[:3, :] for signature in (None, pd_model_signature): for example in (None, example_): with TempDir() as tmp: path = tmp.path("model") mlflow.paddle.save_model( pd_model.model, path=path, signature=signature, input_example=example ) mlflow_model = Model.load(path) if signature is None and example is None: assert mlflow_model.signature is None else: assert mlflow_model.signature == pd_model_signature if example is None: assert mlflow_model.saved_input_example_info is None else: np.testing.assert_array_equal(_read_example(mlflow_model, path), example) def test_model_log_persists_specified_conda_env_in_mlflow_model_directory(pd_model, pd_custom_env): artifact_path = "model" with mlflow.start_run(): model_info = mlflow.paddle.log_model( pd_model.model, name=artifact_path, conda_env=pd_custom_env ) model_path = _download_artifact_from_uri(artifact_uri=model_info.model_uri) pyfunc_conf = _get_flavor_configuration(model_path=model_path, flavor_name=pyfunc.FLAVOR_NAME) saved_conda_env_path = os.path.join(model_path, pyfunc_conf[pyfunc.ENV]["conda"]) assert os.path.exists(saved_conda_env_path) assert saved_conda_env_path != pd_custom_env with open(pd_custom_env) as f: pd_custom_env_parsed = yaml.safe_load(f) with open(saved_conda_env_path) as f: saved_conda_env_parsed = yaml.safe_load(f) assert saved_conda_env_parsed == pd_custom_env_parsed def test_model_save_without_specified_conda_env_uses_default_env_with_expected_dependencies( pd_model, model_path ): mlflow.paddle.save_model(pd_model=pd_model.model, path=model_path) _assert_pip_requirements(model_path, mlflow.paddle.get_default_pip_requirements()) def test_model_log_without_specified_conda_env_uses_default_env_with_expected_dependencies( pd_model, ): artifact_path = "model" with mlflow.start_run(): model_info = mlflow.paddle.log_model(pd_model.model, name=artifact_path) _assert_pip_requirements(model_info.model_uri, mlflow.paddle.get_default_pip_requirements()) @pytest.fixture(scope="module") def get_dataset_built_in_high_level_api(): train_dataset = paddle.text.datasets.UCIHousing(mode="train") eval_dataset = paddle.text.datasets.UCIHousing(mode="test") return train_dataset, eval_dataset
ModelWithData
python
hyperopt__hyperopt
hyperopt/tests/unit/test_pchoice.py
{ "start": 2533, "end": 5341 }
class ____(unittest.TestCase): # test that that a space with a pchoice in it is # (a) accepted for each algo (random, tpe, anneal) # and # (b) handled correctly. # def setUp(self): self.space = hp.pchoice("a", [(0.1, 0), (0.2, 1), (0.3, 2), (0.4, 3)]) self.trials = Trials() def objective(self, a): return [1, 1, 1, 0][a] def test_random(self): max_evals = 150 fmin( self.objective, space=self.space, trials=self.trials, algo=rand.suggest, rstate=np.random.default_rng(4), max_evals=max_evals, ) a_vals = [t["misc"]["vals"]["a"][0] for t in self.trials.trials] counts = np.bincount(a_vals) assert counts[3] > max_evals * 0.35 assert counts[3] < max_evals * 0.60 def test_tpe(self): max_evals = 100 fmin( self.objective, space=self.space, trials=self.trials, algo=partial(tpe.suggest, n_startup_jobs=10), rstate=np.random.default_rng(4), max_evals=max_evals, ) a_vals = [t["misc"]["vals"]["a"][0] for t in self.trials.trials] counts = np.bincount(a_vals) assert counts[3] > max_evals * 0.6 def test_anneal(self): max_evals = 100 fmin( self.objective, space=self.space, trials=self.trials, algo=partial(anneal.suggest), rstate=np.random.default_rng(4), max_evals=max_evals, ) a_vals = [t["misc"]["vals"]["a"][0] for t in self.trials.trials] counts = np.bincount(a_vals) assert counts[3] > max_evals * 0.6 def test_constant_fn_rand(): space = hp.choice( "preprocess_choice", [ {"pwhiten": hp.pchoice("whiten_randomPCA", [(0.3, False), (0.7, True)])}, {"palgo": False}, {"pthree": 7}, ], ) fmin(fn=lambda x: 1, space=space, algo=rand.suggest, max_evals=50) def test_constant_fn_tpe(): space = hp.choice( "preprocess_choice", [ {"pwhiten": hp.pchoice("whiten_randomPCA", [(0.3, False), (0.7, True)])}, {"palgo": False}, {"pthree": 7}, ], ) fmin( fn=lambda x: 1, space=space, algo=tpe.suggest, max_evals=50, rstate=np.random.default_rng(44), ) def test_constant_fn_anneal(): space = hp.choice( "preprocess_choice", [ {"pwhiten": hp.pchoice("whiten_randomPCA", [(0.3, False), (0.7, True)])}, {"palgo": False}, {"pthree": 7}, ], ) fmin(fn=lambda x: 1, space=space, algo=anneal.suggest, max_evals=50)
TestSimpleFMin
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/sensors/bigquery.py
{ "start": 1484, "end": 6151 }
class ____(BaseSensorOperator): """ Checks for the existence of a table in Google Bigquery. :param project_id: The Google cloud project in which to look for the table. The connection supplied to the hook must provide access to the specified project. :param dataset_id: The name of the dataset in which to look for the table. storage bucket. :param table_id: The name of the table to check the existence of. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "project_id", "dataset_id", "table_id", "impersonation_chain", ) ui_color = "#f0eee4" def __init__( self, *, project_id: str, dataset_id: str, table_id: str, 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: if deferrable and "poke_interval" not in kwargs: # TODO: Remove once deprecated if "polling_interval" in kwargs: kwargs["poke_interval"] = kwargs["polling_interval"] warnings.warn( "Argument `poll_interval` is deprecated and will be removed " "in a future release. Please use `poke_interval` instead.", AirflowProviderDeprecationWarning, stacklevel=2, ) else: kwargs["poke_interval"] = 5 super().__init__(**kwargs) self.project_id = project_id self.dataset_id = dataset_id self.table_id = table_id self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.deferrable = deferrable def poke(self, context: Context) -> bool: table_uri = f"{self.project_id}:{self.dataset_id}.{self.table_id}" self.log.info("Sensor checks existence of table: %s", table_uri) hook = BigQueryHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) return hook.table_exists( project_id=self.project_id, dataset_id=self.dataset_id, table_id=self.table_id ) def execute(self, context: Context) -> None: """Airflow runs this method on the worker and defers using the trigger.""" if not self.deferrable: super().execute(context) else: if not self.poke(context=context): self.defer( timeout=timedelta(seconds=self.timeout), trigger=BigQueryTableExistenceTrigger( dataset_id=self.dataset_id, table_id=self.table_id, project_id=self.project_id, poll_interval=self.poke_interval, gcp_conn_id=self.gcp_conn_id, hook_params={ "impersonation_chain": self.impersonation_chain, }, ), method_name="execute_complete", ) def execute_complete(self, context: dict[str, Any], event: dict[str, str] | None = None) -> str: """ Act as a callback for when the trigger fires - returns immediately. Relies on trigger to throw an exception, otherwise it assumes execution was successful. """ table_uri = f"{self.project_id}:{self.dataset_id}.{self.table_id}" self.log.info("Sensor checks existence of table: %s", table_uri) if event: if event["status"] == "success": return event["message"] raise AirflowException(event["message"]) message = "No event received in trigger callback" raise AirflowException(message)
BigQueryTableExistenceSensor
python
tensorflow__tensorflow
tensorflow/python/keras/constraints.py
{ "start": 4229, "end": 4491 }
class ____(Constraint): """Constrains the weights to be non-negative. Also available via the shortcut function `tf.keras.constraints.non_neg`. """ def __call__(self, w): return w * math_ops.cast(math_ops.greater_equal(w, 0.), backend.floatx())
NonNeg
python
getlogbook__logbook
src/logbook/utils.py
{ "start": 2741, "end": 5604 }
class ____: def __init__(self, func, message, obj=None, objtype=None): super().__init__() self._func = func self._message = message self._obj = obj self._objtype = objtype def _get_underlying_func(self): returned = self._func if isinstance(returned, classmethod): if hasattr(returned, "__func__"): returned = returned.__func__ else: returned = returned.__get__(self._objtype).__func__ return returned def __call__(self, *args, **kwargs): func = self._get_underlying_func() warning = f"{self._get_func_str()} is deprecated." if self._message is not None: warning += f" {self._message}" _write_deprecations_if_needed(warning, frame_correction=+1) if self._obj is not None: return func(self._obj, *args, **kwargs) elif self._objtype is not None: return func(self._objtype, *args, **kwargs) return func(*args, **kwargs) def _get_func_str(self): func = self._get_underlying_func() if self._objtype is not None: return f"{self._objtype.__name__}.{func.__name__}" return f"{func.__module__}.{func.__name__}" def __get__(self, obj, objtype): return self.bound_to(obj, objtype) def bound_to(self, obj, objtype): return _DeprecatedFunction(self._func, self._message, obj=obj, objtype=objtype) @property def __name__(self): return self._get_underlying_func().__name__ @property def __doc__(self): if returned := self._get_underlying_func().__doc__: # pylint: disable=no-member returned += "\n.. deprecated\n" # pylint: disable=no-member if self._message: returned += f" {self._message}" # pylint: disable=no-member return returned @__doc__.setter def __doc__(self, doc): self._get_underlying_func().__doc__ = doc def deprecated(func=None, message=None): """Marks the specified function as deprecated, and emits a warning when it's called. >>> @deprecated(message='No longer supported') ... def deprecated_func(): ... pass This will cause a warning log to be emitted when the function gets called, with the correct filename/lineno. .. versionadded:: 0.12 """ if isinstance(func, str): assert message is None message = func func = None if func is None: return functools.partial(deprecated, message=message) return _DeprecatedFunction(func, message) def _get_caller_location(frame_correction): frame = sys._getframe(frame_correction + 1) # pylint: disable=protected-access try: return (frame.f_code.co_name, frame.f_lineno) finally: del frame
_DeprecatedFunction
python
numba__numba
numba/tests/npyufunc/test_vectorize_decor.py
{ "start": 2220, "end": 2309 }
class ____(unittest.TestCase, BaseVectorizeDecor): target = 'cpu'
TestCPUVectorizeDecor
python
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 7338, "end": 12915 }
class ____(Scale): """ A categorical scale without relative importance / magnitude. """ # Categorical (convert to strings), un-sortable values: tuple | str | list | dict | None = None order: list | None = None _priority: ClassVar[int] = 4 def _setup( self, data: Series, prop: Property, axis: Axis | None = None, ) -> Scale: new = copy(self) if new._tick_params is None: new = new.tick() if new._label_params is None: new = new.label() # TODO flexibility over format() which isn't great for numbers / dates stringify = np.vectorize(format, otypes=["object"]) units_seed = categorical_order(data, new.order) # TODO move to Nominal._get_scale? # TODO this needs some more complicated rethinking about how to pass # a unit dictionary down to these methods, along with how much we want # to invest in their API. What is it useful for tick() to do here? # (Ordinal may be different if we draw that contrast). # Any customization we do to allow, e.g., label wrapping will probably # require defining our own Formatter subclass. # We could also potentially implement auto-wrapping in an Axis subclass # (see Axis.draw ... it already is computing the bboxes). # major_locator, minor_locator = new._get_locators(**new._tick_params) # major_formatter = new._get_formatter(major_locator, **new._label_params) class CatScale(mpl.scale.LinearScale): def set_default_locators_and_formatters(self, axis): ... # axis.set_major_locator(major_locator) # if minor_locator is not None: # axis.set_minor_locator(minor_locator) # axis.set_major_formatter(major_formatter) mpl_scale = CatScale(data.name) if axis is None: axis = PseudoAxis(mpl_scale) # TODO Currently just used in non-Coordinate contexts, but should # we use this to (A) set the padding we want for categorial plots # and (B) allow the values parameter for a Coordinate to set xlim/ylim axis.set_view_interval(0, len(units_seed) - 1) new._matplotlib_scale = mpl_scale # TODO array cast necessary to handle float/int mixture, which we need # to solve in a more systematic way probably # (i.e. if we have [1, 2.5], do we want [1.0, 2.5]? Unclear) axis.update_units(stringify(np.array(units_seed))) # TODO define this more centrally def convert_units(x): # TODO only do this with explicit order? # (But also category dtype?) # TODO isin fails when units_seed mixes numbers and strings (numpy error?) # but np.isin also does not seem any faster? (Maybe not broadcasting in C) # keep = x.isin(units_seed) keep = np.array([x_ in units_seed for x_ in x], bool) out = np.full(len(x), np.nan) out[keep] = axis.convert_units(stringify(x[keep])) return out new._pipeline = [convert_units, prop.get_mapping(new, data)] new._spacer = _default_spacer if prop.legend: new._legend = units_seed, list(stringify(units_seed)) return new def _finalize(self, p: Plot, axis: Axis) -> None: ax = axis.axes name = axis.axis_name axis.grid(False, which="both") if name not in p._limits: nticks = len(axis.get_major_ticks()) lo, hi = -.5, nticks - .5 if name == "y": lo, hi = hi, lo set_lim = getattr(ax, f"set_{name}lim") set_lim(lo, hi, auto=None) def tick(self, locator: Locator | None = None) -> Nominal: """ Configure the selection of ticks for the scale's axis or legend. .. note:: This API is under construction and will be enhanced over time. At the moment, it is probably not very useful. Parameters ---------- locator : :class:`matplotlib.ticker.Locator` subclass Pre-configured matplotlib locator; other parameters will not be used. Returns ------- Copy of self with new tick configuration. """ new = copy(self) new._tick_params = {"locator": locator} return new def label(self, formatter: Formatter | None = None) -> Nominal: """ Configure the selection of labels for the scale's axis or legend. .. note:: This API is under construction and will be enhanced over time. At the moment, it is probably not very useful. Parameters ---------- formatter : :class:`matplotlib.ticker.Formatter` subclass Pre-configured matplotlib formatter; other parameters will not be used. Returns ------- scale Copy of self with new tick configuration. """ new = copy(self) new._label_params = {"formatter": formatter} return new def _get_locators(self, locator): if locator is not None: return locator, None locator = mpl.category.StrCategoryLocator({}) return locator, None def _get_formatter(self, locator, formatter): if formatter is not None: return formatter formatter = mpl.category.StrCategoryFormatter({}) return formatter @dataclass
Nominal
python
pyinstaller__pyinstaller
PyInstaller/loader/pyimod02_importers.py
{ "start": 26184, "end": 29280 }
class ____: """ Resource reader for importlib.resources / importlib_resources support. Supports only on-disk resources, which should cover the typical use cases, i.e., the access to data files; PyInstaller collects data files onto filesystem, and as of v6.0.0, the embedded PYZ archive is guaranteed to contain only .pyc modules. When listing resources, source .py files will not be listed as they are not collected by default. Similarly, sub-directories that contained only .py files are not reconstructed on filesystem, so they will not be listed, either. If access to .py files is required for whatever reason, they need to be explicitly collected as data files anyway, which will place them on filesystem and make them appear as resources. For on-disk resources, we *must* return path compatible with pathlib.Path() in order to avoid copy to a temporary file, which might break under some circumstances, e.g., metpy with importlib_resources back-port, due to: https://github.com/Unidata/MetPy/blob/a3424de66a44bf3a92b0dcacf4dff82ad7b86712/src/metpy/plots/wx_symbols.py#L24-L25 (importlib_resources tries to use 'fonts/wx_symbols.ttf' as a temporary filename suffix, which fails as it contains a separator). Furthermore, some packages expect files() to return either pathlib.Path or zipfile.Path, e.g., https://github.com/tensorflow/datasets/blob/master/tensorflow_datasets/core/utils/resource_utils.py#L81-L97 This makes implementation of mixed support for on-disk and embedded resources using importlib.abc.Traversable protocol rather difficult. So in order to maximize compatibility with unfrozen behavior, the below implementation is basically equivalent of importlib.readers.FileReader from python 3.10: https://github.com/python/cpython/blob/839d7893943782ee803536a47f1d4de160314f85/Lib/importlib/readers.py#L11 and its underlying classes, importlib.abc.TraversableResources and importlib.abc.ResourceReader: https://github.com/python/cpython/blob/839d7893943782ee803536a47f1d4de160314f85/Lib/importlib/abc.py#L422 https://github.com/python/cpython/blob/839d7893943782ee803536a47f1d4de160314f85/Lib/importlib/abc.py#L312 """ def __init__(self, loader): # Local import to avoid including `pathlib` and its dependencies in `base_library.zip` import pathlib # This covers both modules and (regular) packages. Note that PEP-420 namespace packages are not handled by this # resource reader (since they are not handled by PyiFrozenLoader, which uses this reader). self.path = pathlib.Path(loader.path).parent def open_resource(self, resource): return self.files().joinpath(resource).open('rb') def resource_path(self, resource): return str(self.path.joinpath(resource)) def is_resource(self, path): return self.files().joinpath(path).is_file() def contents(self): return (item.name for item in self.files().iterdir()) def files(self): return self.path
PyiFrozenResourceReader
python
django-mptt__django-mptt
mptt/templatetags/mptt_tags.py
{ "start": 480, "end": 973 }
class ____(template.Node): def __init__(self, model, context_var): self.model = model self.context_var = context_var def render(self, context): cls = apps.get_model(*self.model.split(".")) if cls is None: raise template.TemplateSyntaxError( _("full_tree_for_model tag was given an invalid model: %s") % self.model ) context[self.context_var] = cls._tree_manager.all() return ""
FullTreeForModelNode
python
django__django
django/test/testcases.py
{ "start": 56291, "end": 60323 }
class ____: """Descriptor class for deferred condition checking.""" def __init__(self, *conditions): self.conditions = conditions def add_condition(self, condition, reason): return self.__class__(*self.conditions, (condition, reason)) def __get__(self, instance, cls=None): # Trigger access for all bases. if any(getattr(base, "__unittest_skip__", False) for base in cls.__bases__): return True for condition, reason in self.conditions: if condition(): # Override this descriptor's value and set the skip reason. cls.__unittest_skip__ = True cls.__unittest_skip_why__ = reason return True return False def _deferredSkip(condition, reason, name): def decorator(test_func): nonlocal condition if not ( isinstance(test_func, type) and issubclass(test_func, unittest.TestCase) ): @wraps(test_func) def skip_wrapper(*args, **kwargs): if ( args and isinstance(args[0], unittest.TestCase) and connection.alias not in getattr(args[0], "databases", {}) ): raise ValueError( "%s cannot be used on %s as %s doesn't allow queries " "against the %r database." % ( name, args[0], args[0].__class__.__qualname__, connection.alias, ) ) if condition(): raise unittest.SkipTest(reason) return test_func(*args, **kwargs) test_item = skip_wrapper else: # Assume a class is decorated test_item = test_func databases = getattr(test_item, "databases", None) if not databases or connection.alias not in databases: # Defer raising to allow importing test class's module. def condition(): raise ValueError( "%s cannot be used on %s as it doesn't allow queries " "against the '%s' database." % ( name, test_item, connection.alias, ) ) # Retrieve the possibly existing value from the class's dict to # avoid triggering the descriptor. skip = test_func.__dict__.get("__unittest_skip__") if isinstance(skip, CheckCondition): test_item.__unittest_skip__ = skip.add_condition(condition, reason) elif skip is not True: test_item.__unittest_skip__ = CheckCondition((condition, reason)) return test_item return decorator def skipIfDBFeature(*features): """Skip a test if a database has at least one of the named features.""" return _deferredSkip( lambda: any(getattr(connection.features, feature) for feature in features), "Database has feature(s) %s" % ", ".join(features), "skipIfDBFeature", ) def skipUnlessDBFeature(*features): """Skip a test unless a database has all the named features.""" return _deferredSkip( lambda: not all(getattr(connection.features, feature) for feature in features), "Database doesn't support feature(s): %s" % ", ".join(features), "skipUnlessDBFeature", ) def skipUnlessAnyDBFeature(*features): """Skip a test unless a database has any of the named features.""" return _deferredSkip( lambda: not any(getattr(connection.features, feature) for feature in features), "Database doesn't support any of the feature(s): %s" % ", ".join(features), "skipUnlessAnyDBFeature", )
CheckCondition
python
django__django
tests/gis_tests/inspectapp/models.py
{ "start": 43, "end": 397 }
class ____(models.Model): f_decimal = models.FloatField() f_float = models.FloatField() f_int = models.IntegerField() f_char = models.CharField(max_length=10) f_date = models.DateField() f_datetime = models.DateTimeField() f_time = models.TimeField() geom = models.PolygonField() point = models.PointField()
AllOGRFields
python
django__django
tests/admin_inlines/models.py
{ "start": 4240, "end": 4457 }
class ____(models.Model): person = models.OneToOneField(Person, models.CASCADE, primary_key=True) weaknesses = models.ManyToManyField( OutfitItem, through="ShoppingWeakness", blank=True )
Fashionista
python
huggingface__transformers
src/transformers/models/vivit/modeling_vivit.py
{ "start": 13755, "end": 14278 }
class ____(nn.Module): def __init__(self, config: VivitConfig): super().__init__() self.config = config self.layer = nn.ModuleList([VivitLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, hidden_states: torch.Tensor) -> BaseModelOutput: for i, layer_module in enumerate(self.layer): hidden_states = layer_module(hidden_states) return BaseModelOutput(last_hidden_state=hidden_states)
VivitEncoder
python
plotly__plotly.py
plotly/graph_objs/isosurface/_colorbar.py
{ "start": 233, "end": 61532 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "isosurface" _path_str = "isosurface.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "nticks", "orientation", "outlinecolor", "outlinewidth", "separatethousands", "showexponent", "showticklabels", "showtickprefix", "showticksuffix", "thickness", "thicknessmode", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabeloverflow", "ticklabelposition", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "x", "xanchor", "xpad", "xref", "y", "yanchor", "ypad", "yref", } @property def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val @property def bordercolor(self): """ Sets the axis line color. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val @property def borderwidth(self): """ Sets the width (in px) or the border enclosing this color bar. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html- like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val @property def len(self): """ Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The 'len' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["len"] @len.setter def len(self, val): self["len"] = val @property def lenmode(self): """ Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. The 'lenmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["lenmode"] @lenmode.setter def lenmode(self, val): self["lenmode"] = val @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val @property def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val @property def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["outlinecolor"] @outlinecolor.setter def outlinecolor(self, val): self["outlinecolor"] = val @property def outlinewidth(self): """ Sets the width (in px) of the axis line. The 'outlinewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["outlinewidth"] @outlinewidth.setter def outlinewidth(self, val): self["outlinewidth"] = val @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val @property def thickness(self): """ Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val @property def thicknessmode(self): """ Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. The 'thicknessmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["thicknessmode"] @thicknessmode.setter def thicknessmode(self, val): self["thicknessmode"] = val @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val @property def tickfont(self): """ Sets the color bar's tick label font The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.isosurface.colorbar.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Returns ------- plotly.graph_objs.isosurface.colorbar.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val @property def tickformat(self): """ Sets the tick label 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. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.isosurface.colorbar.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Returns ------- tuple[plotly.graph_objs.isosurface.colorbar.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.data.isosurface.col orbar.tickformatstopdefaults), sets the default property values to use for elements of isosurface.colorbar.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.isosurface.colorbar.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Returns ------- plotly.graph_objs.isosurface.colorbar.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val @property def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"] @ticklabeloverflow.setter def ticklabeloverflow(self, val): self["ticklabeloverflow"] = val @property def ticklabelposition(self): """ Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". The 'ticklabelposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'] Returns ------- Any """ return self["ticklabelposition"] @ticklabelposition.setter def ticklabelposition(self, val): self["ticklabelposition"] = val @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.isosurface.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Returns ------- plotly.graph_objs.isosurface.colorbar.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val @property def x(self): """ Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". The 'x' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val @property def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"] @xpad.setter def xpad(self, val): self["xpad"] = val @property def xref(self): """ Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. The 'xref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["xref"] @xref.setter def xref(self, val): self["xref"] = val @property def y(self): """ Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". The 'y' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val @property def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"] @ypad.setter def ypad(self, val): self["ypad"] = val @property def yref(self): """ Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["yref"] @yref.setter def yref(self, val): self["yref"] = val @property def _prop_descriptions(self): return """\ bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label 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. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.isosurface.colo rbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.isosur face.colorbar.tickformatstopdefaults), sets the default property values to use for elements of isosurface.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.isosurface.colorbar.Title` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. """ def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, labelalias=None, len=None, lenmode=None, minexponent=None, nticks=None, orientation=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabeloverflow=None, ticklabelposition=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, x=None, xanchor=None, xpad=None, xref=None, y=None, yanchor=None, ypad=None, yref=None, **kwargs, ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.isosurface.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label 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. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.isosurface.colo rbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.isosur face.colorbar.tickformatstopdefaults), sets the default property values to use for elements of isosurface.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.isosurface.colorbar.Title` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- ColorBar """ super().__init__("colorbar") 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.isosurface.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.isosurface.ColorBar`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("bgcolor", arg, bgcolor) self._set_property("bordercolor", arg, bordercolor) self._set_property("borderwidth", arg, borderwidth) self._set_property("dtick", arg, dtick) self._set_property("exponentformat", arg, exponentformat) self._set_property("labelalias", arg, labelalias) self._set_property("len", arg, len) self._set_property("lenmode", arg, lenmode) self._set_property("minexponent", arg, minexponent) self._set_property("nticks", arg, nticks) self._set_property("orientation", arg, orientation) self._set_property("outlinecolor", arg, outlinecolor) self._set_property("outlinewidth", arg, outlinewidth) self._set_property("separatethousands", arg, separatethousands) self._set_property("showexponent", arg, showexponent) self._set_property("showticklabels", arg, showticklabels) self._set_property("showtickprefix", arg, showtickprefix) self._set_property("showticksuffix", arg, showticksuffix) self._set_property("thickness", arg, thickness) self._set_property("thicknessmode", arg, thicknessmode) self._set_property("tick0", arg, tick0) self._set_property("tickangle", arg, tickangle) self._set_property("tickcolor", arg, tickcolor) self._set_property("tickfont", arg, tickfont) self._set_property("tickformat", arg, tickformat) self._set_property("tickformatstops", arg, tickformatstops) self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults) self._set_property("ticklabeloverflow", arg, ticklabeloverflow) self._set_property("ticklabelposition", arg, ticklabelposition) self._set_property("ticklabelstep", arg, ticklabelstep) self._set_property("ticklen", arg, ticklen) self._set_property("tickmode", arg, tickmode) self._set_property("tickprefix", arg, tickprefix) self._set_property("ticks", arg, ticks) self._set_property("ticksuffix", arg, ticksuffix) self._set_property("ticktext", arg, ticktext) self._set_property("ticktextsrc", arg, ticktextsrc) self._set_property("tickvals", arg, tickvals) self._set_property("tickvalssrc", arg, tickvalssrc) self._set_property("tickwidth", arg, tickwidth) self._set_property("title", arg, title) self._set_property("x", arg, x) self._set_property("xanchor", arg, xanchor) self._set_property("xpad", arg, xpad) self._set_property("xref", arg, xref) self._set_property("y", arg, y) self._set_property("yanchor", arg, yanchor) self._set_property("ypad", arg, ypad) self._set_property("yref", arg, yref) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
ColorBar
python
mlflow__mlflow
mlflow/spark/autologging.py
{ "start": 9287, "end": 10449 }
class ____(RunContextProvider): """ Context provider used when there's no active run. Accumulates datasource read information, then logs that information to the next-created run. Note that this doesn't clear the accumulated info when logging them to the next run, so it will be logged to any successive runs as well. """ def in_context(self): return True def tags(self): # if autologging is disabled, then short circuit `tags()` and return empty dict. if autologging_is_disabled(FLAVOR_NAME): return {} with _lock: seen = set() unique_infos = [] for info in _table_infos: if info not in seen: unique_infos.append(info) seen.add(info) if len(unique_infos) > 0: tags = { _SPARK_TABLE_INFO_TAG_NAME: _generate_datasource_tag_value( "\n".join([_get_table_info_string(*info) for info in unique_infos]) ) } else: tags = {} return tags
SparkAutologgingContext
python
dask__distributed
distributed/gc.py
{ "start": 5357, "end": 9207 }
class ____: """ An object that hooks itself into the gc callbacks to collect timing and memory statistics, and log interesting info. Don't instantiate this directly except for tests. Instead, use the global instance. """ N_SAMPLES = 30 def __init__(self, info_over_frac=0.1, info_over_rss_win=10 * 1e6): self._info_over_frac = info_over_frac self._info_over_rss_win = info_over_rss_win self._enabled = False self._fractional_timer = None def enable(self): assert not self._enabled self._fractional_timer = FractionalTimer(n_samples=self.N_SAMPLES) self._proc = psutil.Process() cb = self._gc_callback assert cb not in gc.callbacks # NOTE: a global ref to self is saved there so __del__ can't work gc.callbacks.append(cb) self._enabled = True def disable(self): assert self._enabled gc.callbacks.remove(self._gc_callback) self._enabled = False @property def enabled(self): return self._enabled def __enter__(self): self.enable() return self def __exit__(self, exc_type, exc_value, traceback): self.disable() def _gc_callback(self, phase, info): # Young generations are small and collected very often, # don't waste time measuring them if info["generation"] != 2: return rss = self._proc.memory_info().rss if phase == "start": self._fractional_timer.start_timing() self._gc_rss_before = rss return assert phase == "stop" self._fractional_timer.stop_timing() frac = self._fractional_timer.running_fraction if frac is not None: level = logging.INFO if frac >= self._info_over_frac else logging.DEBUG logger.log( level, "full garbage collections took %d%% CPU time " "recently (threshold: %d%%)", 100 * frac, 100 * self._info_over_frac, ) rss_saved = self._gc_rss_before - rss level = logging.INFO if rss_saved >= self._info_over_rss_win else logging.DEBUG logger.log( level, "full garbage collection released %s " "from %d reference cycles (threshold: %s)", format_bytes(rss_saved), info["collected"], format_bytes(self._info_over_rss_win), ) if info["uncollectable"] > 0: # This should ideally never happen on Python 3, but who knows? logger.warning( "garbage collector couldn't collect %d objects, " "please look in gc.garbage", info["uncollectable"], ) _gc_diagnosis = GCDiagnosis() _gc_diagnosis_users = 0 _gc_diagnosis_lock = threading.Lock() def enable_gc_diagnosis(): """ Ask to enable global GC diagnosis. """ global _gc_diagnosis_users with _gc_diagnosis_lock: if _gc_diagnosis_users == 0: _gc_diagnosis.enable() else: assert _gc_diagnosis.enabled _gc_diagnosis_users += 1 def disable_gc_diagnosis(force=False): """ Ask to disable global GC diagnosis. """ global _gc_diagnosis_users with _gc_diagnosis_lock: if _gc_diagnosis_users > 0: _gc_diagnosis_users -= 1 if _gc_diagnosis_users == 0: _gc_diagnosis.disable() elif force: _gc_diagnosis.disable() _gc_diagnosis_users = 0 else: assert _gc_diagnosis.enabled def gc_collect_duration() -> float: if _gc_diagnosis._fractional_timer is None: return 0 return _gc_diagnosis._fractional_timer.duration_total
GCDiagnosis
python
scipy__scipy
scipy/optimize/tests/test_minpack.py
{ "start": 15653, "end": 42688 }
class ____: def setup_method(self): self.y = array([1.0, 3.2, 9.5, 13.7]) self.x = array([1.0, 2.0, 3.0, 4.0]) def test_one_argument(self): def func(x,a): return x**a popt, pcov = curve_fit(func, self.x, self.y) assert_(len(popt) == 1) assert_(pcov.shape == (1,1)) assert_almost_equal(popt[0], 1.9149, decimal=4) assert_almost_equal(pcov[0,0], 0.0016, decimal=4) # Test if we get the same with full_output. Regression test for #1415. # Also test if check_finite can be turned off. res = curve_fit(func, self.x, self.y, full_output=1, check_finite=False) (popt2, pcov2, infodict, errmsg, ier) = res assert_array_almost_equal(popt, popt2) def test_two_argument(self): def func(x, a, b): return b*x**a popt, pcov = curve_fit(func, self.x, self.y) assert_(len(popt) == 2) assert_(pcov.shape == (2,2)) assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4) assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]], decimal=4) def test_func_is_classmethod(self): class test_self: """This class tests if curve_fit passes the correct number of arguments when the model function is a class instance method. """ def func(self, x, a, b): return b * x**a test_self_inst = test_self() popt, pcov = curve_fit(test_self_inst.func, self.x, self.y) assert_(pcov.shape == (2,2)) assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4) assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]], decimal=4) def test_regression_2639(self): # This test fails if epsfcn in leastsq is too large. x = [574.14200000000005, 574.154, 574.16499999999996, 574.17700000000002, 574.18799999999999, 574.19899999999996, 574.21100000000001, 574.22199999999998, 574.23400000000004, 574.245] y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0, 1550.0, 949.0, 841.0] guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0, 0.0035019999999983615, 859.0] good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03, 1.0068462e-02, 8.57450661e+02] def f_double_gauss(x, x0, x1, A0, A1, sigma, c): return (A0*np.exp(-(x-x0)**2/(2.*sigma**2)) + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c) popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000) assert_allclose(popt, good, rtol=1e-5) def test_pcov(self): xdata = np.array([0, 1, 2, 3, 4, 5]) ydata = np.array([1, 1, 5, 7, 8, 12]) sigma = np.array([1, 2, 1, 2, 1, 2]) def f(x, a, b): return a*x + b for method in ['lm', 'trf', 'dogbox']: popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma, method=method) perr_scaled = np.sqrt(np.diag(pcov)) assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3) popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma, method=method) perr_scaled = np.sqrt(np.diag(pcov)) assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3) popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma, absolute_sigma=True, method=method) perr = np.sqrt(np.diag(pcov)) assert_allclose(perr, [0.30714756, 0.85045308], rtol=1e-3) popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma, absolute_sigma=True, method=method) perr = np.sqrt(np.diag(pcov)) assert_allclose(perr, [3*0.30714756, 3*0.85045308], rtol=1e-3) # infinite variances def f_flat(x, a, b): return a*x pcov_expected = np.array([np.inf]*4).reshape(2, 2) with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "Covariance of the parameters could not be estimated", OptimizeWarning) popt, pcov = curve_fit(f_flat, xdata, ydata, p0=[2, 0], sigma=sigma) popt1, pcov1 = curve_fit(f, xdata[:2], ydata[:2], p0=[2, 0]) assert_(pcov.shape == (2, 2)) assert_array_equal(pcov, pcov_expected) assert_(pcov1.shape == (2, 2)) assert_array_equal(pcov1, pcov_expected) def test_array_like(self): # Test sequence input. Regression test for gh-3037. def f_linear(x, a, b): return a*x + b x = [1, 2, 3, 4] y = [3, 5, 7, 9] assert_allclose(curve_fit(f_linear, x, y)[0], [2, 1], atol=1e-10) def test_indeterminate_covariance(self): # Test that a warning is returned when pcov is indeterminate xdata = np.array([1, 2, 3, 4, 5, 6]) ydata = np.array([1, 2, 3, 4, 5.5, 6]) with pytest.warns(OptimizeWarning): curve_fit(lambda x, a, b: a*x, xdata, ydata) def test_NaN_handling(self): # Test for correct handling of NaNs in input data: gh-3422 # create input with NaNs xdata = np.array([1, np.nan, 3]) ydata = np.array([1, 2, 3]) assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b, xdata, ydata) assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b, ydata, xdata) assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b, xdata, ydata, **{"check_finite": True}) @staticmethod def _check_nan_policy(f, xdata_with_nan, xdata_without_nan, ydata_with_nan, ydata_without_nan, method): kwargs = {'f': f, 'xdata': xdata_with_nan, 'ydata': ydata_with_nan, 'method': method, 'check_finite': False} # propagate test error_msg = ("`nan_policy='propagate'` is not supported " "by this function.") with assert_raises(ValueError, match=error_msg): curve_fit(**kwargs, nan_policy="propagate", maxfev=2000) # raise test with assert_raises(ValueError, match="The input contains nan"): curve_fit(**kwargs, nan_policy="raise") # omit test result_with_nan, _ = curve_fit(**kwargs, nan_policy="omit") kwargs['xdata'] = xdata_without_nan kwargs['ydata'] = ydata_without_nan result_without_nan, _ = curve_fit(**kwargs) assert_allclose(result_with_nan, result_without_nan) # not valid policy test # check for argument names in any order error_msg = (r"nan_policy must be one of \{(?:'raise'|'omit'|None)" r"(?:, ?(?:'raise'|'omit'|None))*\}") with assert_raises(ValueError, match=error_msg): curve_fit(**kwargs, nan_policy="hi") @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) def test_nan_policy_1d(self, method): def f(x, a, b): return a*x + b xdata_with_nan = np.array([2, 3, np.nan, 4, 4, np.nan]) ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7]) xdata_without_nan = np.array([2, 3, 4]) ydata_without_nan = np.array([1, 2, 3]) self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, ydata_with_nan, ydata_without_nan, method) @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) def test_nan_policy_2d(self, method): def f(x, a, b): x1 = x[0, :] x2 = x[1, :] return a*x1 + b + x2 xdata_with_nan = np.array([[2, 3, np.nan, 4, 4, np.nan, 5], [2, 3, np.nan, np.nan, 4, np.nan, 7]]) ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10]) xdata_without_nan = np.array([[2, 3, 5], [2, 3, 7]]) ydata_without_nan = np.array([1, 2, 10]) self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, ydata_with_nan, ydata_without_nan, method) @pytest.mark.parametrize('n', [2, 3]) @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"]) def test_nan_policy_2_3d(self, n, method): def f(x, a, b): x1 = x[..., 0, :].squeeze() x2 = x[..., 1, :].squeeze() return a*x1 + b + x2 xdata_with_nan = np.array([[[2, 3, np.nan, 4, 4, np.nan, 5], [2, 3, np.nan, np.nan, 4, np.nan, 7]]]) xdata_with_nan = xdata_with_nan.squeeze() if n == 2 else xdata_with_nan ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10]) xdata_without_nan = np.array([[[2, 3, 5], [2, 3, 7]]]) ydata_without_nan = np.array([1, 2, 10]) self._check_nan_policy(f, xdata_with_nan, xdata_without_nan, ydata_with_nan, ydata_without_nan, method) def test_empty_inputs(self): # Test both with and without bounds (regression test for gh-9864) assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], []) assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [], bounds=(1, 2)) assert_raises(ValueError, curve_fit, lambda x, a: a*x, [1], []) assert_raises(ValueError, curve_fit, lambda x, a: a*x, [2], [], bounds=(1, 2)) def test_function_zero_params(self): # Fit args is zero, so "Unable to determine number of fit parameters." assert_raises(ValueError, curve_fit, lambda x: x, [1, 2], [3, 4]) def test_None_x(self): # Added in GH10196 popt, pcov = curve_fit(lambda _, a: a * np.arange(10), None, 2 * np.arange(10)) assert_allclose(popt, [2.]) def test_method_argument(self): def f(x, a, b): return a * np.exp(-b*x) xdata = np.linspace(0, 1, 11) ydata = f(xdata, 2., 2.) for method in ['trf', 'dogbox', 'lm', None]: popt, pcov = curve_fit(f, xdata, ydata, method=method) assert_allclose(popt, [2., 2.]) assert_raises(ValueError, curve_fit, f, xdata, ydata, method='unknown') def test_full_output(self): def f(x, a, b): return a * np.exp(-b * x) xdata = np.linspace(0, 1, 11) ydata = f(xdata, 2., 2.) for method in ['trf', 'dogbox', 'lm', None]: popt, pcov, infodict, errmsg, ier = curve_fit( f, xdata, ydata, method=method, full_output=True) assert_allclose(popt, [2., 2.]) assert "nfev" in infodict assert "fvec" in infodict if method == 'lm' or method is None: assert "fjac" in infodict assert "ipvt" in infodict assert "qtf" in infodict assert isinstance(errmsg, str) assert ier in (1, 2, 3, 4) def test_bounds(self): def f(x, a, b): return a * np.exp(-b*x) xdata = np.linspace(0, 1, 11) ydata = f(xdata, 2., 2.) # The minimum w/out bounds is at [2., 2.], # and with bounds it's at [1.5, smth]. lb = [1., 0] ub = [1.5, 3.] # Test that both variants of the bounds yield the same result bounds = (lb, ub) bounds_class = Bounds(lb, ub) for method in [None, 'trf', 'dogbox']: popt, pcov = curve_fit(f, xdata, ydata, bounds=bounds, method=method) assert_allclose(popt[0], 1.5) popt_class, pcov_class = curve_fit(f, xdata, ydata, bounds=bounds_class, method=method) assert_allclose(popt_class, popt) # With bounds, the starting estimate is feasible. popt, pcov = curve_fit(f, xdata, ydata, method='trf', bounds=([0., 0], [0.6, np.inf])) assert_allclose(popt[0], 0.6) # method='lm' doesn't support bounds. assert_raises(ValueError, curve_fit, f, xdata, ydata, bounds=bounds, method='lm') def test_bounds_p0(self): # This test is for issue #5719. The problem was that an initial guess # was ignored when 'trf' or 'dogbox' methods were invoked. def f(x, a): return np.sin(x + a) xdata = np.linspace(-2*np.pi, 2*np.pi, 40) ydata = np.sin(xdata) bounds = (-3 * np.pi, 3 * np.pi) for method in ['trf', 'dogbox']: popt_1, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi) popt_2, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi, bounds=bounds, method=method) # If the initial guess is ignored, then popt_2 would be close 0. assert_allclose(popt_1, popt_2) def test_jac(self): # Test that Jacobian callable is handled correctly and # weighted if sigma is provided. def f(x, a, b): return a * np.exp(-b*x) def jac(x, a, b): e = np.exp(-b*x) return np.vstack((e, -a * x * e)).T xdata = np.linspace(0, 1, 11) ydata = f(xdata, 2., 2.) # Test numerical options for least_squares backend. for method in ['trf', 'dogbox']: for scheme in ['2-point', '3-point', 'cs']: popt, pcov = curve_fit(f, xdata, ydata, jac=scheme, method=method) assert_allclose(popt, [2, 2]) # Test the analytic option. for method in ['lm', 'trf', 'dogbox']: popt, pcov = curve_fit(f, xdata, ydata, method=method, jac=jac) assert_allclose(popt, [2, 2]) # Now add an outlier and provide sigma. ydata[5] = 100 sigma = np.ones(xdata.shape[0]) sigma[5] = 200 for method in ['lm', 'trf', 'dogbox']: popt, pcov = curve_fit(f, xdata, ydata, sigma=sigma, method=method, jac=jac) # Still the optimization process is influenced somehow, # have to set rtol=1e-3. assert_allclose(popt, [2, 2], rtol=1e-3) def test_maxfev_and_bounds(self): # gh-6340: with no bounds, curve_fit accepts parameter maxfev (via leastsq) # but with bounds, the parameter is `max_nfev` (via least_squares) x = np.arange(0, 10) y = 2*x popt1, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), maxfev=100) popt2, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), max_nfev=100) assert_allclose(popt1, 2, atol=1e-14) assert_allclose(popt2, 2, atol=1e-14) @pytest.mark.parametrize("sigma_dim", [0, 1, 2]) def test_curvefit_omitnan(self, sigma_dim): def exponential(x, a, b): return b * np.exp(a * x) rng = np.random.default_rng(578285731148908) N = 100 x = np.linspace(1, 10, N) y = exponential(x, 0.2, 0.5) if (sigma_dim == 0): sigma = 0.05 y += rng.normal(0, sigma, N) elif (sigma_dim == 1): sigma = x * 0.05 y += rng.normal(0, sigma, N) elif (sigma_dim == 2): # The covariance matrix must be symmetric positive-semidefinite a = rng.normal(0, 2, (N, N)) sigma = a @ a.T y += rng.multivariate_normal(np.zeros_like(x), sigma) else: assert False, "The sigma must be a scalar, 1D array or 2D array." p0 = [0.1, 1.0] # Choose indices to place NaNs. i_x = rng.integers(N, size=5) i_y = rng.integers(N, size=5) # Add NaNs and compute result using `curve_fit` x[i_x] = np.nan y[i_y] = np.nan res_opt, res_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma, nan_policy="omit") # Manually remove elements that should be eliminated, and # calculate reference using `curve_fit` i_delete = np.unique(np.concatenate((i_x, i_y))) x = np.delete(x, i_delete, axis=0) y = np.delete(y, i_delete, axis=0) sigma = np.asarray(sigma) if sigma.ndim == 1: sigma = np.delete(sigma, i_delete) elif sigma.ndim == 2: sigma = np.delete(sigma, i_delete, axis=0) sigma = np.delete(sigma, i_delete, axis=1) ref_opt, ref_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma) assert_allclose(res_opt, ref_opt, atol=1e-14) assert_allclose(res_cov, ref_cov, atol=1e-14) def test_curvefit_simplecovariance(self): def func(x, a, b): return a * np.exp(-b*x) def jac(x, a, b): e = np.exp(-b*x) return np.vstack((e, -a * x * e)).T rng = np.random.default_rng(123) xdata = np.linspace(0, 4, 50) y = func(xdata, 2.5, 1.3) ydata = y + 0.2 * rng.standard_normal(size=len(xdata)) sigma = np.zeros(len(xdata)) + 0.2 covar = np.diag(sigma**2) for jac1, jac2 in [(jac, jac), (None, None)]: for absolute_sigma in [False, True]: popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma, jac=jac1, absolute_sigma=absolute_sigma) popt2, pcov2 = curve_fit(func, xdata, ydata, sigma=covar, jac=jac2, absolute_sigma=absolute_sigma) assert_allclose(popt1, popt2, atol=1e-14) assert_allclose(pcov1, pcov2, atol=1e-14) def test_curvefit_covariance(self): def funcp(x, a, b): rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], [1./np.sqrt(2), 1./np.sqrt(2), 0], [0, 0, 1.0]]) return rotn.dot(a * np.exp(-b*x)) def jacp(x, a, b): rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], [1./np.sqrt(2), 1./np.sqrt(2), 0], [0, 0, 1.0]]) e = np.exp(-b*x) return rotn.dot(np.vstack((e, -a * x * e)).T) def func(x, a, b): return a * np.exp(-b*x) def jac(x, a, b): e = np.exp(-b*x) return np.vstack((e, -a * x * e)).T rng = np.random.default_rng(1234) xdata = np.arange(1, 4) y = func(xdata, 2.5, 1.0) ydata = y + 0.2 * rng.standard_normal(size=len(xdata)) sigma = np.zeros(len(xdata)) + 0.2 covar = np.diag(sigma**2) # Get a rotation matrix, and obtain ydatap = R ydata # Chisq = ydata^T C^{-1} ydata # = ydata^T R^T R C^{-1} R^T R ydata # = ydatap^T Cp^{-1} ydatap # Cp^{-1} = R C^{-1} R^T # Cp = R C R^T, since R^-1 = R^T rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0], [1./np.sqrt(2), 1./np.sqrt(2), 0], [0, 0, 1.0]]) ydatap = rotn.dot(ydata) covarp = rotn.dot(covar).dot(rotn.T) for jac1, jac2 in [(jac, jacp), (None, None)]: for absolute_sigma in [False, True]: popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma, jac=jac1, absolute_sigma=absolute_sigma) popt2, pcov2 = curve_fit(funcp, xdata, ydatap, sigma=covarp, jac=jac2, absolute_sigma=absolute_sigma) assert_allclose(popt1, popt2, rtol=1.4e-7, atol=1e-14) assert_allclose(pcov1, pcov2, rtol=1.4e-7, atol=1e-14) @pytest.mark.parametrize("absolute_sigma", [False, True]) def test_curvefit_scalar_sigma(self, absolute_sigma): def func(x, a, b): return a * x + b x, y = self.x, self.y _, pcov1 = curve_fit(func, x, y, sigma=2, absolute_sigma=absolute_sigma) # Explicitly building the sigma 1D array _, pcov2 = curve_fit( func, x, y, sigma=np.full_like(y, 2), absolute_sigma=absolute_sigma ) assert np.all(pcov1 == pcov2) def test_dtypes(self): # regression test for gh-9581: curve_fit fails if x and y dtypes differ x = np.arange(-3, 5) y = 1.5*x + 3.0 + 0.5*np.sin(x) def func(x, a, b): return a*x + b for method in ['lm', 'trf', 'dogbox']: for dtx in [np.float32, np.float64]: for dty in [np.float32, np.float64]: x = x.astype(dtx) y = y.astype(dty) with warnings.catch_warnings(): warnings.simplefilter("error", OptimizeWarning) p, cov = curve_fit(func, x, y, method=method) assert np.isfinite(cov).all() assert not np.allclose(p, 1) # curve_fit's initial value def test_dtypes2(self): # regression test for gh-7117: curve_fit fails if # both inputs are float32 def hyperbola(x, s_1, s_2, o_x, o_y, c): b_2 = (s_1 + s_2) / 2 b_1 = (s_2 - s_1) / 2 return o_y + b_1*(x-o_x) + b_2*np.sqrt((x-o_x)**2 + c**2/4) min_fit = np.array([-3.0, 0.0, -2.0, -10.0, 0.0]) max_fit = np.array([0.0, 3.0, 3.0, 0.0, 10.0]) guess = np.array([-2.5/3.0, 4/3.0, 1.0, -4.0, 0.5]) params = [-2, .4, -1, -5, 9.5] xdata = np.array([-32, -16, -8, 4, 4, 8, 16, 32]) ydata = hyperbola(xdata, *params) # run optimization twice, with xdata being float32 and float64 popt_64, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess, bounds=(min_fit, max_fit)) xdata = xdata.astype(np.float32) ydata = hyperbola(xdata, *params) popt_32, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess, bounds=(min_fit, max_fit)) assert_allclose(popt_32, popt_64, atol=2e-5) def test_broadcast_y(self): xdata = np.arange(10) rng = np.random.default_rng(123) target = 4.7 * xdata ** 2 + 3.5 * xdata + rng.random(size=len(xdata)) def fit_func(x, a, b): return a * x ** 2 + b * x - target for method in ['lm', 'trf', 'dogbox']: popt0, pcov0 = curve_fit(fit_func, xdata=xdata, ydata=np.zeros_like(xdata), method=method) popt1, pcov1 = curve_fit(fit_func, xdata=xdata, ydata=0, method=method) assert_allclose(pcov0, pcov1) def test_args_in_kwargs(self): # Ensure that `args` cannot be passed as keyword argument to `curve_fit` def func(x, a, b): return a * x + b with assert_raises(ValueError): curve_fit(func, xdata=[1, 2, 3, 4], ydata=[5, 9, 13, 17], p0=[1], args=(1,)) def test_data_point_number_validation(self): def func(x, a, b, c, d, e): return a * np.exp(-b * x) + c + d + e with assert_raises(TypeError, match="The number of func parameters="): curve_fit(func, xdata=[1, 2, 3, 4], ydata=[5, 9, 13, 17]) @pytest.mark.filterwarnings('ignore::RuntimeWarning') def test_gh4555(self): # gh-4555 reported that covariance matrices returned by `leastsq` # can have negative diagonal elements and eigenvalues. (In fact, # they can also be asymmetric.) This shows up in the output of # `scipy.optimize.curve_fit`. Check that it has been resolved.giit def f(x, a, b, c, d, e): return a*np.log(x + 1 + b) + c*np.log(x + 1 + d) + e rng = np.random.default_rng(408113519974467917) n = 100 x = np.arange(n) y = np.linspace(2, 7, n) + rng.random(n) p, cov = optimize.curve_fit(f, x, y, maxfev=100000) assert np.all(np.diag(cov) > 0) eigs = linalg.eigh(cov)[0] # separate line for debugging # some platforms see a small negative eigevenvalue assert np.all(eigs > -1e-2) assert_allclose(cov, cov.T) def test_gh4555b(self): # check that PR gh-17247 did not significantly change covariance matrix # for simple cases rng = np.random.default_rng(408113519974467917) def func(x, a, b, c): return a * np.exp(-b * x) + c xdata = np.linspace(0, 4, 50) y = func(xdata, 2.5, 1.3, 0.5) y_noise = 0.2 * rng.normal(size=xdata.size) ydata = y + y_noise _, res = curve_fit(func, xdata, ydata) # reference from commit 1d80a2f254380d2b45733258ca42eb6b55c8755b ref = [[+0.0158972536486215, 0.0069207183284242, -0.0007474400714749], [+0.0069207183284242, 0.0205057958128679, +0.0053997711275403], [-0.0007474400714749, 0.0053997711275403, +0.0027833930320877]] # Linux_Python_38_32bit_full fails with default tolerance assert_allclose(res, ref, 2e-7) def test_gh13670(self): # gh-13670 reported that `curve_fit` executes callables # with the same values of the parameters at the beginning of # optimization. Check that this has been resolved. rng = np.random.default_rng(8250058582555444926) x = np.linspace(0, 3, 101) y = 2 * x + 1 + rng.normal(size=101) * 0.5 def line(x, *p): assert not np.all(line.last_p == p) line.last_p = p return x * p[0] + p[1] def jac(x, *p): assert not np.all(jac.last_p == p) jac.last_p = p return np.array([x, np.ones_like(x)]).T line.last_p = None jac.last_p = None p0 = np.array([1.0, 5.0]) curve_fit(line, x, y, p0, method='lm', jac=jac) @pytest.mark.parametrize('method', ['trf', 'dogbox']) def test_gh20155_error_mentions_x0(self, method): # `curve_fit` produced an error message that referred to an undocumented # variable `x0`, which was really `p0`. Check that this is resolved. def func(x,a): return x**a message = "Initial guess is outside of provided bounds" with pytest.raises(ValueError, match=message): curve_fit(func, self.x, self.y, p0=[1], bounds=(1000, 1001), method=method)
TestCurveFit
python
airbytehq__airbyte
airbyte-integrations/connectors/source-faker/source_faker/streams.py
{ "start": 4310, "end": 6705 }
class ____(Stream, IncrementalMixin): primary_key = "id" cursor_field = "updated_at" def __init__(self, count: int, seed: int, parallelism: int, records_per_slice: int, always_updated: bool, **kwargs): super().__init__(**kwargs) self.count = count self.seed = seed self.records_per_slice = records_per_slice self.parallelism = parallelism self.always_updated = always_updated self.generator = PurchaseGenerator(self.name, self.seed) @property def state_checkpoint_interval(self) -> Optional[int]: return self.records_per_slice @property def state(self) -> Mapping[str, Any]: if hasattr(self, "_state"): return self._state else: return {} @state.setter def state(self, value: Mapping[str, Any]): self._state = value def read_records(self, **kwargs) -> Iterable[Mapping[str, Any]]: """ This is a multi-process implementation of read_records. We make N workers (where N is the number of available CPUs) and spread out the CPU-bound work of generating records and serializing them to JSON """ if "updated_at" in self.state and not self.always_updated: return iter([]) updated_at = "" # a fuzzy guess, some users have purchases, some don't median_record_byte_size = 230 yield generate_estimate(self.name, (self.count) * 1.3, median_record_byte_size) loop_offset = 0 with Pool(initializer=self.generator.prepare, processes=self.parallelism) as pool: while loop_offset < self.count: records_remaining_this_loop = min(self.records_per_slice, (self.count - loop_offset)) carts = pool.map(self.generator.generate, range(loop_offset, loop_offset + records_remaining_this_loop)) for purchases in carts: loop_offset += 1 for purchase in purchases: updated_at = purchase.record.data["updated_at"] yield purchase if records_remaining_this_loop == 0: break self.state = {"seed": self.seed, "updated_at": updated_at, "loop_offset": loop_offset} self.state = {"seed": self.seed, "updated_at": updated_at, "loop_offset": loop_offset}
Purchases
python
walkccc__LeetCode
solutions/856. Score of Parentheses/856.py
{ "start": 0, "end": 232 }
class ____: def scoreOfParentheses(self, s: str) -> int: ans = 0 layer = 0 for a, b in itertools.pairwise(s): if a + b == '()': ans += 1 << layer layer += 1 if a == '(' else -1 return ans
Solution
python
pappasam__jedi-language-server
jedi_language_server/notebook_utils.py
{ "start": 8188, "end": 8541 }
class ____(LanguageServer): def __init__(self, server: LanguageServer): self._wrapped = server self._workspace = WorkspaceWrapper(server.workspace) @property def workspace(self) -> Workspace: return self._workspace def __getattr__(self, name: str) -> Any: return getattr(self._wrapped, name)
ServerWrapper
python
getsentry__sentry
tests/sentry/issues/test_occurrence_consumer.py
{ "start": 14787, "end": 27735 }
class ____(IssueOccurrenceTestBase): def run_test(self, message: dict[str, Any]) -> None: _get_kwargs(message) def run_invalid_schema_test( self, message: dict[str, Any], expected_error: type[Exception] ) -> None: with pytest.raises(expected_error): self.run_test(message) def run_invalid_payload_test( self, remove_event_fields: Sequence[str] | None = None, update_event_fields: dict[str, Any] | None = None, expected_error: type[Exception] = InvalidEventPayloadError, ) -> None: message = deepcopy(get_test_message(self.project.id)) if remove_event_fields: for field in remove_event_fields: message["event"].pop(field) if update_event_fields: message["event"].update(update_event_fields) self.run_invalid_schema_test(message, expected_error) def test_invalid_payload(self) -> None: self.run_invalid_payload_test( remove_event_fields=["project_id"], expected_error=InvalidEventPayloadError ) self.run_invalid_payload_test( remove_event_fields=["timestamp"], expected_error=ValidationError ) self.run_invalid_payload_test( remove_event_fields=["platform"], expected_error=ValidationError ) self.run_invalid_payload_test( update_event_fields={"project_id": "p_id"}, expected_error=InvalidEventPayloadError ) self.run_invalid_payload_test( update_event_fields={"platform": 0000}, expected_error=ValidationError ) self.run_invalid_payload_test( update_event_fields={"tags": "tagged"}, expected_error=ValidationError ) def test_valid(self) -> None: self.run_test(get_test_message(self.project.id)) def test_numeric_timestamp_valid_with_new_schema(self) -> None: # per https://develop.sentry.dev/sdk/event-payloads/ timestamp can be numeric message = deepcopy(get_test_message(self.project.id)) message["event"]["timestamp"] = 0000 self.run_test(message) def test_frame_additional_fields_valid_with_new_schema(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["event"]["stacktrace"]["frames"][0]["data"] = {"foo": "bar"} self.run_test(message) def test_tags_not_required_with_new_schema(self) -> None: # per https://develop.sentry.dev/sdk/event-payloads/ tags are optional message = deepcopy(get_test_message(self.project.id)) message["event"].pop("tags") self.run_test(message) def test_valid_nan(self) -> None: # NaN is invalid in new event schema, but valid in legacy schema, so it emits only one of the metrics message = deepcopy(get_test_message(self.project.id)) message["event"]["tags"]["nan-tag"] = float("nan") with mock.patch("sentry.issues.occurrence_consumer.metrics") as metrics: self.run_test(message) metrics.incr.assert_called_once_with( "occurrence_ingest.event_payload_invalid", sample_rate=mock.ANY, tags={"occurrence_type": mock.ANY}, ) def test_valid_nan_exception_log(self) -> None: # NaN is invalid in new event schema, but valid in legacy schema, so it emits logging, but doesn't raise message = deepcopy(get_test_message(self.project.id)) message["event"]["tags"]["nan-tag"] = float("nan") with self.assertLogs("sentry.issues.occurrence_consumer", logging.ERROR) as cm: self.run_test(message) assert ( "Error validating event payload, falling back to legacy validation" in cm.records[0].msg ) assert cm.records[0].exc_info is not None def test_invalid_payload_emits_both_metrics(self) -> None: with mock.patch("sentry.issues.occurrence_consumer.metrics") as metrics: self.run_invalid_payload_test( remove_event_fields=["timestamp"], expected_error=ValidationError ) metrics.incr.assert_has_calls( [ mock.call( "occurrence_ingest.event_payload_invalid", sample_rate=mock.ANY, tags={"occurrence_type": mock.ANY}, ), mock.call( "occurrence_ingest.legacy_event_payload_invalid", sample_rate=mock.ANY, tags={"occurrence_type": mock.ANY}, ), ] ) def test_missing_event_id_and_event_data(self) -> None: message = deepcopy(get_test_message(self.project.id)) message.pop("event_id", None) message.pop("event", None) with pytest.raises(InvalidEventPayloadError): _get_kwargs(message) def test_event_id_mismatch(self) -> None: """ if they're mismatched, we move forward and validate further down the line """ message = deepcopy(get_test_message(self.project.id)) message["event_id"] = uuid.uuid4().hex message["event"]["event_id"] = uuid.uuid4().hex kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["event_id"] == message["event_id"] assert kwargs["event_data"]["event_id"] == message["event"]["event_id"] def test_missing_top_level_event_id(self) -> None: message = deepcopy(get_test_message(self.project.id)) event_id = uuid.uuid4().hex message.pop("event_id", None) message["event"]["event_id"] = event_id kwargs = _get_kwargs(message) assert kwargs is not None assert kwargs["occurrence_data"]["event_id"] == kwargs["event_data"]["event_id"] == event_id def test_missing_event_id_in_event_data(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["event_id"] = "id1" message["event"].pop("event_id", None) with pytest.raises(InvalidEventPayloadError): _get_kwargs(message) def test_project_ids_mismatch(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["project_id"] = self.project.id message["event"]["project_id"] = 999999999999 with pytest.raises(InvalidEventPayloadError): _get_kwargs(message) def test_uuid_coercion(self) -> None: event_id = "0c6d75ac-3969-41e0-bc4b-33c2ff7f3657" occurrence_id = "b6e6e7d9-e582-40fd-8101-5666e96eb038" message = deepcopy(get_test_message(self.project.id, id=occurrence_id, event_id=event_id)) message["event"]["event_id"] = event_id kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["id"] == occurrence_id.replace("-", "") assert kwargs["occurrence_data"]["event_id"] == event_id.replace("-", "") assert kwargs["event_data"]["event_id"] == event_id.replace("-", "") def test_invalid_uuid(self) -> None: with pytest.raises(InvalidEventPayloadError): _get_kwargs(deepcopy(get_test_message(self.project.id, id="hi"))) with pytest.raises(InvalidEventPayloadError): _get_kwargs(deepcopy(get_test_message(self.project.id, event_id="hi"))) with pytest.raises(InvalidEventPayloadError): message = deepcopy(get_test_message(self.project.id)) message["event"]["event_id"] = "hi" _get_kwargs(message) def test_occurrence_title_on_event(self) -> None: message = deepcopy(get_test_message(self.project.id)) kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["issue_title"] == kwargs["event_data"]["metadata"]["title"] def test_occurrence_level_on_event(self) -> None: message = deepcopy(get_test_message(self.project.id)) kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["level"] == kwargs["event_data"]["level"] def test_debug_meta(self) -> None: debug_meta_cases = [ {"debug_meta": {}}, {"debug_meta": None}, {"debug_meta": {"images": []}}, {"debug_meta": {"images": None}}, {"debug_meta": {"images": [{}]}}, ] for case in debug_meta_cases: message = deepcopy(get_test_message(self.project.id, True)) message["event"].update(**case) _get_kwargs(message) def test_culprit(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["culprit"] = "i did it" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["culprit"] == "i did it" def test_priority(self) -> None: message = deepcopy(get_test_message(self.project.id)) kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["priority"] == PriorityLevel.LOW def test_priority_defaults_to_grouptype(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["priority"] = None kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["priority"] == PriorityLevel.LOW def test_priority_overrides_defaults(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["priority"] = PriorityLevel.HIGH kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["priority"] == PriorityLevel.HIGH def test_assignee(self) -> None: message = deepcopy(get_test_message(self.project.id)) message["assignee"] = f"user:{self.user.id}" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] == f"user:{self.user.id}" def test_assignee_perms(self) -> None: message = deepcopy(get_test_message(self.project.id)) random_user = self.create_user() message["assignee"] = f"user:{random_user.id}" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] is None message = deepcopy(get_test_message(self.project.id)) message["assignee"] = "user:99999999999" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] is None other_org = self.create_organization() random_team = self.create_team(other_org) message = deepcopy(get_test_message(self.project.id)) message["assignee"] = f"team:{random_team.id}" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] is None def test_assignee_none(self) -> None: kwargs = _get_kwargs(deepcopy(get_test_message(self.project.id))) assert kwargs["occurrence_data"]["assignee"] is None message = deepcopy(get_test_message(self.project.id)) message["assignee"] = None kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] is None message = deepcopy(get_test_message(self.project.id)) message["assignee"] = "" kwargs = _get_kwargs(message) assert kwargs["occurrence_data"]["assignee"] is None @mock.patch("sentry.issues.occurrence_consumer._process_message") def test_validate_cache(self, mock_process_message: mock.MagicMock) -> None: # Test to ensure cache is set properly after processing an occurrence group with mock.patch("django.core.cache.cache.set", side_effect=cache.set) as mock_cache_set: process_occurrence_group([{"id": 1}, {"id": 2}, {"id": 2}]) # Check if cache.set is called with the correct parameters expected_calls = [ mock.call("occurrence_consumer.process_occurrence_group.1", 1, 300), mock.call("occurrence_consumer.process_occurrence_group.2", 1, 300), ] mock_cache_set.assert_has_calls(expected_calls, any_order=True) assert mock_process_message.call_count == 2 def test_status_change(self) -> None: event = self.store_event( data={ "event_id": "a" * 32, "message": "oh no", "timestamp": datetime.datetime.now().isoformat(), "fingerprint": ["group-1"], }, project_id=self.project.id, ) group = event.group assert group.status == GroupStatus.UNRESOLVED status = GroupStatus.RESOLVED status_change = StatusChangeMessage( fingerprint=["group-1"], project_id=group.project_id, new_status=status, new_substatus=None, ) message = _prepare_status_change_message(status_change) assert message is not None process_occurrence_group([message]) group = Group.objects.get(id=group.id) assert group.status == status
ParseEventPayloadTest
python
donnemartin__interactive-coding-challenges
graphs_trees/bst_successor/test_bst_successor.py
{ "start": 18, "end": 1192 }
class ____(unittest.TestCase): def test_bst_successor_empty(self): bst_successor = BstSuccessor() bst_successor.get_next(None) def test_bst_successor(self): nodes = {} node = Node(5) nodes[5] = node bst = Bst(nodes[5]) nodes[3] = bst.insert(3) nodes[8] = bst.insert(8) nodes[2] = bst.insert(2) nodes[4] = bst.insert(4) nodes[6] = bst.insert(6) nodes[12] = bst.insert(12) nodes[1] = bst.insert(1) nodes[7] = bst.insert(7) nodes[10] = bst.insert(10) nodes[15] = bst.insert(15) nodes[9] = bst.insert(9) bst_successor = BstSuccessor() self.assertEqual(bst_successor.get_next(nodes[4]), 5) self.assertEqual(bst_successor.get_next(nodes[5]), 6) self.assertEqual(bst_successor.get_next(nodes[8]), 9) self.assertEqual(bst_successor.get_next(nodes[15]), None) print('Success: test_bst_successor') def main(): test = TestBstSuccessor() test.test_bst_successor() test.assertRaises(TypeError, test.test_bst_successor_empty) if __name__ == '__main__': main()
TestBstSuccessor
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-make-median-of-array-equal-to-k.py
{ "start": 68, "end": 1594 }
class ____(object): def minOperationsToMakeMedianK(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def nth_element(nums, n, left=0, compare=lambda a, b: a < b): def tri_partition(nums, left, right, target, compare): mid = left while mid <= right: if nums[mid] == target: mid += 1 elif compare(nums[mid], target): nums[left], nums[mid] = nums[mid], nums[left] left += 1 mid += 1 else: nums[mid], nums[right] = nums[right], nums[mid] right -= 1 return left, right right = len(nums)-1 while left <= right: pivot_idx = random.randint(left, right) pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare) if pivot_left <= n <= pivot_right: return elif pivot_left > n: right = pivot_left-1 else: # pivot_right < n. left = pivot_right+1 nth_element(nums, len(nums)//2) return (sum(max(nums[i]-k, 0) for i in xrange(len(nums)//2+1))+ sum(max(k-nums[i], 0) for i in xrange(len(nums)//2, len(nums)))) # Time: O(nlogn) # Space: O(1) # sort, greedy
Solution
python
django__django
django/db/models/fields/mixins.py
{ "start": 110, "end": 972 }
class ____: """ An API for working with the model's fields value cache. Subclasses must set self.cache_name to a unique entry for the cache - typically the field’s name. """ @cached_property def cache_name(self): raise NotImplementedError def get_cached_value(self, instance, default=NOT_PROVIDED): try: return instance._state.fields_cache[self.cache_name] except KeyError: if default is NOT_PROVIDED: raise return default def is_cached(self, instance): return self.cache_name in instance._state.fields_cache def set_cached_value(self, instance, value): instance._state.fields_cache[self.cache_name] = value def delete_cached_value(self, instance): del instance._state.fields_cache[self.cache_name]
FieldCacheMixin
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 86495, "end": 104983 }
class ____(NonStrictDataModel): """ :param id: Frame id :type id: str :param augmentation: List of augmentations :type augmentation: Sequence[Augmentation] :param timestamp: Frame's offset in milliseconds, used primarily for video content. Used for the default frames sorting as the secondary key (with the primary key being 'context_id'). For images, this value should typically be 0. If not set, value is filled from the timestamp of the first source. We recommend using this field only in cases concerning the default sorting behavior. :type timestamp: int :param dataset: Frame's dataset version :type dataset: DatasetVersion :param saved: Last time frame was saved (timestamp) :type saved: int :param saved_in_version: Last version this frame was saved in (version ID) :type saved_in_version: str :param updated: Last time frame was saved (timestamp) :type updated: int :param updated_in_version: Last version this frame was updated in (version ID) :type updated_in_version: str :param rois: Frame regions of interest :type rois: Sequence[Roi] :param labels_size: Number of labels returned :type labels_size: int :param rule_name: Name of the filtering rule according to which this frame was provided (if applicable) :type rule_name: str :param video_gop: Video encoding GOP value for the source of this frame. Only valid for video frames :type video_gop: float :param is_key_frame: Is this a key frame (only applicable in frames who'se src is a video) :type is_key_frame: bool :param key_frame: ID of the key frame that this frame belongs to :type key_frame: str :param meta: Additional metadata dictionary for the frame. Please note that using this field effectively defines a schema (dictionary structure and types used as values) - frames within the same dataset cannot use conflicting schemas for this field (see documentation for more details). :type meta: dict :param blob: Raw data (blob) for the frame :type blob: str :param meta_blob: Non searchable metadata dictionary for the frame. The fields in this object cannot be searched by and are not added to the frame schema :type meta_blob: dict :param new_ver: Newer version of this frame, if asked to merge :type new_ver: Frame :param label_rule_counts: The number of matched roi per lable rule :type label_rule_counts: dict :param sources: Sources of this frame :type sources: Sequence[Source] :param context_id: Context ID. Used for the default frames sorting. If not set then it is filled from the uri of the first source. :type context_id: str :param num_frames: Number of frames represented by this snippet :type num_frames: int """ _schema = { "properties": { "augmentation": { "description": "List of augmentations", "items": {"$ref": "#/definitions/augmentation"}, "type": ["array", "null"], }, "blob": { "description": "Raw data (blob) for the frame", "type": ["string", "null"], }, "context_id": { "description": ( "Context ID. Used for the default frames sorting. If not set then it is filled from the " "uri of the first source." ), "type": ["string", "null"], }, "dataset": { "description": "Frame's dataset version", "oneOf": [{"$ref": "#/definitions/dataset_version"}, {"type": "null"}], }, "id": {"description": "Frame id", "type": ["string", "null"]}, "is_key_frame": { "description": "Is this a key frame (only applicable in frames who'se src is a video)", "type": ["boolean", "null"], }, "key_frame": { "description": "ID of the key frame that this frame belongs to", "type": ["string", "null"], }, "label_rule_counts": { "additionalProperties": True, "description": "The number of matched roi per lable rule", "type": ["object", "null"], }, "labels_size": { "description": "Number of labels returned", "type": ["integer", "null"], }, "meta": { "additionalProperties": True, "description": ( "Additional metadata dictionary for the frame. Please note that using this field effectively" " defines a schema (dictionary structure and types used as values) - frames within the same dataset" " cannot use conflicting schemas for this field (see documentation for more details)." ), "type": ["object", "null"], }, "meta_blob": { "additionalProperties": True, "description": ( "Non searchable metadata dictionary for the frame. The fields in this object cannot be searched by" " and are not added to the frame schema" ), "type": ["object", "null"], }, "new_ver": { "description": "Newer version of this frame, if asked to merge", "oneOf": [{"$ref": "#/definitions/frame"}, {"type": "null"}], }, "num_frames": { "description": "Number of frames represented by this snippet", "type": ["integer", "null"], }, "rois": { "description": "Frame regions of interest", "items": {"$ref": "#/definitions/roi"}, "type": ["array", "null"], }, "rule_name": { "description": "Name of the filtering rule according to which this frame was provided (if applicable)", "type": ["string", "null"], }, "saved": { "description": "Last time frame was saved (timestamp)", "type": ["integer", "null"], }, "saved_in_version": { "description": "Last version this frame was saved in (version ID)", "type": ["string", "null"], }, "sources": { "description": "Sources of this frame", "items": {"$ref": "#/definitions/source"}, "type": ["array", "null"], }, "timestamp": { "description": ( "Frame's offset in milliseconds, used primarily for video content. Used for the default frames" " sorting as the secondary key (with the primary key being 'context_id'). For images, this value" " should typically be 0. If not set, value is filled from the timestamp of the first source. We" " recommend using this field only in cases concerning the default sorting behavior." ), "type": ["integer", "null"], }, "updated": { "description": "Last time frame was saved (timestamp)", "type": ["integer", "null"], }, "updated_in_version": { "description": "Last version this frame was updated in (version ID)", "type": ["string", "null"], }, "video_gop": { "description": "Video encoding GOP value for the source of this frame. Only valid for video frames", "type": ["number", "null"], }, }, "type": "object", } def __init__( self, id=None, augmentation=None, timestamp=None, dataset=None, saved=None, saved_in_version=None, updated=None, updated_in_version=None, rois=None, labels_size=None, rule_name=None, video_gop=None, is_key_frame=None, key_frame=None, meta=None, blob=None, meta_blob=None, new_ver=None, label_rule_counts=None, sources=None, context_id=None, num_frames=None, **kwargs ): super(Snippet, self).__init__(**kwargs) self.id = id self.augmentation = augmentation self.timestamp = timestamp self.dataset = dataset self.saved = saved self.saved_in_version = saved_in_version self.updated = updated self.updated_in_version = updated_in_version self.rois = rois self.labels_size = labels_size self.rule_name = rule_name self.video_gop = video_gop self.is_key_frame = is_key_frame self.key_frame = key_frame self.meta = meta self.blob = blob self.meta_blob = meta_blob self.new_ver = new_ver self.label_rule_counts = label_rule_counts self.sources = sources self.context_id = context_id self.num_frames = num_frames @schema_property("id") def id(self): return self._property_id @id.setter def id(self, value): if value is None: self._property_id = None return self.assert_isinstance(value, "id", six.string_types) self._property_id = value @schema_property("augmentation") def augmentation(self): return self._property_augmentation @augmentation.setter def augmentation(self, value): if value is None: self._property_augmentation = None return self.assert_isinstance(value, "augmentation", (list, tuple)) if any(isinstance(v, dict) for v in value): value = [ Augmentation.from_dict(v) if isinstance(v, dict) else v for v in value ] else: self.assert_isinstance(value, "augmentation", Augmentation, is_array=True) self._property_augmentation = value @schema_property("timestamp") def timestamp(self): return self._property_timestamp @timestamp.setter def timestamp(self, value): if value is None: self._property_timestamp = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "timestamp", six.integer_types) self._property_timestamp = value @schema_property("dataset") def dataset(self): return self._property_dataset @dataset.setter def dataset(self, value): if value is None: self._property_dataset = None return if isinstance(value, dict): value = DatasetVersion.from_dict(value) else: self.assert_isinstance(value, "dataset", DatasetVersion) self._property_dataset = value @schema_property("saved") def saved(self): return self._property_saved @saved.setter def saved(self, value): if value is None: self._property_saved = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "saved", six.integer_types) self._property_saved = value @schema_property("saved_in_version") def saved_in_version(self): return self._property_saved_in_version @saved_in_version.setter def saved_in_version(self, value): if value is None: self._property_saved_in_version = None return self.assert_isinstance(value, "saved_in_version", six.string_types) self._property_saved_in_version = value @schema_property("updated") def updated(self): return self._property_updated @updated.setter def updated(self, value): if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value @schema_property("updated_in_version") def updated_in_version(self): return self._property_updated_in_version @updated_in_version.setter def updated_in_version(self, value): if value is None: self._property_updated_in_version = None return self.assert_isinstance(value, "updated_in_version", six.string_types) self._property_updated_in_version = value @schema_property("rois") def rois(self): return self._property_rois @rois.setter def rois(self, value): if value is None: self._property_rois = None return self.assert_isinstance(value, "rois", (list, tuple)) if any(isinstance(v, dict) for v in value): value = [Roi.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "rois", Roi, is_array=True) self._property_rois = value @schema_property("labels_size") def labels_size(self): return self._property_labels_size @labels_size.setter def labels_size(self, value): if value is None: self._property_labels_size = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "labels_size", six.integer_types) self._property_labels_size = value @schema_property("rule_name") def rule_name(self): return self._property_rule_name @rule_name.setter def rule_name(self, value): if value is None: self._property_rule_name = None return self.assert_isinstance(value, "rule_name", six.string_types) self._property_rule_name = value @schema_property("video_gop") def video_gop(self): return self._property_video_gop @video_gop.setter def video_gop(self, value): if value is None: self._property_video_gop = None return self.assert_isinstance(value, "video_gop", six.integer_types + (float,)) self._property_video_gop = value @schema_property("is_key_frame") def is_key_frame(self): return self._property_is_key_frame @is_key_frame.setter def is_key_frame(self, value): if value is None: self._property_is_key_frame = None return self.assert_isinstance(value, "is_key_frame", (bool,)) self._property_is_key_frame = value @schema_property("key_frame") def key_frame(self): return self._property_key_frame @key_frame.setter def key_frame(self, value): if value is None: self._property_key_frame = None return self.assert_isinstance(value, "key_frame", six.string_types) self._property_key_frame = value @schema_property("meta") def meta(self): return self._property_meta @meta.setter def meta(self, value): if value is None: self._property_meta = None return self.assert_isinstance(value, "meta", (dict,)) self._property_meta = value @schema_property("blob") def blob(self): return self._property_blob @blob.setter def blob(self, value): if value is None: self._property_blob = None return self.assert_isinstance(value, "blob", six.string_types) self._property_blob = value @schema_property("meta_blob") def meta_blob(self): return self._property_meta_blob @meta_blob.setter def meta_blob(self, value): if value is None: self._property_meta_blob = None return self.assert_isinstance(value, "meta_blob", (dict,)) self._property_meta_blob = value @schema_property("new_ver") def new_ver(self): return self._property_new_ver @new_ver.setter def new_ver(self, value): if value is None: self._property_new_ver = None return if isinstance(value, dict): value = Frame.from_dict(value) else: self.assert_isinstance(value, "new_ver", Frame) self._property_new_ver = value @schema_property("label_rule_counts") def label_rule_counts(self): return self._property_label_rule_counts @label_rule_counts.setter def label_rule_counts(self, value): if value is None: self._property_label_rule_counts = None return self.assert_isinstance(value, "label_rule_counts", (dict,)) self._property_label_rule_counts = value @schema_property("sources") def sources(self): return self._property_sources @sources.setter def sources(self, value): if value is None: self._property_sources = None return self.assert_isinstance(value, "sources", (list, tuple)) if any(isinstance(v, dict) for v in value): value = [Source.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "sources", Source, is_array=True) self._property_sources = value @schema_property("context_id") def context_id(self): return self._property_context_id @context_id.setter def context_id(self, value): if value is None: self._property_context_id = None return self.assert_isinstance(value, "context_id", six.string_types) self._property_context_id = value @schema_property("num_frames") def num_frames(self): return self._property_num_frames @num_frames.setter def num_frames(self, value): if value is None: self._property_num_frames = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "num_frames", six.integer_types) self._property_num_frames = value
Snippet
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 58730, "end": 59075 }
class ____(BaseModel): usage: Optional["Usage"] = Field(default=None, description="") time: Optional[float] = Field(default=None, description="Time spent to process this request") status: Optional[str] = Field(default=None, description="") result: Optional["QueryResponse"] = Field(default=None, description="")
InlineResponse20021
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 4216, "end": 4841 }
class ____(sgqlc.types.Enum): """The possible states for a check suite or run status. Enumeration Choices: * `COMPLETED`: The check suite or run has been completed. * `IN_PROGRESS`: The check suite or run is in progress. * `PENDING`: The check suite or run is in pending state. * `QUEUED`: The check suite or run has been queued. * `REQUESTED`: The check suite or run has been requested. * `WAITING`: The check suite or run is in waiting state. """ __schema__ = github_schema __choices__ = ("COMPLETED", "IN_PROGRESS", "PENDING", "QUEUED", "REQUESTED", "WAITING")
CheckStatusState
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/contrib/regular_languages/regex_parser.py
{ "start": 2414, "end": 2974 }
class ____(Node): """ Mark a variable in the regular grammar. This will be translated into a named group. Each variable can have his own completer, validator, etc.. :param childnode: The grammar which is wrapped inside this variable. :param varname: String. """ def __init__(self, childnode: Node, varname: str = "") -> None: self.childnode = childnode self.varname = varname def __repr__(self) -> str: return f"{self.__class__.__name__}(childnode={self.childnode!r}, varname={self.varname!r})"
Variable
python
django__django
tests/auth_tests/models/with_integer_username.py
{ "start": 427, "end": 681 }
class ____(AbstractBaseUser): username = models.IntegerField() password = models.CharField(max_length=255) USERNAME_FIELD = "username" REQUIRED_FIELDS = ["username", "password"] objects = IntegerUsernameUserManager()
IntegerUsernameUser
python
jazzband__django-waffle
test_app/views.py
{ "start": 3198, "end": 3277 }
class ____(WaffleFlagMixin, BaseWaffleView): waffle_flag = '!foo'
FlagOffView
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataproc.py
{ "start": 20213, "end": 30503 }
class ____: def test_image_version(self): with pytest.raises(ValueError, match="custom_image and image_version"): ClusterGenerator( custom_image="custom_image", image_version="image_version", project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME, ) def test_custom_image_family_error_with_image_version(self): with pytest.raises(ValueError, match="image_version and custom_image_family"): ClusterGenerator( image_version="image_version", custom_image_family="custom_image_family", project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME, ) def test_custom_image_family_error_with_custom_image(self): with pytest.raises(ValueError, match="custom_image and custom_image_family"): ClusterGenerator( custom_image="custom_image", custom_image_family="custom_image_family", project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME, ) def test_nodes_number(self): with pytest.raises(ValueError, match="Single node cannot have preemptible workers"): ClusterGenerator( num_workers=0, num_preemptible_workers=1, project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME ) def test_min_num_workers_less_than_num_workers(self): with pytest.raises( ValueError, match="The value of min_num_workers must be less than or equal to num_workers. " r"Provided 4\(min_num_workers\) and 3\(num_workers\).", ): ClusterGenerator( num_workers=3, min_num_workers=4, project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME ) def test_min_num_workers_without_num_workers(self): with pytest.raises(ValueError, match="Must specify num_workers when min_num_workers are provided."): ClusterGenerator(min_num_workers=4, project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME) def test_build(self): generator = ClusterGenerator( project_id="project_id", num_workers=2, min_num_workers=1, zone="zone", network_uri="network_uri", subnetwork_uri="subnetwork_uri", internal_ip_only=True, tags=["tags"], storage_bucket="storage_bucket", init_actions_uris=["init_actions_uris"], init_action_timeout="10m", metadata={"metadata": "data"}, custom_image="custom_image", custom_image_project_id="custom_image_project_id", autoscaling_policy="autoscaling_policy", properties={"properties": "data"}, optional_components=["optional_components"], num_masters=2, master_machine_type="master_machine_type", master_disk_type="master_disk_type", master_disk_size=128, worker_machine_type="worker_machine_type", worker_disk_type="worker_disk_type", worker_disk_size=256, num_preemptible_workers=4, preemptibility="Spot", region="region", service_account="service_account", service_account_scopes=["service_account_scopes"], idle_delete_ttl=60, auto_delete_time=datetime(2019, 9, 12), auto_delete_ttl=250, customer_managed_key="customer_managed_key", driver_pool_id="cluster_driver_pool", driver_pool_size=2, cluster_tier="CLUSTER_TIER_STANDARD", ) cluster = generator.make() assert cluster == CONFIG def test_build_with_custom_image_family(self): generator = ClusterGenerator( project_id="project_id", num_workers=2, zone="zone", network_uri="network_uri", subnetwork_uri="subnetwork_uri", internal_ip_only=True, tags=["tags"], storage_bucket="storage_bucket", init_actions_uris=["init_actions_uris"], init_action_timeout="10m", metadata={"metadata": "data"}, custom_image_family="custom_image_family", custom_image_project_id="custom_image_project_id", autoscaling_policy="autoscaling_policy", properties={"properties": "data"}, optional_components=["optional_components"], num_masters=2, master_machine_type="master_machine_type", master_disk_type="master_disk_type", master_disk_size=128, worker_machine_type="worker_machine_type", worker_disk_type="worker_disk_type", worker_disk_size=256, num_preemptible_workers=4, preemptibility="Spot", region="region", service_account="service_account", service_account_scopes=["service_account_scopes"], idle_delete_ttl=60, auto_delete_time=datetime(2019, 9, 12), auto_delete_ttl=250, customer_managed_key="customer_managed_key", enable_component_gateway=True, ) cluster = generator.make() assert cluster == CONFIG_WITH_CUSTOM_IMAGE_FAMILY def test_build_with_flex_migs(self): generator = ClusterGenerator( project_id="project_id", num_workers=2, zone="zone", network_uri="network_uri", subnetwork_uri="subnetwork_uri", internal_ip_only=True, tags=["tags"], storage_bucket="storage_bucket", init_actions_uris=["init_actions_uris"], init_action_timeout="10m", metadata={"metadata": "data"}, custom_image="custom_image", custom_image_project_id="custom_image_project_id", autoscaling_policy="autoscaling_policy", properties={"properties": "data"}, optional_components=["optional_components"], num_masters=2, master_machine_type="master_machine_type", master_disk_type="master_disk_type", master_disk_size=128, worker_machine_type="worker_machine_type", worker_disk_type="worker_disk_type", worker_disk_size=256, num_preemptible_workers=4, preemptibility="Spot", region="region", service_account="service_account", service_account_scopes=["service_account_scopes"], idle_delete_ttl=60, auto_delete_time=datetime(2019, 9, 12), auto_delete_ttl=250, customer_managed_key="customer_managed_key", secondary_worker_instance_flexibility_policy=InstanceFlexibilityPolicy( [ InstanceSelection( [ "projects/project_id/zones/zone/machineTypes/machine1", "projects/project_id/zones/zone/machineTypes/machine2", ], 0, ), InstanceSelection(["projects/project_id/zones/zone/machineTypes/machine3"], 1), ] ), ) cluster = generator.make() assert cluster == CONFIG_WITH_FLEX_MIG def test_build_with_gpu_accelerator(self): generator = ClusterGenerator( project_id="project_id", num_workers=2, min_num_workers=1, zone="zone", network_uri="network_uri", subnetwork_uri="subnetwork_uri", internal_ip_only=True, tags=["tags"], storage_bucket="storage_bucket", init_actions_uris=["init_actions_uris"], init_action_timeout="10m", metadata={"metadata": "data"}, custom_image="custom_image", custom_image_project_id="custom_image_project_id", autoscaling_policy="autoscaling_policy", properties={"properties": "data"}, optional_components=["optional_components"], num_masters=2, master_machine_type="master_machine_type", master_disk_type="master_disk_type", master_disk_size=128, master_accelerator_type="master_accelerator_type", master_accelerator_count=1, worker_machine_type="worker_machine_type", worker_disk_type="worker_disk_type", worker_disk_size=256, worker_accelerator_type="worker_accelerator_type", worker_accelerator_count=1, num_preemptible_workers=4, secondary_worker_accelerator_type="secondary_worker_accelerator_type", secondary_worker_accelerator_count=1, preemptibility="preemptible", region="region", service_account="service_account", service_account_scopes=["service_account_scopes"], idle_delete_ttl=60, auto_delete_time=datetime(2019, 9, 12), auto_delete_ttl=250, customer_managed_key="customer_managed_key", ) cluster = generator.make() assert cluster == CONFIG_WITH_GPU_ACCELERATOR def test_build_with_default_value_for_internal_ip_only(self): generator = ClusterGenerator(project_id="project_id") cluster = generator.make() assert "internal_ip_only" not in cluster["gce_cluster_config"] def test_build_sets_provided_value_for_internal_ip_only(self): for internal_ip_only in [True, False]: generator = ClusterGenerator( project_id="project_id", internal_ip_only=internal_ip_only, subnetwork_uri="subnetwork_uri" ) cluster = generator.make() assert cluster["gce_cluster_config"]["internal_ip_only"] == internal_ip_only def test_build_with_cluster_tier(self): generator = ClusterGenerator(project_id="project_id", cluster_tier="CLUSTER_TIER_STANDARD") cluster = generator.make() assert cluster["cluster_tier"] == "CLUSTER_TIER_STANDARD"
TestsClusterGenerator
python
coleifer__peewee
peewee.py
{ "start": 160302, "end": 160371 }
class ____(IntegerField): field_type = 'SMALLINT'
SmallIntegerField
python
pdm-project__pdm
src/pdm/builders/editable.py
{ "start": 102, "end": 1060 }
class ____(EnvBuilder): """Build egg-info in isolated env with managed Python.""" @wrap_error def prepare_metadata(self, out_dir: str) -> str: if self.isolated: self.install(self._requires, shared=True) requires = self._hook.get_requires_for_build_editable(self.config_settings) self.install(requires) filename = self._hook.prepare_metadata_for_build_editable(out_dir, self.config_settings) return os.path.join(out_dir, filename) @wrap_error def build(self, out_dir: str, metadata_directory: str | None = None) -> str: if self.isolated: self.install(self._requires, shared=True) requires = self._hook.get_requires_for_build_editable(self.config_settings) self.install(requires) filename = self._hook.build_editable(out_dir, self.config_settings, metadata_directory) return os.path.join(out_dir, filename)
EditableBuilder
python
Textualize__textual
src/textual/css/tokenize.py
{ "start": 6965, "end": 9283 }
class ____: """State machine for the tokenizer. Attributes: EXPECT: The initial expectation of the tokenizer. Since we start tokenizing at the root scope, we might expect to see either a variable or selector, for example. STATE_MAP: Maps token names to Expects, defines the sets of valid tokens that we'd expect to see next, given the current token. For example, if we've just processed a variable declaration name, we next expect to see the value of that variable. """ EXPECT = expect_root_scope STATE_MAP = { "variable_name": expect_variable_name_continue, "variable_value_end": expect_root_scope, "selector_start": expect_selector_continue, "selector_start_id": expect_selector_continue, "selector_start_class": expect_selector_continue, "selector_start_universal": expect_selector_continue, "selector_id": expect_selector_continue, "selector_class": expect_selector_continue, "selector_universal": expect_selector_continue, "declaration_set_start": expect_declaration, "declaration_name": expect_declaration_content, "declaration_end": expect_declaration, "declaration_set_end": expect_root_nested, "nested": expect_selector_continue, } def __call__(self, code: str, read_from: CSSLocation) -> Iterable[Token]: tokenizer = Tokenizer(code, read_from=read_from) expect = self.EXPECT get_token = tokenizer.get_token get_state = self.STATE_MAP.get nest_level = 0 while True: token = get_token(expect) name = token.name if name == "comment_line": continue elif name == "comment_start": tokenizer.skip_to(expect_comment_end) continue elif name == "eof": break elif name == "declaration_set_start": nest_level += 1 elif name == "declaration_set_end": nest_level -= 1 expect = expect_declaration if nest_level else expect_root_scope yield token continue expect = get_state(name, expect) yield token
TCSSTokenizerState
python
sphinx-doc__sphinx
tests/roots/test-ext-autosummary/autosummary_dummy_module.py
{ "start": 669, "end": 961 }
class ____(Exception): pass #: a module-level attribute qux = 2 #: a module-level attribute that has been excluded from __all__ quuz = 2 considered_as_imported = Class() non_imported_member = Class() """ This attribute has a docstring, so it is recognized as a not-imported member """
_Exc
python
walkccc__LeetCode
solutions/37. Sudoku Solver/37.py
{ "start": 0, "end": 703 }
class ____: def solveSudoku(self, board: list[list[str]]) -> None: def isValid(row: int, col: int, c: str) -> bool: for i in range(9): if (board[i][col] == c or board[row][i] == c or board[3 * (row // 3) + i // 3][3 * (col // 3) + i % 3] == c): return False return True def solve(s: int) -> bool: if s == 81: return True i = s // 9 j = s % 9 if board[i][j] != '.': return solve(s + 1) for c in string.digits[1:]: if isValid(i, j, c): board[i][j] = c if solve(s + 1): return True board[i][j] = '.' return False solve(0)
Solution
python
doocs__leetcode
lcof/面试题33. 二叉搜索树的后序遍历序列/Solution.py
{ "start": 0, "end": 441 }
class ____: def verifyPostorder(self, postorder: List[int]) -> bool: def dfs(l, r): if l >= r: return True v = postorder[r] i = l while i < r and postorder[i] < v: i += 1 if any(x < v for x in postorder[i:r]): return False return dfs(l, i - 1) and dfs(i, r - 1) return dfs(0, len(postorder) - 1)
Solution
python
justquick__django-activity-stream
actstream/admin.py
{ "start": 559, "end": 883 }
class ____(ModelAdmin): list_display = ('__str__', 'user', 'follow_object', 'actor_only', 'started') list_editable = ('user',) list_filter = ('user', 'started',) raw_id_fields = ('user', 'content_type') admin.site.register(models.Action, ActionAdmin) admin.site.register(models.Follow, FollowAdmin)
FollowAdmin
python
jupyterlab__jupyterlab
jupyterlab/handlers/announcements.py
{ "start": 3818, "end": 4545 }
class ____(CheckForUpdateABC): """Check update version that does nothing. This is provided for administrators that want to turn off requesting external resources. Args: version: Current JupyterLab version Attributes: version - str: Current JupyterLab version logger - logging.Logger: Server logger """ async def __call__(self) -> Awaitable[None]: """Get the notification message if a new version is available. Returns: None if there is no update. or the notification message or the notification message and a tuple(label, URL link) for the user to get more information """ return None
NeverCheckForUpdate
python
redis__redis-py
redis/exceptions.py
{ "start": 4103, "end": 4376 }
class ____(ResponseError): """ Error indicated CROSSSLOT error received from cluster. A CROSSSLOT error is generated when keys in a request don't hash to the same slot. """ message = "Keys in request don't hash to the same slot"
ClusterCrossSlotError
python
astropy__astropy
astropy/extern/ply/yacc.py
{ "start": 116966, "end": 137736 }
class ____(object): def __init__(self, pdict, log=None): self.pdict = pdict self.start = None self.error_func = None self.tokens = None self.modules = set() self.grammar = [] self.error = False if log is None: self.log = PlyLogger(sys.stderr) else: self.log = log # Get all of the basic information def get_all(self): self.get_start() self.get_error_func() self.get_tokens() self.get_precedence() self.get_pfunctions() # Validate all of the information def validate_all(self): self.validate_start() self.validate_error_func() self.validate_tokens() self.validate_precedence() self.validate_pfunctions() self.validate_modules() return self.error # Compute a signature over the grammar def signature(self): parts = [] try: if self.start: parts.append(self.start) if self.prec: parts.append(''.join([''.join(p) for p in self.prec])) if self.tokens: parts.append(' '.join(self.tokens)) for f in self.pfuncs: if f[3]: parts.append(f[3]) except (TypeError, ValueError): pass return ''.join(parts) # ----------------------------------------------------------------------------- # validate_modules() # # This method checks to see if there are duplicated p_rulename() functions # in the parser module file. Without this function, it is really easy for # users to make mistakes by cutting and pasting code fragments (and it's a real # bugger to try and figure out why the resulting parser doesn't work). Therefore, # we just do a little regular expression pattern matching of def statements # to try and detect duplicates. # ----------------------------------------------------------------------------- def validate_modules(self): # Match def p_funcname( fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(') for module in self.modules: try: lines, linen = inspect.getsourcelines(module) except IOError: continue counthash = {} for linen, line in enumerate(lines): linen += 1 m = fre.match(line) if m: name = m.group(1) prev = counthash.get(name) if not prev: counthash[name] = linen else: filename = inspect.getsourcefile(module) self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d', filename, linen, name, prev) # Get the start symbol def get_start(self): self.start = self.pdict.get('start') # Validate the start symbol def validate_start(self): if self.start is not None: if not isinstance(self.start, string_types): self.log.error("'start' must be a string") # Look for error handler def get_error_func(self): self.error_func = self.pdict.get('p_error') # Validate the error function def validate_error_func(self): if self.error_func: if isinstance(self.error_func, types.FunctionType): ismethod = 0 elif isinstance(self.error_func, types.MethodType): ismethod = 1 else: self.log.error("'p_error' defined, but is not a function or method") self.error = True return eline = self.error_func.__code__.co_firstlineno efile = self.error_func.__code__.co_filename module = inspect.getmodule(self.error_func) self.modules.add(module) argcount = self.error_func.__code__.co_argcount - ismethod if argcount != 1: self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) self.error = True # Get the tokens map def get_tokens(self): tokens = self.pdict.get('tokens') if not tokens: self.log.error('No token list is defined') self.error = True return if not isinstance(tokens, (list, tuple)): self.log.error('tokens must be a list or tuple') self.error = True return if not tokens: self.log.error('tokens is empty') self.error = True return self.tokens = sorted(tokens) # Validate the tokens def validate_tokens(self): # Validate the tokens. if 'error' in self.tokens: self.log.error("Illegal token name 'error'. Is a reserved word") self.error = True return terminals = set() for n in self.tokens: if n in terminals: self.log.warning('Token %r multiply defined', n) terminals.add(n) # Get the precedence map (if any) def get_precedence(self): self.prec = self.pdict.get('precedence') # Validate and parse the precedence map def validate_precedence(self): preclist = [] if self.prec: if not isinstance(self.prec, (list, tuple)): self.log.error('precedence must be a list or tuple') self.error = True return for level, p in enumerate(self.prec): if not isinstance(p, (list, tuple)): self.log.error('Bad precedence table') self.error = True return if len(p) < 2: self.log.error('Malformed precedence entry %s. Must be (assoc, term, ..., term)', p) self.error = True return assoc = p[0] if not isinstance(assoc, string_types): self.log.error('precedence associativity must be a string') self.error = True return for term in p[1:]: if not isinstance(term, string_types): self.log.error('precedence items must be strings') self.error = True return preclist.append((term, assoc, level+1)) self.preclist = preclist # Get all p_functions from the grammar def get_pfunctions(self): p_functions = [] for name, item in self.pdict.items(): if not name.startswith('p_') or name == 'p_error': continue if isinstance(item, (types.FunctionType, types.MethodType)): line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno) module = inspect.getmodule(item) p_functions.append((line, module, name, item.__doc__)) # Sort all of the actions by line number; make sure to stringify # modules to make them sortable, since `line` may not uniquely sort all # p functions p_functions.sort(key=lambda p_function: ( p_function[0], str(p_function[1]), p_function[2], p_function[3])) self.pfuncs = p_functions # Validate all of the p_functions def validate_pfunctions(self): grammar = [] # Check for non-empty symbols if len(self.pfuncs) == 0: self.log.error('no rules of the form p_rulename are defined') self.error = True return for line, module, name, doc in self.pfuncs: file = inspect.getsourcefile(module) func = self.pdict[name] if isinstance(func, types.MethodType): reqargs = 2 else: reqargs = 1 if func.__code__.co_argcount > reqargs: self.log.error('%s:%d: Rule %r has too many arguments', file, line, func.__name__) self.error = True elif func.__code__.co_argcount < reqargs: self.log.error('%s:%d: Rule %r requires an argument', file, line, func.__name__) self.error = True elif not func.__doc__: self.log.warning('%s:%d: No documentation string specified in function %r (ignored)', file, line, func.__name__) else: try: parsed_g = parse_grammar(doc, file, line) for g in parsed_g: grammar.append((name, g)) except SyntaxError as e: self.log.error(str(e)) self.error = True # Looks like a valid grammar rule # Mark the file in which defined. self.modules.add(module) # Secondary validation step that looks for p_ definitions that are not functions # or functions that look like they might be grammar rules. for n, v in self.pdict.items(): if n.startswith('p_') and isinstance(v, (types.FunctionType, types.MethodType)): continue if n.startswith('t_'): continue if n.startswith('p_') and n != 'p_error': self.log.warning('%r not defined as a function', n) if ((isinstance(v, types.FunctionType) and v.__code__.co_argcount == 1) or (isinstance(v, types.MethodType) and v.__func__.__code__.co_argcount == 2)): if v.__doc__: try: doc = v.__doc__.split(' ') if doc[1] == ':': self.log.warning('%s:%d: Possible grammar rule %r defined without p_ prefix', v.__code__.co_filename, v.__code__.co_firstlineno, n) except IndexError: pass self.grammar = grammar # ----------------------------------------------------------------------------- # yacc(module) # # Build a parser # ----------------------------------------------------------------------------- def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None, check_recursion=True, optimize=False, write_tables=True, debugfile=debug_file, outputdir=None, debuglog=None, errorlog=None, picklefile=None): if tabmodule is None: tabmodule = tab_module # Reference to the parsing method of the last built parser global parse # If pickling is enabled, table files are not created if picklefile: write_tables = 0 if errorlog is None: errorlog = PlyLogger(sys.stderr) # Get the module dictionary used for the parser if module: _items = [(k, getattr(module, k)) for k in dir(module)] pdict = dict(_items) # If no __file__ or __package__ attributes are available, try to obtain them # from the __module__ instead if '__file__' not in pdict: pdict['__file__'] = sys.modules[pdict['__module__']].__file__ if '__package__' not in pdict and '__module__' in pdict: if hasattr(sys.modules[pdict['__module__']], '__package__'): pdict['__package__'] = sys.modules[pdict['__module__']].__package__ else: pdict = get_caller_module_dict(2) if outputdir is None: # If no output directory is set, the location of the output files # is determined according to the following rules: # - If tabmodule specifies a package, files go into that package directory # - Otherwise, files go in the same directory as the specifying module if isinstance(tabmodule, types.ModuleType): srcfile = tabmodule.__file__ else: if '.' not in tabmodule: srcfile = pdict['__file__'] else: parts = tabmodule.split('.') pkgname = '.'.join(parts[:-1]) exec('import %s' % pkgname) srcfile = getattr(sys.modules[pkgname], '__file__', '') outputdir = os.path.dirname(srcfile) # Determine if the module is package of a package or not. # If so, fix the tabmodule setting so that tables load correctly pkg = pdict.get('__package__') if pkg and isinstance(tabmodule, str): if '.' not in tabmodule: tabmodule = pkg + '.' + tabmodule # Set start symbol if it's specified directly using an argument if start is not None: pdict['start'] = start # Collect parser information from the dictionary pinfo = ParserReflect(pdict, log=errorlog) pinfo.get_all() if pinfo.error: raise YaccError('Unable to build parser') # Check signature against table files (if any) signature = pinfo.signature() # Read the tables try: lr = LRTable() if picklefile: read_signature = lr.read_pickle(picklefile) else: read_signature = lr.read_table(tabmodule) if optimize or (read_signature == signature): try: lr.bind_callables(pinfo.pdict) parser = LRParser(lr, pinfo.error_func) parse = parser.parse return parser except Exception as e: errorlog.warning('There was a problem loading the table file: %r', e) except VersionError as e: errorlog.warning(str(e)) except ImportError: pass if debuglog is None: if debug: try: debuglog = PlyLogger(open(os.path.join(outputdir, debugfile), 'w')) except IOError as e: errorlog.warning("Couldn't open %r. %s" % (debugfile, e)) debuglog = NullLogger() else: debuglog = NullLogger() debuglog.info('Created by PLY version %s (http://www.dabeaz.com/ply)', __version__) errors = False # Validate the parser information if pinfo.validate_all(): raise YaccError('Unable to build parser') if not pinfo.error_func: errorlog.warning('no p_error() function is defined') # Create a grammar object grammar = Grammar(pinfo.tokens) # Set precedence level for terminals for term, assoc, level in pinfo.preclist: try: grammar.set_precedence(term, assoc, level) except GrammarError as e: errorlog.warning('%s', e) # Add productions to the grammar for funcname, gram in pinfo.grammar: file, line, prodname, syms = gram try: grammar.add_production(prodname, syms, funcname, file, line) except GrammarError as e: errorlog.error('%s', e) errors = True # Set the grammar start symbols try: if start is None: grammar.set_start(pinfo.start) else: grammar.set_start(start) except GrammarError as e: errorlog.error(str(e)) errors = True if errors: raise YaccError('Unable to build parser') # Verify the grammar structure undefined_symbols = grammar.undefined_symbols() for sym, prod in undefined_symbols: errorlog.error('%s:%d: Symbol %r used, but not defined as a token or a rule', prod.file, prod.line, sym) errors = True unused_terminals = grammar.unused_terminals() if unused_terminals: debuglog.info('') debuglog.info('Unused terminals:') debuglog.info('') for term in unused_terminals: errorlog.warning('Token %r defined, but not used', term) debuglog.info(' %s', term) # Print out all productions to the debug log if debug: debuglog.info('') debuglog.info('Grammar') debuglog.info('') for n, p in enumerate(grammar.Productions): debuglog.info('Rule %-5d %s', n, p) # Find unused non-terminals unused_rules = grammar.unused_rules() for prod in unused_rules: errorlog.warning('%s:%d: Rule %r defined, but not used', prod.file, prod.line, prod.name) if len(unused_terminals) == 1: errorlog.warning('There is 1 unused token') if len(unused_terminals) > 1: errorlog.warning('There are %d unused tokens', len(unused_terminals)) if len(unused_rules) == 1: errorlog.warning('There is 1 unused rule') if len(unused_rules) > 1: errorlog.warning('There are %d unused rules', len(unused_rules)) if debug: debuglog.info('') debuglog.info('Terminals, with rules where they appear') debuglog.info('') terms = list(grammar.Terminals) terms.sort() for term in terms: debuglog.info('%-20s : %s', term, ' '.join([str(s) for s in grammar.Terminals[term]])) debuglog.info('') debuglog.info('Nonterminals, with rules where they appear') debuglog.info('') nonterms = list(grammar.Nonterminals) nonterms.sort() for nonterm in nonterms: debuglog.info('%-20s : %s', nonterm, ' '.join([str(s) for s in grammar.Nonterminals[nonterm]])) debuglog.info('') if check_recursion: unreachable = grammar.find_unreachable() for u in unreachable: errorlog.warning('Symbol %r is unreachable', u) infinite = grammar.infinite_cycles() for inf in infinite: errorlog.error('Infinite recursion detected for symbol %r', inf) errors = True unused_prec = grammar.unused_precedence() for term, assoc in unused_prec: errorlog.error('Precedence rule %r defined for unknown symbol %r', assoc, term) errors = True if errors: raise YaccError('Unable to build parser') # Run the LRGeneratedTable on the grammar if debug: errorlog.debug('Generating %s tables', method) lr = LRGeneratedTable(grammar, method, debuglog) if debug: num_sr = len(lr.sr_conflicts) # Report shift/reduce and reduce/reduce conflicts if num_sr == 1: errorlog.warning('1 shift/reduce conflict') elif num_sr > 1: errorlog.warning('%d shift/reduce conflicts', num_sr) num_rr = len(lr.rr_conflicts) if num_rr == 1: errorlog.warning('1 reduce/reduce conflict') elif num_rr > 1: errorlog.warning('%d reduce/reduce conflicts', num_rr) # Write out conflicts to the output file if debug and (lr.sr_conflicts or lr.rr_conflicts): debuglog.warning('') debuglog.warning('Conflicts:') debuglog.warning('') for state, tok, resolution in lr.sr_conflicts: debuglog.warning('shift/reduce conflict for %s in state %d resolved as %s', tok, state, resolution) already_reported = set() for state, rule, rejected in lr.rr_conflicts: if (state, id(rule), id(rejected)) in already_reported: continue debuglog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) debuglog.warning('rejected rule (%s) in state %d', rejected, state) errorlog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) errorlog.warning('rejected rule (%s) in state %d', rejected, state) already_reported.add((state, id(rule), id(rejected))) warned_never = [] for state, rule, rejected in lr.rr_conflicts: if not rejected.reduced and (rejected not in warned_never): debuglog.warning('Rule (%s) is never reduced', rejected) errorlog.warning('Rule (%s) is never reduced', rejected) warned_never.append(rejected) # Write the table file if requested if write_tables: try: lr.write_table(tabmodule, outputdir, signature) if tabmodule in sys.modules: del sys.modules[tabmodule] except IOError as e: errorlog.warning("Couldn't create %r. %s" % (tabmodule, e)) # Write a pickled version of the tables if picklefile: try: lr.pickle_table(picklefile, signature) except IOError as e: errorlog.warning("Couldn't create %r. %s" % (picklefile, e)) # Build the parser lr.bind_callables(pinfo.pdict) parser = LRParser(lr, pinfo.error_func) parse = parser.parse return parser
ParserReflect
python
bokeh__bokeh
tests/unit/bokeh/core/test_has_props.py
{ "start": 2570, "end": 2632 }
class ____(Parent): int1 = Override(default=20)
OverrideChild
python
networkx__networkx
networkx/algorithms/assortativity/tests/test_pairs.py
{ "start": 1675, "end": 3008 }
class ____(BaseTestDegreeMixing): def test_node_degree_xy_undirected(self): xy = sorted(nx.node_degree_xy(self.P4)) xy_result = sorted([(1, 2), (2, 1), (2, 2), (2, 2), (1, 2), (2, 1)]) assert xy == xy_result def test_node_degree_xy_undirected_nodes(self): xy = sorted(nx.node_degree_xy(self.P4, nodes=[0, 1, -1])) xy_result = sorted([(1, 2), (2, 1)]) assert xy == xy_result def test_node_degree_xy_directed(self): xy = sorted(nx.node_degree_xy(self.D)) xy_result = sorted([(2, 1), (2, 3), (1, 3), (1, 3)]) assert xy == xy_result def test_node_degree_xy_multigraph(self): xy = sorted(nx.node_degree_xy(self.M)) xy_result = sorted( [(2, 3), (2, 3), (3, 2), (3, 2), (2, 3), (3, 2), (1, 2), (2, 1)] ) assert xy == xy_result def test_node_degree_xy_selfloop(self): xy = sorted(nx.node_degree_xy(self.S)) xy_result = sorted([(2, 2), (2, 2)]) assert xy == xy_result def test_node_degree_xy_weighted(self): G = nx.Graph() G.add_edge(1, 2, weight=7) G.add_edge(2, 3, weight=10) xy = sorted(nx.node_degree_xy(G, weight="weight")) xy_result = sorted([(7, 17), (17, 10), (17, 7), (10, 17)]) assert xy == xy_result
TestDegreeMixingXY
python
matplotlib__matplotlib
lib/matplotlib/_mathtext.py
{ "start": 35181, "end": 35346 }
class ____(FontConstantsBase): script_space = 0.1 sup1 = 0.8 sub2 = 0.6 delta = 0.05 delta_slanted = 0.3 delta_integral = 0.3
STIXFontConstants
python
nedbat__coveragepy
tests/test_debug.py
{ "start": 13289, "end": 15473 }
class ____(CoverageTest): """Tests of coverage.debug.short_stack.""" run_in_temp_dir = False def test_short_stack(self) -> None: stack = f_one().splitlines() assert 4 == len(stack) assert "test_short_stack" in stack[0] assert "f_one" in stack[1] assert "f_two" in stack[2] assert "f_three" in stack[3] def test_short_stack_skip(self) -> None: stack = f_one(skip=1).splitlines() assert 3 == len(stack) assert "test_short_stack" in stack[0] assert "f_one" in stack[1] assert "f_two" in stack[2] def test_short_stack_full(self) -> None: stack_text = f_one(full=True) s = re.escape(os.sep) if env.WINDOWS: pylib = "[Ll]ib" else: py = "pypy" if env.PYPY else "python" majv, minv = sys.version_info[:2] pylib = f"lib{s}{py}{majv}.{minv}{sys.abiflags}" assert len(re_lines(rf"{s}{pylib}{s}site-packages{s}_pytest", stack_text)) > 3 assert len(re_lines(rf"{s}{pylib}{s}site-packages{s}pluggy", stack_text)) > 3 assert not re_lines(r" 0x[0-9a-fA-F]+", stack_text) # No frame ids stack = stack_text.splitlines() assert len(stack) > 25 assert "test_short_stack" in stack[-4] assert "f_one" in stack[-3] assert "f_two" in stack[-2] assert "f_three" in stack[-1] def test_short_stack_short_filenames(self) -> None: stack_text = f_one(full=True, short_filenames=True) s = re.escape(os.sep) assert not re_lines(r"site-packages", stack_text) assert len(re_lines(rf"syspath:{s}_pytest", stack_text)) > 3 assert len(re_lines(rf"syspath:{s}pluggy", stack_text)) > 3 def test_short_stack_frame_ids(self) -> None: stack = f_one(full=True, frame_ids=True).splitlines() assert len(stack) > 25 frame_ids = [m[0] for line in stack if (m := re.search(r" 0x[0-9a-fA-F]{6,}", line))] # Every line has a frame id. assert len(frame_ids) == len(stack) # All the frame ids are different. assert len(set(frame_ids)) == len(frame_ids)
ShortStackTest
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_repositories.py
{ "start": 360, "end": 9718 }
class ____(APITestCase): def setUp(self) -> None: super().setUp() self.org = self.create_organization(owner=self.user, name="baz") self.url = reverse("sentry-api-0-organization-repositories", args=[self.org.slug]) self.login_as(user=self.user) def test_simple(self) -> None: repo = Repository.objects.create(name="example", organization_id=self.org.id) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert len(response.data) == 1 assert response.data[0]["id"] == str(repo.id) assert response.data[0]["externalSlug"] is None def test_get_integration_repository(self) -> None: repo = Repository.objects.create( name="getsentry/example", organization_id=self.org.id, external_id=12345, provider="dummy", config={"name": "getsentry/example"}, ) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert len(response.data) == 1 first_row = response.data[0] assert first_row["id"] == str(repo.id) assert first_row["provider"] == {"id": "dummy", "name": "Example"} assert first_row["externalSlug"] == str(repo.external_id) def test_get_active_repos(self) -> None: repo1 = Repository.objects.create( name="getsentry/example", organization_id=self.org.id, external_id=12345, provider="dummy", config={"name": "getsentry/example"}, ) repo2 = Repository.objects.create( name="getsentry/sentry", organization_id=self.org.id, external_id=54321, provider="dummy", config={"name": "getsentry/sentry"}, ) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert len(response.data) == 2 first_row = response.data[0] assert first_row["id"] == str(repo1.id) assert first_row["provider"] == {"id": "dummy", "name": "Example"} assert first_row["externalSlug"] == str(repo1.external_id) second_row = response.data[1] assert second_row["id"] == str(repo2.id) assert second_row["provider"] == {"id": "dummy", "name": "Example"} assert second_row["externalSlug"] == str(repo2.external_id) def test_get_exclude_hidden_repo(self) -> None: repo = Repository.objects.create( name="getsentry/example", organization_id=self.org.id, external_id=12345, provider="dummy", config={"name": "getsentry/example"}, ) Repository.objects.create( name="getsentry/sentry", organization_id=self.org.id, external_id=54321, provider="dummy", config={"name": "getsentry/sentry"}, status=ObjectStatus.HIDDEN, ) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert len(response.data) == 1 first_row = response.data[0] assert first_row["id"] == str(repo.id) assert first_row["provider"] == {"id": "dummy", "name": "Example"} assert first_row["externalSlug"] == str(repo.external_id) def test_get_all_repos(self) -> None: repo1 = Repository.objects.create( name="getsentry/example", organization_id=self.org.id, external_id=12345, provider="dummy", config={"name": "getsentry/example"}, ) repo2 = Repository.objects.create( name="getsentry/sentry", organization_id=self.org.id, external_id=54321, provider="dummy", config={"name": "getsentry/sentry"}, status=ObjectStatus.HIDDEN, ) self.url = self.url + "?status=" response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert len(response.data) == 2 first_row = response.data[0] assert first_row["id"] == str(repo1.id) assert first_row["provider"] == {"id": "dummy", "name": "Example"} assert first_row["externalSlug"] == str(repo1.external_id) second_row = response.data[1] assert second_row["id"] == str(repo2.id) assert second_row["provider"] == {"id": "dummy", "name": "Example"} assert second_row["externalSlug"] == str(repo2.external_id) def test_status_unmigratable(self) -> None: self.url = self.url + "?status=unmigratable" self.create_integration( organization=self.org, provider="github", external_id="github:1", ) unmigratable_repo = Repository.objects.create( name="NotConnected/foo", organization_id=self.org.id ) with patch( "sentry.integrations.github.integration.GitHubIntegration.get_unmigratable_repositories" ) as f: f.return_value = [unmigratable_repo] response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data[0]["name"] == unmigratable_repo.name def test_status_unmigratable_missing_org_integration(self) -> None: self.url = self.url + "?status=unmigratable" self.create_integration( organization=self.create_organization(), provider="github", external_id="github:1", ) unmigratable_repo = Repository.objects.create( name="NotConnected/foo", organization_id=self.org.id ) with patch( "sentry.integrations.github.integration.GitHubIntegration.get_unmigratable_repositories" ) as f: f.return_value = [unmigratable_repo] response = self.client.get(self.url, format="json") # Doesn't return anything when the OrganizatioIntegration doesn't # exist (the Integration has been disabled) assert response.status_code == 200, response.content assert len(response.data) == 0 def test_status_unmigratable_disabled_integration(self) -> None: self.url = self.url + "?status=unmigratable" self.create_integration( organization=self.org, provider="github", external_id="github:1", status=ObjectStatus.DISABLED, ) unmigratable_repo = Repository.objects.create( name="NotConnected/foo", organization_id=self.org.id ) with patch( "sentry.integrations.github.integration.GitHubIntegration.get_unmigratable_repositories" ) as f: f.return_value = [unmigratable_repo] response = self.client.get(self.url, format="json") assert response.status_code == 200 # Shouldn't return the above "unmigratable repo" since the # Integration is disabled. assert len(response.data) == 0 # Shouldn't even make the request to get repos assert not f.called def test_status_unmigratable_disabled_org_integration(self) -> None: self.url = self.url + "?status=unmigratable" self.create_integration( organization=self.org, provider="github", external_id="github:1", oi_params={"status": ObjectStatus.DISABLED}, ) unmigratable_repo = Repository.objects.create( name="NotConnected/foo", organization_id=self.org.id ) with patch( "sentry.integrations.github.integration.GitHubIntegration.get_unmigratable_repositories" ) as f: f.return_value = [unmigratable_repo] response = self.client.get(self.url, format="json") assert response.status_code == 200 # Shouldn't return the above "unmigratable repo" since the # Integration is disabled. assert len(response.data) == 0 # Shouldn't even make the request to get repos assert not f.called def test_passing_integration_id(self) -> None: integration = self.create_integration( organization=self.org, provider="github", external_id="github:1", ) repo = Repository.objects.create( name="example", organization_id=self.org.id, integration_id=integration.id ) integration2 = self.create_integration( organization=self.org, provider="github", external_id="github:2", ) Repository.objects.create( name="example2", organization_id=self.org.id, integration_id=integration2.id ) response = self.client.get(f"{self.url}?integration_id={integration.id}", format="json") assert response.status_code == 200, response.content assert len(response.data) == 1 assert response.data[0]["id"] == str(repo.id) assert response.data[0]["externalSlug"] is None
OrganizationRepositoriesListTest
python
doocs__leetcode
solution/0900-0999/0935.Knight Dialer/Solution.py
{ "start": 0, "end": 483 }
class ____: def knightDialer(self, n: int) -> int: f = [1] * 10 for _ in range(n - 1): g = [0] * 10 g[0] = f[4] + f[6] g[1] = f[6] + f[8] g[2] = f[7] + f[9] g[3] = f[4] + f[8] g[4] = f[0] + f[3] + f[9] g[6] = f[0] + f[1] + f[7] g[7] = f[2] + f[6] g[8] = f[1] + f[3] g[9] = f[2] + f[4] f = g return sum(f) % (10**9 + 7)
Solution
python
walkccc__LeetCode
solutions/3082. Find the Sum of the Power of All Subsequences/3082-2.py
{ "start": 0, "end": 795 }
class ____: def sumOfPower(self, nums: list[int], k: int) -> int: MOD = 1_000_000_007 n = len(nums) # dp[i][j] := the number of subsequences in nums[0..i) that sums to k dp = [[0] * (k + 1) for _ in range(n + 1)] dp[0][0] = 1 for i in range(1, n + 1): num = nums[i - 1] for j in range(k + 1): if j < num: # 1. Exclude nums[i] in the subsequence. # 2. Include nums[i] in the subsequence and skip it. dp[i][j] = (dp[i - 1][j] * 2) % MOD else: # 1. Exclude nums[i] in the subsequence. # 2. Include nums[i] in the subsequence and skip it. # 3. Include nums[i] in the subsequence and pick it. dp[i][j] = (dp[i - 1][j] * 2 + dp[i - 1][j - num]) % MOD return dp[n][k]
Solution
python
streamlit__streamlit
lib/streamlit/runtime/caching/storage/local_disk_cache_storage.py
{ "start": 4531, "end": 8932 }
class ____(CacheStorage): """Cache storage that persists data to disk This is the default cache persistence layer for `@st.cache_data`. """ def __init__(self, context: CacheStorageContext) -> None: self.function_key = context.function_key self.persist = context.persist self._ttl_seconds = context.ttl_seconds self._max_entries = context.max_entries @property def ttl_seconds(self) -> float: return self._ttl_seconds if self._ttl_seconds is not None else math.inf @property def max_entries(self) -> float: return float(self._max_entries) if self._max_entries is not None else math.inf def get(self, key: str) -> bytes: """ Returns the stored value for the key if persisted, raise CacheStorageKeyNotFoundError if not found, or not configured with persist="disk". """ if self.persist == "disk": path = self._get_cache_file_path(key) try: with streamlit_read(path, binary=True) as file: value = file.read() _LOGGER.debug("Disk cache HIT: %s", key) return bytes(value) except FileNotFoundError: raise CacheStorageKeyNotFoundError("Key not found in disk cache") except Exception as ex: _LOGGER.exception("Error reading from cache") raise CacheStorageError("Unable to read from cache") from ex else: raise CacheStorageKeyNotFoundError( f"Local disk cache storage is disabled (persist={self.persist})" ) def set(self, key: str, value: bytes) -> None: """Sets the value for a given key.""" if self.persist == "disk": path = self._get_cache_file_path(key) try: with streamlit_write(path, binary=True) as output: output.write(value) except errors.Error as ex: _LOGGER.debug("Unable to write to cache", exc_info=ex) # Clean up file so we don't leave zero byte files. try: os.remove(path) except (FileNotFoundError, OSError): # If we can't remove the file, it's not a big deal. pass raise CacheStorageError("Unable to write to cache") from ex def delete(self, key: str) -> None: """Delete a cache file from disk. If the file does not exist on disk, return silently. If another exception occurs, log it. Does not throw. """ if self.persist == "disk": path = self._get_cache_file_path(key) try: os.remove(path) except FileNotFoundError: # The file is already removed. pass except Exception as ex: _LOGGER.exception( "Unable to remove a file from the disk cache", exc_info=ex ) def clear(self) -> None: """Delete all keys for the current storage.""" cache_dir = get_cache_folder_path() if os.path.isdir(cache_dir): # We try to remove all files in the cache directory that start with # the function key, whether `clear` called for `self.persist` # storage or not, to avoid leaving orphaned files in the cache directory. for file_name in os.listdir(cache_dir): if self._is_cache_file(file_name): os.remove(os.path.join(cache_dir, file_name)) def close(self) -> None: """Dummy implementation of close, we don't need to actually "close" anything.""" def _get_cache_file_path(self, value_key: str) -> str: """Return the path of the disk cache file for the given value.""" cache_dir = get_cache_folder_path() return os.path.join( cache_dir, f"{self.function_key}-{value_key}.{_CACHED_FILE_EXTENSION}" ) def _is_cache_file(self, fname: str) -> bool: """Return true if the given file name is a cache file for this storage.""" return fname.startswith(f"{self.function_key}-") and fname.endswith( f".{_CACHED_FILE_EXTENSION}" ) def get_cache_folder_path() -> str: return get_streamlit_file_path(_CACHE_DIR_NAME)
LocalDiskCacheStorage
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 29959, "end": 30125 }
class ____(ExprNode): __slots__ = ("keys", "values") @property def is_literal_value(self): return all(v.is_literal_value for v in self.values)
Dict
python
pytorch__pytorch
test/distributed/checkpoint/test_file_system_checkpoint_cpu.py
{ "start": 9241, "end": 19937 }
class ____(ShardedTensorTestBase): @property def world_size(self) -> int: return 2 def get_file_path(self) -> str: paths = [tempfile.mkdtemp()] if dist.get_rank() == 0 else [None] dist.broadcast_object_list(paths) return paths[0] def load_tensor(self, tensor: ShardedTensor) -> torch.Tensor: res = torch.zeros(tensor.shape, device="cpu") if dist.get_rank() == 0 else None tensor.gather(out=res) return res @with_comms(init_rpc=False, backend="gloo") @parametrize("thread_count", _THREAD_COUNTS) def test_load_with_different_shard_plan(self, thread_count) -> None: path = self.get_file_path() # We hardcode the assumption of how many shards are around self.assertEqual(self.world_size, dist.get_world_size()) specs = [ # pyre-fixme [28]: Unexpected keyword argument `dim` to call `dist._sharding_spec.api.ChunkShardingSpec.__init__`. ChunkShardingSpec( dim=0, placements=[ "rank:0", "rank:1", ], ), # pyre-fixme [28]: Unexpected keyword argument `dim` to call `dist._sharding_spec.api.ChunkShardingSpec.__init__`. ChunkShardingSpec( dim=0, placements=[ "rank:0", "rank:1", "rank:1", "rank:0", ], ), # This requires the tensors to be [10, 20] EnumerableShardingSpec( shards=[ ShardMetadata( shard_offsets=[0, 0], shard_sizes=[2, 20], placement="rank:0", ), ShardMetadata( shard_offsets=[2, 0], shard_sizes=[1, 20], placement="rank:1", ), ShardMetadata( shard_offsets=[3, 0], shard_sizes=[3, 20], placement="rank:0", ), ShardMetadata( shard_offsets=[6, 0], shard_sizes=[3, 20], placement="rank:1", ), ShardMetadata( shard_offsets=[9, 0], shard_sizes=[1, 20], placement="rank:0", ), ] ), # This requires the tensors to be [10, 20] EnumerableShardingSpec( shards=[ ShardMetadata( shard_offsets=[0, 0], shard_sizes=[8, 20], placement="rank:1", ), ShardMetadata( shard_offsets=[8, 0], shard_sizes=[2, 20], placement="rank:0", ), ] ), ] for s0 in specs: for s1 in specs: if s0 == s1: continue dist.barrier() model_to_save = MyShardedModel3(s0) model_to_save._register_state_dict_hook(state_dict_hook) state_dict_to_save = model_to_save.state_dict() fs_writer = FileSystemWriter(path=path, thread_count=thread_count) save_state_dict(state_dict=state_dict_to_save, storage_writer=fs_writer) dist.barrier() model_to_load = MyShardedModel3(s1) model_to_load._register_state_dict_hook(state_dict_hook) state_dict_to_load_to = model_to_load.state_dict() dist.barrier() fs_reader = FileSystemReader(path=path) load_state_dict( state_dict=state_dict_to_load_to, storage_reader=fs_reader ) dist.barrier() store_tensor = self.load_tensor(model_to_save.sharded_tensor) dist.barrier() load_tensor = self.load_tensor(model_to_load.sharded_tensor) if dist.get_rank() == 0: self.assertTrue( torch.allclose(store_tensor, load_tensor), msg=f"{s0} vs {s1}", ) @with_comms(init_rpc=False, backend="gloo") @parametrize("thread_count", _THREAD_COUNTS) def test_load_rowwise_to_colwise(self, thread_count) -> None: path = self.get_file_path() self.assertEqual(self.world_size, dist.get_world_size()) # pyre-fixme [28]: Unexpected keyword argument `dim` to call `dist._sharding_spec.api.ChunkShardingSpec.__init__`. src_spec = ChunkShardingSpec( dim=0, placements=[ "rank:0", "rank:1", ], ) # pyre-fixme [28]: Unexpected keyword argument `dim` to call `dist._sharding_spec.api.ChunkShardingSpec.__init__`. dst_spec = ChunkShardingSpec( dim=1, placements=[ "rank:0", "rank:1", ], ) model_to_save = MyShardedModel3(src_spec).cuda(dist.get_rank()) model_to_save._register_state_dict_hook(state_dict_hook) state_dict_to_save = model_to_save.state_dict() fs_writer = FileSystemWriter(path=path, thread_count=thread_count) save_state_dict(state_dict=state_dict_to_save, storage_writer=fs_writer) model_to_load = MyShardedModel3(dst_spec).cuda(dist.get_rank()) model_to_load._register_state_dict_hook(state_dict_hook) state_dict_to_load_to = model_to_load.state_dict() fs_reader = FileSystemReader(path=path) load_state_dict(state_dict=state_dict_to_load_to, storage_reader=fs_reader) # We can't use torch.allclose since each ST has a different sharding spec store_tensor = self.load_tensor(model_to_save.sharded_tensor) load_tensor = self.load_tensor(model_to_load.sharded_tensor) if dist.get_rank() == 0: self.assertTrue(torch.allclose(store_tensor, load_tensor)) @with_comms(init_rpc=False, backend="gloo") @parametrize("thread_count", _THREAD_COUNTS) def test_save_load_bytes(self, thread_count) -> None: path = self.get_file_path() state_dict_to_save = {"bytes0": [1], "bytes1": "string"} fs_writer = FileSystemWriter(path=path, thread_count=thread_count) save_state_dict(state_dict=state_dict_to_save, storage_writer=fs_writer) state_dict_to_load = {"bytes0": [2], "bytes1": "other"} fs_reader = FileSystemReader(path=path) load_state_dict(state_dict=state_dict_to_load, storage_reader=fs_reader) self.assertEqual([1], state_dict_to_load["bytes0"]) self.assertEqual("string", state_dict_to_load["bytes1"]) @with_comms(init_rpc=False, backend="gloo") @parametrize("thread_count", _THREAD_COUNTS) def test_switch_between_sharded_tensor_to_tensor(self, thread_count) -> None: path = self.get_file_path() tensor_size = 32 specs = [ ChunkShardingSpec( dim=0, placements=[ "rank:0", "rank:1", ], ), ChunkShardingSpec( dim=0, placements=[ "rank:0", "rank:1", "rank:1", "rank:0", ], ), EnumerableShardingSpec( shards=[ ShardMetadata( shard_offsets=[0], shard_sizes=[8], placement="rank:1", ), ShardMetadata( shard_offsets=[8], shard_sizes=[tensor_size - 8], placement="rank:0", ), ] ), EnumerableShardingSpec( shards=[ ShardMetadata( shard_offsets=[0], shard_sizes=[10], placement="rank:0", ), ShardMetadata( shard_offsets=[10], shard_sizes=[tensor_size - 10], placement="rank:1", ), ] ), ] for save_spec in specs: for load_spec in specs: save_dict = { "sharded": sharded_tensor.rand(save_spec, tensor_size), "replicated": torch.rand(tensor_size, device="cpu"), } dist.broadcast(save_dict["replicated"], src=0) fs_writer = FileSystemWriter(path=path, thread_count=thread_count) save_state_dict(state_dict=save_dict, storage_writer=fs_writer) # Freaky Friday the tensors load_dict = { "sharded": torch.zeros(tensor_size, device="cpu"), "replicated": sharded_tensor.zeros(load_spec, tensor_size), } fs_reader = FileSystemReader(path=path) load_state_dict(state_dict=load_dict, storage_reader=fs_reader) save_dict_sharded = self.load_tensor(save_dict["sharded"]) load_dict_replicated = self.load_tensor(load_dict["replicated"]) if dist.get_rank() == 0: self.assertTrue( torch.allclose(save_dict_sharded, load_dict["sharded"]), f"save-spec {save_spec} load-spec {load_spec}", ) self.assertTrue( torch.allclose(save_dict["replicated"], load_dict_replicated), f"save-spec {save_spec} load-spec {load_spec}", ) instantiate_parametrized_tests(TestDistributedStateDictSaveLoad) instantiate_parametrized_tests(TestDistributedStateDictSaveLoadRot13) instantiate_parametrized_tests(TestDistributedStateDictSaveLoadWithSharedTensor) instantiate_parametrized_tests(TestDistributedStateDictSaveLoadZStandard) instantiate_parametrized_tests(TestDistributedReshardOnLoad) if __name__ == "__main__": run_tests()
TestDistributedReshardOnLoad
python
dagster-io__dagster
python_modules/dagster/dagster_tests/general_tests/seven_tests/test_seven.py
{ "start": 2238, "end": 3161 }
class ____(Foo): pass def test_is_subclass(): assert is_subclass(Bar, Foo) assert not is_subclass(Foo, Bar) assert is_subclass(dg.DagsterType, dg.DagsterType) assert is_subclass(str, str) assert is_subclass(ListType, dg.DagsterType) assert not is_subclass(dg.DagsterType, ListType) assert not is_subclass(ListType, str) # type that aren't classes can be passed into is_subclass assert not inspect.isclass(2) assert not is_subclass(2, dg.DagsterType) # pyright: ignore[reportArgumentType] @pytest.mark.skipif( sys.version_info.minor < 9, reason="Generic aliases only exist on py39 or later" ) def test_is_subclass_generic_alias(): class AbsParent(ABC): ... class Child(AbsParent): ... # See comments around is_subclass for why this fails with pytest.raises(TypeError): issubclass(list[str], Child) assert not is_subclass(list[str], Child)
Bar
python
getsentry__sentry
tests/snuba/models/test_group.py
{ "start": 12828, "end": 19268 }
class ____(TestCase, SnubaTestCase, PerformanceIssueTestCase): def setUp(self) -> None: super().setUp() self.project = self.create_project() group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1" event_data_a = load_data( "transaction-n-plus-one", fingerprint=[group_fingerprint], timestamp=before_now(minutes=1), start_timestamp=before_now(minutes=1, seconds=1), event_id="a" * 32, ) event_data_a["environment"] = "staging" event_data_b = load_data( "transaction-n-plus-one", fingerprint=[group_fingerprint], timestamp=before_now(minutes=2), start_timestamp=before_now(minutes=2, seconds=1), event_id="b" * 32, ) event_data_b["environment"] = "production" event_data_b["contexts"].update( { "replay": {"replay_id": uuid.uuid4().hex}, "profile": {"profile_id": uuid.uuid4().hex}, } ) event_data_c = load_data( "transaction-n-plus-one", fingerprint=[group_fingerprint], timestamp=before_now(minutes=3), start_timestamp=before_now(minutes=3, seconds=1), event_id="c" * 32, ) event_data_c["environment"] = "staging" event_data_c["contexts"].update({"profile": {"profile_id": uuid.uuid4().hex}}) event_data_c["tags"] = {"organization.slug": "sentry"} self.event_a = self.create_performance_issue( event_data=event_data_a, fingerprint=group_fingerprint ) self.event_b = self.create_performance_issue( event_data=event_data_b, fingerprint=group_fingerprint ) self.event_c = self.create_performance_issue( event_data=event_data_c, fingerprint=group_fingerprint ) self.group: Group = Group.objects.get() assert isinstance(self.group, Group) def test_recommended_event(self) -> None: # No filter assert _get_recommended(self.group).event_id == self.event_b.event_id # Filter by environment conditions = [Condition(Column("environment"), Op.IN, ["staging"])] assert _get_recommended(self.group, conditions=conditions).event_id == self.event_c.event_id conditions = [Condition(Column("environment"), Op.IN, ["production"])] assert _get_recommended(self.group, conditions=conditions).event_id == self.event_b.event_id conditions = [Condition(Column("environment"), Op.IN, ["development"])] assert self.group.get_recommended_event(conditions=conditions) is None # Filter by query conditions = [Condition(Column("tags[organization.slug]"), Op.EQ, "sentry")] assert _get_recommended(self.group, conditions=conditions).event_id == self.event_c.event_id conditions = [Condition(Column("profile_id"), Op.IS_NULL)] assert _get_recommended(self.group, conditions=conditions).event_id == self.event_a.event_id # Filter by date range assert ( _get_recommended( self.group, start=before_now(seconds=120), end=before_now(seconds=30) ).event_id == self.event_b.event_id ) assert ( _get_recommended( self.group, start=before_now(hours=1), end=before_now(seconds=90) ).event_id == self.event_b.event_id ) def test_latest_event(self) -> None: # No filter assert _get_latest(self.group).event_id == self.event_a.event_id # Filter by environment conditions = [Condition(Column("environment"), Op.IN, ["staging"])] assert _get_latest(self.group, conditions=conditions).event_id == self.event_a.event_id conditions = [Condition(Column("environment"), Op.IN, ["production"])] assert _get_latest(self.group, conditions=conditions).event_id == self.event_b.event_id conditions = [Condition(Column("environment"), Op.IN, ["development"])] assert self.group.get_latest_event(conditions=conditions) is None # Filter by query conditions = [Condition(Column("tags[organization.slug]"), Op.EQ, "sentry")] assert _get_latest(self.group, conditions=conditions).event_id == self.event_c.event_id conditions = [Condition(Column("profile_id"), Op.IS_NULL)] assert _get_latest(self.group, conditions=conditions).event_id == self.event_a.event_id # Filter by date range assert ( _get_latest( self.group, start=before_now(seconds=120), end=before_now(seconds=30) ).event_id == self.event_a.event_id ) assert ( _get_latest(self.group, start=before_now(hours=1), end=before_now(seconds=90)).event_id == self.event_b.event_id ) def test_oldest_event(self) -> None: # No filter assert _get_oldest(self.group).event_id == self.event_c.event_id # Filter by environment conditions = [Condition(Column("environment"), Op.IN, ["staging"])] assert _get_oldest(self.group, conditions=conditions).event_id == self.event_c.event_id conditions = [Condition(Column("environment"), Op.IN, ["production"])] assert _get_oldest(self.group, conditions=conditions).event_id == self.event_b.event_id conditions = [Condition(Column("environment"), Op.IN, ["development"])] assert self.group.get_oldest_event(conditions=conditions) is None # Filter by query conditions = [Condition(Column("tags[organization.slug]"), Op.EQ, "sentry")] assert _get_oldest(self.group, conditions=conditions).event_id == self.event_c.event_id conditions = [Condition(Column("profile_id"), Op.IS_NULL)] assert _get_oldest(self.group, conditions=conditions).event_id == self.event_a.event_id # Filter by date range assert ( _get_oldest( self.group, start=before_now(seconds=150), end=before_now(seconds=30) ).event_id == self.event_b.event_id ) assert ( _get_oldest(self.group, start=before_now(hours=1), end=before_now(seconds=90)).event_id == self.event_c.event_id ) @freeze_time()
GroupTestSnubaPerformanceIssue
python
realpython__materials
django-migrations/bitcoin_tracker/historical_data/migrations/0002_switch_to_decimals.py
{ "start": 92, "end": 393 }
class ____(migrations.Migration): dependencies = [("historical_data", "0001_initial")] operations = [ migrations.AlterField( model_name="pricehistory", name="volume", field=models.DecimalField(decimal_places=3, max_digits=7), ) ]
Migration
python
graphql-python__graphene
graphene/types/tests/test_objecttype.py
{ "start": 293, "end": 378 }
class ____(ObjectType): field1 = Field(MyType) field2 = Field(MyType)
Container
python
huggingface__transformers
src/transformers/models/vits/modeling_vits.py
{ "start": 31272, "end": 35676 }
class ____(nn.Module): def __init__(self, config): super().__init__() embed_dim = config.speaker_embedding_size filter_channels = config.hidden_size self.conv_pre = nn.Conv1d(filter_channels, filter_channels, 1) self.conv_proj = nn.Conv1d(filter_channels, filter_channels, 1) self.conv_dds = VitsDilatedDepthSeparableConv( config, dropout_rate=config.duration_predictor_dropout, ) if embed_dim != 0: self.cond = nn.Conv1d(embed_dim, filter_channels, 1) self.flows = nn.ModuleList() self.flows.append(VitsElementwiseAffine(config)) for _ in range(config.duration_predictor_num_flows): self.flows.append(VitsConvFlow(config)) self.post_conv_pre = nn.Conv1d(1, filter_channels, 1) self.post_conv_proj = nn.Conv1d(filter_channels, filter_channels, 1) self.post_conv_dds = VitsDilatedDepthSeparableConv( config, dropout_rate=config.duration_predictor_dropout, ) self.post_flows = nn.ModuleList() self.post_flows.append(VitsElementwiseAffine(config)) for _ in range(config.duration_predictor_num_flows): self.post_flows.append(VitsConvFlow(config)) def forward(self, inputs, padding_mask, global_conditioning=None, durations=None, reverse=False, noise_scale=1.0): inputs = torch.detach(inputs) inputs = self.conv_pre(inputs) if global_conditioning is not None: global_conditioning = torch.detach(global_conditioning) inputs = inputs + self.cond(global_conditioning) inputs = self.conv_dds(inputs, padding_mask) inputs = self.conv_proj(inputs) * padding_mask if not reverse: hidden_states = self.post_conv_pre(durations) hidden_states = self.post_conv_dds(hidden_states, padding_mask) hidden_states = self.post_conv_proj(hidden_states) * padding_mask random_posterior = ( torch.randn(durations.size(0), 2, durations.size(2)).to(device=inputs.device, dtype=inputs.dtype) * padding_mask ) log_determinant_posterior_sum = 0 latents_posterior = random_posterior for flow in self.post_flows: latents_posterior, log_determinant = flow( latents_posterior, padding_mask, global_conditioning=inputs + hidden_states ) latents_posterior = torch.flip(latents_posterior, [1]) log_determinant_posterior_sum += log_determinant first_half, second_half = torch.split(latents_posterior, [1, 1], dim=1) log_determinant_posterior_sum += torch.sum( (nn.functional.logsigmoid(first_half) + nn.functional.logsigmoid(-first_half)) * padding_mask, [1, 2] ) logq = ( torch.sum(-0.5 * (math.log(2 * math.pi) + (random_posterior**2)) * padding_mask, [1, 2]) - log_determinant_posterior_sum ) first_half = (durations - torch.sigmoid(first_half)) * padding_mask first_half = torch.log(torch.clamp_min(first_half, 1e-5)) * padding_mask log_determinant_sum = torch.sum(-first_half, [1, 2]) latents = torch.cat([first_half, second_half], dim=1) for flow in self.flows: latents, log_determinant = flow(latents, padding_mask, global_conditioning=inputs) latents = torch.flip(latents, [1]) log_determinant_sum += log_determinant nll = torch.sum(0.5 * (math.log(2 * math.pi) + (latents**2)) * padding_mask, [1, 2]) - log_determinant_sum return nll + logq else: flows = list(reversed(self.flows)) flows = flows[:-2] + [flows[-1]] # remove a useless vflow latents = ( torch.randn(inputs.size(0), 2, inputs.size(2)).to(device=inputs.device, dtype=inputs.dtype) * noise_scale ) for flow in flows: latents = torch.flip(latents, [1]) latents, _ = flow(latents, padding_mask, global_conditioning=inputs, reverse=True) log_duration, _ = torch.split(latents, [1, 1], dim=1) return log_duration
VitsStochasticDurationPredictor
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/job_base.py
{ "start": 458, "end": 1830 }
class ____(ABC): """IJob is a wrapper interface for JobDefinitions to be used as parameters to Dagster's core execution APIs. This enables these execution APIs to operate on both in memory job definitions to be executed in the current process (InMemoryJob) as well as definitions that can be reconstructed and executed in a different process (ReconstructableJob). """ @abstractmethod def get_definition(self) -> "JobDefinition": pass @abstractmethod def get_repository_definition(self) -> Optional["RepositoryDefinition"]: pass @abstractmethod def get_subset( self, *, op_selection: Optional[Iterable[str]] = None, asset_selection: Optional[AbstractSet[AssetKey]] = None, asset_check_selection: Optional[AbstractSet[AssetCheckKey]] = None, ) -> "IJob": pass @property @abstractmethod def op_selection(self) -> Optional[AbstractSet[str]]: pass @property @abstractmethod def asset_selection(self) -> Optional[AbstractSet[AssetKey]]: pass @property @abstractmethod def asset_check_selection(self) -> Optional[AbstractSet[AssetCheckKey]]: pass @property def resolved_op_selection(self) -> Optional[AbstractSet[str]]: return set(self.op_selection) if self.op_selection else None
IJob
python
numba__numba
numba/cuda/cudamath.py
{ "start": 1508, "end": 1863 }
class ____(ConcreteTemplate): key = math.atan2 cases = [ signature(types.float64, types.int64, types.int64), signature(types.float64, types.uint64, types.uint64), signature(types.float32, types.float32, types.float32), signature(types.float64, types.float64, types.float64), ] @infer_global(math.hypot)
Math_atan2
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_tm_future_annotations_sync.py
{ "start": 148092, "end": 153175 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): """try a bunch of common mappings using the new style""" __dialect__ = "default" def test_employee_joined_inh(self, decl_base: Type[DeclarativeBase]): global str50, str30, opt_str50 str50 = Annotated[str, 50] str30 = Annotated[str, 30] opt_str50 = Optional[str50] decl_base.registry.update_type_annotation_map( {str50: String(50), str30: String(30)} ) class Company(decl_base): __tablename__ = "company" company_id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str50] employees: Mapped[Set["Person"]] = relationship() # noqa: F821 class Person(decl_base): __tablename__ = "person" person_id: Mapped[int] = mapped_column(primary_key=True) company_id: Mapped[int] = mapped_column( ForeignKey("company.company_id") ) name: Mapped[str50] type: Mapped[str30] = mapped_column() __mapper_args__ = {"polymorphic_on": type} class Engineer(Person): __tablename__ = "engineer" person_id: Mapped[int] = mapped_column( ForeignKey("person.person_id"), primary_key=True ) __mapper_args__ = {"polymorphic_identity": "engineer"} status: Mapped[str] = mapped_column(String(30)) engineer_name: Mapped[opt_str50] primary_language: Mapped[opt_str50] class Manager(Person): __tablename__ = "manager" person_id: Mapped[int] = mapped_column( ForeignKey("person.person_id"), primary_key=True ) status: Mapped[str] = mapped_column(String(30)) manager_name: Mapped[str50] __mapper_args__ = {"polymorphic_identity": "manager"} is_(Person.__mapper__.polymorphic_on, Person.__table__.c.type) # the SELECT statements here confirm the columns present and their # ordering self.assert_compile( select(Person), "SELECT person.person_id, person.company_id, person.name, " "person.type FROM person", ) self.assert_compile( select(Manager), "SELECT manager.person_id, person.person_id AS person_id_1, " "person.company_id, person.name, person.type, manager.status, " "manager.manager_name FROM person " "JOIN manager ON person.person_id = manager.person_id", ) self.assert_compile( select(Company).join(Company.employees.of_type(Engineer)), "SELECT company.company_id, company.name FROM company JOIN " "(person JOIN engineer ON person.person_id = engineer.person_id) " "ON company.company_id = person.company_id", ) @testing.variation("anno_type", ["plain", "typemap", "annotated"]) @testing.variation("inh_type", ["single", "joined"]) def test_mixin_interp_on_inh(self, decl_base, inh_type, anno_type): global anno_col if anno_type.typemap: anno_col = Annotated[str, 30] decl_base.registry.update_type_annotation_map({anno_col: String}) class Mixin: foo: Mapped[anno_col] elif anno_type.annotated: anno_col = Annotated[str, mapped_column(String)] class Mixin: foo: Mapped[anno_col] else: class Mixin: foo: Mapped[str] class Employee(Mixin, decl_base): __tablename__ = "employee" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] type: Mapped[str] __mapper_args__ = { "polymorphic_on": "type", "polymorphic_identity": "employee", } class Manager(Employee): if inh_type.joined: __tablename__ = "manager" id: Mapped[int] = mapped_column( # noqa: A001 ForeignKey("employee.id"), primary_key=True ) manager_data: Mapped[str] = mapped_column(nullable=True) __mapper_args__ = { "polymorphic_identity": "manager", } if inh_type.single: self.assert_compile( select(Manager), "SELECT employee.id, employee.name, employee.type, " "employee.foo, employee.manager_data FROM employee " "WHERE employee.type IN (__[POSTCOMPILE_type_1])", ) elif inh_type.joined: self.assert_compile( select(Manager), "SELECT manager.id, employee.id AS id_1, employee.name, " "employee.type, employee.foo, manager.manager_data " "FROM employee JOIN manager ON employee.id = manager.id", ) else: inh_type.fail()
AllYourFavoriteHitsTest
python
bottlepy__bottle
bottle.py
{ "start": 142180, "end": 142330 }
class ____(ServerAdapter): """ Extend ServerAdapter for adding custom event loop """ def get_event_loop(self): pass
AsyncioServerAdapter
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/atrous_conv2d_test.py
{ "start": 9430, "end": 10577 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testAtrousDepthwiseConv2DForward(self): strides = [1, 1, 1, 1] 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) for padding in ["SAME", "VALID"]: y1 = nn_impl.depthwise_conv2d( x, f, strides, padding, rate=[rate, rate]) y2 = nn_impl.depthwise_conv2d(x, f_up, strides, padding) self.assertAllClose(y1, y2, rtol=1e-3, atol=1e-3) if __name__ == "__main__": test.main()
AtrousDepthwiseConv2DTest
python
walkccc__LeetCode
solutions/261. Graph Valid Tree/261-2.py
{ "start": 0, "end": 557 }
class ____: def __init__(self, n: int): self.count = n self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 self.count -= 1 def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u]
UnionFind
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format12.py
{ "start": 315, "end": 1820 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format12.xlsx") def test_create_file(self): """Test the creation of an XlsxWriter file with chart formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "line"}) chart.axis_ids = [54794880, 56296576] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$B$1:$B$5", "trendline": { "type": "moving_average", "period": 2, "line": { "color": "red", "width": 1, "dash_type": "long_dash", }, }, } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
test/sql/test_compare.py
{ "start": 64048, "end": 69139 }
class ____(CoreFixtures, fixtures.TestBase): @classmethod def setup_test_class(cls): # TODO: we need to get dialects here somehow, perhaps in test_suite? [ importlib.import_module("sqlalchemy.dialects.%s" % d) for d in dialects.__all__ if not d.startswith("_") ] def test_all_present(self): """test for elements that are in SQLAlchemy Core, that they are also included in the fixtures above. """ need = set( cls for cls in all_hascachekey_subclasses( ignore_subclasses=[Annotated, NoInit, SingletonConstant] ) if "orm" not in cls.__module__ and "compiler" not in cls.__module__ and "dialects" not in cls.__module__ and issubclass( cls, ( ColumnElement, Selectable, LambdaElement, DQLDMLClauseElement, ), ) ) for fixture in self.fixtures + self.dont_compare_values_fixtures: case_a = fixture() for elem in case_a: for mro in type(elem).__mro__: need.discard(mro) is_false(bool(need), "%d Remaining classes: %r" % (len(need), need)) def test_compare_labels(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() for a, b in itertools.combinations_with_replacement( range(len(case_a)), 2 ): if a == b: is_true( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), f"{case_a[a]!r} != {case_b[b]!r} (index {a} {b})", ) else: is_false( case_a[a].compare( case_b[b], compare_annotations=True, compare_values=compare_values, ), f"{case_a[a]!r} == {case_b[b]!r} (index {a} {b})", ) def test_compare_col_identity(self): stmt1 = ( select(table_a.c.a, table_b.c.b) .where(table_a.c.a == table_b.c.b) .alias() ) stmt1_c = ( select(table_a.c.a, table_b.c.b) .where(table_a.c.a == table_b.c.b) .alias() ) stmt2 = union(select(table_a), select(table_b)) equivalents = {table_a.c.a: [table_b.c.a]} is_false( stmt1.compare(stmt2, use_proxies=True, equivalents=equivalents) ) is_true( stmt1.compare(stmt1_c, use_proxies=True, equivalents=equivalents) ) is_true( (table_a.c.a == table_b.c.b).compare( stmt1.c.a == stmt1.c.b, use_proxies=True, equivalents=equivalents, ) ) def test_copy_internals(self): for fixtures_, compare_values in [ (self.fixtures, True), (self.dont_compare_values_fixtures, False), ]: for fixture in fixtures_: case_a = fixture() case_b = fixture() for idx in range(len(case_a)): assert case_a[idx].compare( case_b[idx], compare_values=compare_values ) clone = visitors.replacement_traverse( case_a[idx], {}, lambda elem: None ) assert clone.compare( case_b[idx], compare_values=compare_values ) assert case_a[idx].compare( case_b[idx], compare_values=compare_values ) # copy internals of Select is very different than other # elements and additionally this is extremely well tested # in test_selectable and test_external_traversal, so # skip these if isinstance(case_a[idx], Select): continue for elema, elemb in zip( visitors.iterate(case_a[idx], {}), visitors.iterate(clone, {}), ): if isinstance(elema, ClauseElement) and not isinstance( elema, Immutable ): assert elema is not elemb
CompareAndCopyTest
python
coleifer__peewee
peewee.py
{ "start": 161435, "end": 161613 }
class ____(Field): field_type = 'FLOAT' def adapt(self, value): try: return float(value) except ValueError: return value
FloatField
python
pytorch__pytorch
test/torch_np/numpy_tests/fft/test_helper.py
{ "start": 5468, "end": 5872 }
class ____(TestCase): def test_definition(self): x = [0, 1, 2, 3, 4, -4, -3, -2, -1] assert_array_almost_equal(9 * fft.fftfreq(9), x) assert_array_almost_equal(9 * pi * fft.fftfreq(9, pi), x) x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1] assert_array_almost_equal(10 * fft.fftfreq(10), x) assert_array_almost_equal(10 * pi * fft.fftfreq(10, pi), x)
TestFFTFreq
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 88744, "end": 93520 }
class ____(Operation): def __init__(self, axis=-1, epsilon=None, rms_scaling=False, *, name=None): super().__init__(name=name) self.axis = axis self.epsilon = epsilon self.rms_scaling = rms_scaling def compute_output_spec(self, x, gamma, beta): return KerasTensor(shape=x.shape, dtype=x.dtype) def call(self, x, gamma=None, beta=None): return _layer_normalization( x, gamma=gamma, beta=beta, axis=self.axis, epsilon=self.epsilon, rms_scaling=self.rms_scaling, ) @keras_export( [ "keras.ops.layer_normalization", "keras.ops.nn.layer_normalization", ] ) def layer_normalization( x, gamma=None, beta=None, axis=-1, epsilon=None, **kwargs ): """Layer normalization layer (Ba et al., 2016). Normalize the activations of the previous layer for each given example in a batch independently, rather than across a batch like Batch Normalization. i.e. applies a transformation that maintains the mean activation within each example close to 0 and the activation standard deviation close to 1. Args: x: Input tensor. gamma: Optional scaling factor for the normalization. beta: Optional add offset for the normalized tensor. axis: The axis or axes along which to perform normalization. Default to `-1`. epsilon: A lower bound value for the norm. Defaults to `backend.epsilon()`. Returns: The normalized array. Example: >>> x = keras.ops.arange(5, dtype="float32") >>> keras.ops.layer_normalization(x) array([-1.4142135, -0.70710677, 0.0, 0.7071067, 1.4142135]) """ rms_scaling = kwargs.pop("rms_scaling", False) if rms_scaling: warnings.warn( "You passed `rms_scaling=True`, which is deprecated. This argument " "incorrectly scales the input by the variance, not the root mean " "square. To correctly use RMS Normalization, please use " "`keras.ops.rms_normalization` / `keras.ops.nn.rms_normalization` " "instead." ) if any_symbolic_tensors((x, gamma, beta)): return LayerNorm( axis=axis, epsilon=epsilon, rms_scaling=rms_scaling ).symbolic_call(x, gamma, beta) return _layer_normalization( x, gamma=gamma, beta=beta, axis=axis, epsilon=epsilon, rms_scaling=rms_scaling, ) def _layer_normalization( x, gamma=None, beta=None, axis=-1, epsilon=None, rms_scaling=False ): if epsilon is None: epsilon = backend.epsilon() original_dtype = backend.standardize_dtype(x.dtype) # Computes in at least float32 precision for stability in half precision # training. compute_dtype = backend.result_type(x.dtype, "float32") x = backend.convert_to_tensor(x, dtype=compute_dtype) if gamma is not None: gamma = backend.convert_to_tensor(gamma, x.dtype) if beta is not None: beta = backend.convert_to_tensor(beta, x.dtype) # Compute the axes along which to reduce the mean / variance input_shape = x.shape ndims = len(input_shape) # Broadcasting only necessary for norm when the axis is not just # the last dimension broadcast_shape = [1] * ndims if isinstance(axis, int): axis = [axis] for dim in axis: broadcast_shape[dim] = input_shape[dim] def _broadcast(v): if v is not None and len(v.shape) != ndims and axis != [ndims - 1]: return backend.numpy.reshape(v, broadcast_shape) return v if rms_scaling: variance = backend.numpy.var(x, axis=axis, keepdims=True) inv = backend.math.rsqrt(variance + epsilon) outputs = outputs = x * inv if gamma is not None: outputs = outputs * backend.cast(_broadcast(gamma), x.dtype) elif backend.config.backend() == "torch" and is_continuous_axis(axis): # when using torch backend,use kernel to improve performance import torch.nn.functional as F normalized_shape = tuple([input_shape[dim] for dim in axis]) outputs = F.layer_norm(x, normalized_shape, gamma, beta, epsilon) else: # Calculate the mean & variance along self.axis (layer activations). mean, variance = moments(x, axes=axis, keepdims=True) gamma, beta = _broadcast(gamma), _broadcast(beta) inv = backend.math.rsqrt(variance + epsilon) if gamma is not None: inv = inv * gamma res = -mean * inv if beta is not None: res = res + beta outputs = x * inv + res return backend.cast(outputs, original_dtype)
LayerNorm
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 957297, "end": 957753 }
class ____(sgqlc.types.Type): """Autogenerated return type of RevokeMigratorRole""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "success") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" success = sgqlc.types.Field(Boolean, graphql_name="success") """Did the operation succeed?"""
RevokeMigratorRolePayload
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1255773, "end": 1262769 }
class ____(RepeatSpec): """ NonLayerRepeatSpec schema wrapper. Base interface for a repeat specification. Parameters ---------- repeat : dict, Sequence[str], :class:`RepeatMapping` Definition for fields to be repeated. One of: 1) An array of fields to be repeated. If ``"repeat"`` is an array, the field can be referred to as ``{"repeat": "repeat"}``. The repeated views are laid out in a wrapped row. You can set the number of columns to control the wrapping. 2) An object that maps ``"row"`` and/or ``"column"`` to the listed fields to be repeated along the particular orientations. The objects ``{"repeat": "row"}`` and ``{"repeat": "column"}`` can be used to refer to the repeated field respectively. spec : dict, :class:`FacetSpec`, :class:`LayerSpec`, :class:`RepeatSpec`, :class:`FacetedUnitSpec`, :class:`LayerRepeatSpec`, :class:`NonNormalizedSpec`, :class:`NonLayerRepeatSpec`, :class:`ConcatSpecGenericSpec`, :class:`HConcatSpecGenericSpec`, :class:`VConcatSpecGenericSpec` A specification of the view that gets repeated. align : dict, :class:`LayoutAlign`, :class:`RowColLayoutAlign`, Literal['all', 'each', 'none'] The alignment to apply to grid rows and columns. The supported string values are ``"all"``, ``"each"``, and ``"none"``. * For ``"none"``, a flow layout will be used, in which adjacent subviews are simply placed one after the other. * For ``"each"``, subviews will be aligned into a clean grid structure, but each row or column may be of variable size. * For ``"all"``, subviews will be aligned and each row or column will be sized identically based on the maximum observed size. String values for this property will be applied to both grid rows and columns. Alternatively, an object value of the form ``{"row": string, "column": string}`` can be used to supply different alignments for rows and columns. **Default value:** ``"all"``. bounds : Literal['full', 'flush'] The bounds calculation method to use for determining the extent of a sub-plot. One of ``full`` (the default) or ``flush``. * If set to ``full``, the entire calculated bounds (including axes, title, and legend) will be used. * If set to ``flush``, only the specified width and height values for the sub-view will be used. The ``flush`` setting can be useful when attempting to place sub-plots without axes or legends into a uniform grid structure. **Default value:** ``"full"`` center : bool, dict, :class:`RowColboolean` Boolean flag indicating if subviews should be centered relative to their respective rows or columns. An object value of the form ``{"row": boolean, "column": boolean}`` can be used to supply different centering values for rows and columns. **Default value:** ``false`` columns : float The number of columns to include in the view composition layout. **Default value**: ``undefined`` -- An infinite number of columns (a single row) will be assumed. This is equivalent to ``hconcat`` (for ``concat``) and to using the ``column`` channel (for ``facet`` and ``repeat``). **Note**: 1) This property is only for: * the general (wrappable) ``concat`` operator (not ``hconcat``/``vconcat``) * the ``facet`` and ``repeat`` operator with one field/repetition definition (without row/column nesting) 2) Setting the ``columns`` to ``1`` is equivalent to ``vconcat`` (for ``concat``) and to using the ``row`` channel (for ``facet`` and ``repeat``). data : dict, :class:`Data`, :class:`UrlData`, :class:`Generator`, :class:`NamedData`, :class:`DataSource`, :class:`InlineData`, :class:`SphereGenerator`, :class:`SequenceGenerator`, :class:`GraticuleGenerator`, None An object describing the data source. Set to ``null`` to ignore the parent's data source. If no data is set, it is derived from the parent. description : str Description of this mark for commenting purpose. name : str Name of the visualization for later reference. resolve : dict, :class:`Resolve` Scale, axis, and legend resolutions for view composition specifications. spacing : dict, float, :class:`RowColnumber` The spacing in pixels between sub-views of the composition operator. An object of the form ``{"row": number, "column": number}`` can be used to set different spacing values for rows and columns. **Default value**: Depends on ``"spacing"`` property of `the view composition configuration <https://vega.github.io/vega-lite/docs/config.html#view-config>`__ (``20`` by default) title : str, dict, :class:`Text`, Sequence[str], :class:`TitleParams` Title for the plot. transform : Sequence[dict, :class:`Transform`, :class:`BinTransform`, :class:`FoldTransform`, :class:`LoessTransform`, :class:`PivotTransform`, :class:`StackTransform`, :class:`ExtentTransform`, :class:`FilterTransform`, :class:`ImputeTransform`, :class:`LookupTransform`, :class:`SampleTransform`, :class:`WindowTransform`, :class:`DensityTransform`, :class:`FlattenTransform`, :class:`QuantileTransform`, :class:`TimeUnitTransform`, :class:`AggregateTransform`, :class:`CalculateTransform`, :class:`RegressionTransform`, :class:`JoinAggregateTransform`] An array of data transformations such as filter and new field calculation. """ _schema = {"$ref": "#/definitions/NonLayerRepeatSpec"} def __init__( self, repeat: Optional[SchemaBase | Sequence[str] | Map] = Undefined, spec: Optional[SchemaBase | Map] = Undefined, align: Optional[SchemaBase | Map | LayoutAlign_T] = Undefined, bounds: Optional[Literal["full", "flush"]] = Undefined, center: Optional[bool | SchemaBase | Map] = Undefined, columns: Optional[float] = Undefined, data: Optional[SchemaBase | ChartDataType | Map | None] = Undefined, description: Optional[str] = Undefined, name: Optional[str] = Undefined, resolve: Optional[SchemaBase | Map] = Undefined, spacing: Optional[float | SchemaBase | Map] = Undefined, title: Optional[str | SchemaBase | Sequence[str] | Map] = Undefined, transform: Optional[Sequence[SchemaBase | Map]] = Undefined, **kwds, ): super().__init__( repeat=repeat, spec=spec, align=align, bounds=bounds, center=center, columns=columns, data=data, description=description, name=name, resolve=resolve, spacing=spacing, title=title, transform=transform, **kwds, )
NonLayerRepeatSpec
python
pytorch__pytorch
test/test_functional_autograd_benchmark.py
{ "start": 378, "end": 2659 }
class ____(TestCase): def _test_runner(self, model, disable_gpu=False): # Note about windows: # The temporary file is exclusively open by this process and the child process # is not allowed to open it again. As this is a simple smoke test, we choose for now # not to run this on windows and keep the code here simple. with TemporaryFileName() as out_file: cmd = [ "python3", "../benchmarks/functional_autograd_benchmark/functional_autograd_benchmark.py", ] if IS_WINDOWS: cmd[0] = "python" # Only run the warmup cmd += ["--num-iters", "0"] # Only run the vjp task (fastest one) cmd += ["--task-filter", "vjp"] # Only run the specified model cmd += ["--model-filter", model] # Output file cmd += ["--output", out_file] if disable_gpu: cmd += ["--gpu", "-1"] res = subprocess.run(cmd, check=False) self.assertTrue(res.returncode == 0) # Check that something was written to the file self.assertTrue(os.stat(out_file).st_size > 0) @unittest.skipIf( PYTORCH_COLLECT_COVERAGE, "Can deadlocks with gcov, see https://github.com/pytorch/pytorch/issues/49656", ) def test_fast_tasks(self): fast_tasks = [ "resnet18", "ppl_simple_reg", "ppl_robust_reg", "wav2letter", "transformer", "multiheadattn", ] for task in fast_tasks: self._test_runner(task) @slowTest @unittest.skipIf( IS_WINDOWS, "NamedTemporaryFile on windows does not have all the features we need.", ) def test_slow_tasks(self): slow_tasks = ["fcn_resnet", "detr"] # deepspeech is voluntarily excluded as it takes too long to run without # proper tuning of the number of threads it should use. for task in slow_tasks: # Disable GPU for slow test as the CI GPU don't have enough memory self._test_runner(task, disable_gpu=True) if __name__ == "__main__": run_tests()
TestFunctionalAutogradBenchmark
python
pydata__xarray
xarray/tests/test_tutorial.py
{ "start": 835, "end": 1517 }
class ____: def test_download_from_github(self, tmp_path) -> None: cache_dir = tmp_path / tutorial._default_cache_dir_name ds = tutorial.load_datatree("tiny", cache_dir=cache_dir) tiny = DataTree.from_dict({"/": DataArray(range(5), name="tiny").to_dataset()}) assert_identical(ds, tiny) def test_download_from_github_load_without_cache(self, tmp_path) -> None: cache_dir = tmp_path / tutorial._default_cache_dir_name ds_nocache = tutorial.load_datatree("tiny", cache=False, cache_dir=cache_dir) ds_cache = tutorial.load_datatree("tiny", cache_dir=cache_dir) assert_identical(ds_cache, ds_nocache)
TestLoadDataTree
python
google__pytype
pytype/tests/test_typing1.py
{ "start": 14545, "end": 16771 }
class ____(test_base.BaseTest): """Tests for importing typing constructs only present in some Python versions. We want pytype to behave as follows: Is the construct supported by pytype? | -> No: Log a plain [not supported-yet] error. | -> Yes: Is the construct being imported from typing_extensions or typing? | -> typing_extensions: Do not log any errors. | -> typing: Is the construct present in the runtime typing module? | -> No: Log [not-supported-yet] with a hint to use typing_extensions. | -> Yes: Do not log any errors. These tests currently use TypeVarTuple (added in 3.11) as the unsupported construct and Final (added in 3.8) as the supported construct. Replace them as needed as pytype's supported features and runtime versions change. """ def test_unsupported_extension(self): errors = self.CheckWithErrors(""" from typing_extensions import TypeVarTuple # not-supported-yet[e] """) self.assertErrorRegexes( errors, {"e": r"typing_extensions.TypeVarTuple not supported yet$"} ) def test_unsupported_construct(self): errors = self.CheckWithErrors(""" from typing import TypeVarTuple # not-supported-yet[e] """) self.assertErrorRegexes( errors, {"e": r"typing.TypeVarTuple not supported yet$"} ) def test_supported_extension(self): self.Check(""" from typing_extensions import Final """) def test_supported_construct_in_supported_version(self): self.Check(""" from typing import Final """) @test_utils.skipBeforePy( (3, 12), "This only happens with 3.12 where it puts LOAD_FAST_AND_CLEAR op", ) def test_re_not_deleted_with_load_fast_and_clear(self): self.Check(""" import re class Foo(): A = [re.compile(r) for r in (r'___', )] B = re.compile(r"dummy") """) def test_deleted_x_normally(self): errors = self.CheckWithErrors(""" x = 1 def f(): x = 2 del x print(x) # name-error[e] """) self.assertErrorRegexes( errors, {"e": r"Name 'x' is not defined"} ) if __name__ == "__main__": test_base.main()
NotSupportedYetTest
python
keras-team__keras
keras/src/quantizers/gptq_core_test.py
{ "start": 831, "end": 3186 }
class ____(layers.Layer): """A toy transformer block with a quantizable Dense layer.""" def __init__(self, **kwargs): super().__init__(**kwargs) self.dense = layers.Dense(128) def call(self, inputs): return self.dense(inputs) def _get_model_with_backbone( has_transformer_layers=True, embedding_name="embedding" ): """Creates a KerasHub-style model with a backbone.""" class Backbone(layers.Layer): def __init__(self, vocab_size, embedding_dim=128, **kwargs): super().__init__(**kwargs) # Use direct assignment setattr( self, embedding_name, layers.Embedding(vocab_size, embedding_dim), ) # Keep track of layers in a list for the call method self.transformer_layers = [] if has_transformer_layers: self.transformer_layers.append(TransformerBlock()) def call(self, inputs): x = getattr(self, embedding_name)(inputs) for layer in self.transformer_layers: x = layer(x) return x class Model(models.Model): def __init__(self, vocab_size, **kwargs): super().__init__(**kwargs) # Pass configuration directly self.backbone = Backbone(vocab_size=vocab_size) self.classifier = layers.Dense(1, activation="sigmoid") def call(self, inputs): x = self.backbone(inputs) x = layers.GlobalAveragePooling1D()(x) return self.classifier(x) model = Model(vocab_size=VOCAB_SIZE) rng = np.random.default_rng(seed=42) dummy_input = rng.normal(loc=0, scale=1, size=(2, 64)).astype(np.float32) _ = model(dummy_input) return model def build_all_tokens_strings(dataset, tokenizer, eos_id=None): pieces = [] for i, s in enumerate(dataset): toks = np.asarray(tokenizer.tokenize(s), dtype=np.int32).reshape(-1) pieces.append(toks) if eos_id is not None and i < len(dataset) - 1: pieces.append(np.array([eos_id], dtype=np.int32)) return np.concatenate(pieces, axis=0).astype(np.int32, copy=False) def sliding_windows(x, L): return np.lib.stride_tricks.sliding_window_view(x, L) @pytest.mark.requires_trainable_backend
TransformerBlock
python
jazzband__django-pipeline
pipeline/storage.py
{ "start": 3146, "end": 3602 }
class ____(NonPackagingMixin, PipelineStorage): pass if _CACHED_STATIC_FILES_STORAGE_AVAILABLE: class PipelineCachedStorage(PipelineMixin, CachedStaticFilesStorage): # Deprecated since Django 2.2 # Removed in Django 3.1 pass class NonPackagingPipelineCachedStorage(NonPackagingMixin, PipelineCachedStorage): # Deprecated since Django 2.2 # Removed in Django 3.1 pass
NonPackagingPipelineStorage
python
spack__spack
lib/spack/spack/test/cmd_extensions.py
{ "start": 271, "end": 10391 }
class ____: """Helper class to simplify the creation of simple command extension directory structures with a conventional format for testing. """ def __init__(self, name, root: pathlib.Path): """Create a command extension. Args: name (str): The name of the command extension. root (path object): The temporary root for the command extension (e.g. from tmp_path.mkdir()). """ self.name = name self.pname = spack.cmd.python_name(name) self.root = root self.main = self.root / self.pname self.main.mkdir(parents=True, exist_ok=True) self.cmd = self.main / "cmd" self.cmd.mkdir(parents=True, exist_ok=True) def add_command(self, command_name, contents): """Add a command to this command extension. Args: command_name (str): The name of the command. contents (str): the desired contents of the new command module file.""" spack.cmd.require_cmd_name(command_name) python_name = spack.cmd.python_name(command_name) cmd = self.cmd / (python_name + ".py") cmd.write_text(contents) @pytest.fixture(scope="function") def extension_creator(tmp_path: pathlib.Path, config): """Create a basic extension command directory structure""" @contextlib.contextmanager def _ce(extension_name="testcommand"): root = tmp_path / ("spack-" + extension_name) root.mkdir() extension = Extension(extension_name, root) with spack.config.override("config:extensions", [str(extension.root)]): yield extension list_of_modules = list(sys.modules.keys()) try: yield _ce finally: to_be_deleted = [x for x in sys.modules if x not in list_of_modules] for module_name in to_be_deleted: del sys.modules[module_name] @pytest.fixture(scope="function") def hello_world_extension(extension_creator): """Create an extension with a hello-world command.""" with extension_creator() as extension: extension.add_command( "hello-world", """ description = "hello world extension command" section = "test command" level = "long" def setup_parser(subparser): pass def hello_world(parser, args): print('Hello world!') """, ) yield extension @pytest.fixture(scope="function") def hello_world_cmd(hello_world_extension): """Create and return an invokable "hello-world" extension command.""" yield spack.main.SpackCommand("hello-world") @pytest.fixture(scope="function") def hello_world_with_module_in_root(extension_creator): """Create a "hello-world" extension command with additional code in the root folder. """ @contextlib.contextmanager def _hwwmir(extension_name=None): with ( extension_creator(extension_name) if extension_name else extension_creator() ) as extension: # Note that the namespace of the extension is derived from the # fixture. extension.add_command( "hello", """ # Test an absolute import from spack.extensions.{ext_pname}.implementation import hello_world # Test a relative import from ..implementation import hello_folks description = "hello world extension command" section = "test command" level = "long" # Test setting a global variable in setup_parser and retrieving # it in the command global_message = 'foo' def setup_parser(subparser): sp = subparser.add_subparsers(metavar='SUBCOMMAND', dest='subcommand') global global_message sp.add_parser('world', help='Print Hello world!') sp.add_parser('folks', help='Print Hello folks!') sp.add_parser('global', help='Print Hello folks!') global_message = 'bar' def hello(parser, args): if args.subcommand == 'world': hello_world() elif args.subcommand == 'folks': hello_folks() elif args.subcommand == 'global': print(global_message) """.format( ext_pname=extension.pname ), ) init_file = extension.main / "__init__.py" init_file.touch() implementation = extension.main / "implementation.py" implementation.write_text( """ def hello_world(): print('Hello world!') def hello_folks(): print('Hello folks!') """ ) yield spack.main.SpackCommand("hello") yield _hwwmir def test_simple_command_extension(hello_world_cmd): """Basic test of a functioning command.""" output = hello_world_cmd() assert "Hello world!" in output def test_multi_extension_search(hello_world_extension, extension_creator): """Ensure we can find an extension command even if it's not in the first place we look. """ with extension_creator("testcommand2"): assert ("Hello world") in spack.main.SpackCommand("hello-world")() def test_duplicate_module_load(hello_world_cmd, capsys): """Ensure duplicate module load attempts are successful. The command module will already have been loaded once by the hello_world_cmd fixture. """ parser = spack.main.make_argument_parser() args = [] hw_cmd = spack.cmd.get_command(hello_world_cmd.command_name) hw_cmd(parser, args) captured = capsys.readouterr() assert captured == ("Hello world!\n", "") @pytest.mark.parametrize( "extension_name", [None, "hyphenated-extension"], ids=["simple", "hyphenated_extension_name"] ) def test_command_with_import(extension_name, hello_world_with_module_in_root): """Ensure we can write a functioning command with multiple imported subcommands, including where the extension name contains a hyphen. """ with hello_world_with_module_in_root(extension_name) as hello_world: output = hello_world("world") assert "Hello world!" in output output = hello_world("folks") assert "Hello folks!" in output output = hello_world("global") assert "bar" in output def test_missing_command(): """Ensure that we raise the expected exception if the desired command is not present. """ with pytest.raises(spack.cmd.CommandNotFoundError): spack.cmd.get_module("no-such-command") @pytest.mark.parametrize( "extension_path,expected_exception", [ ("/my/bad/extension", spack.extensions.ExtensionNamingError), ("", spack.extensions.ExtensionNamingError), ("/my/bad/spack--extra-hyphen", spack.extensions.ExtensionNamingError), ("/my/good/spack-extension", spack.cmd.CommandNotFoundError), ("/my/still/good/spack-extension/", spack.cmd.CommandNotFoundError), ("/my/spack-hyphenated-extension", spack.cmd.CommandNotFoundError), ], ids=["no_stem", "vacuous", "leading_hyphen", "basic_good", "trailing_slash", "hyphenated"], ) def test_extension_naming(tmp_path: pathlib.Path, extension_path, expected_exception, config): """Ensure that we are correctly validating configured extension paths for conformity with the rules: the basename should match ``spack-<name>``; <name> may have embedded hyphens but not begin with one. """ # NOTE: if the directory is a valid extension directory name the "vacuous" test will # fail because it resolves to current working directory import spack.llnl.util.filesystem as fs with fs.working_dir(str(tmp_path)): with spack.config.override("config:extensions", [extension_path]): with pytest.raises(expected_exception): spack.cmd.get_module("no-such-command") def test_missing_command_function(extension_creator, capsys): """Ensure we die as expected if a command module does not have the expected command function defined. """ with extension_creator() as extension: extension.add_command("bad-cmd", """\ndescription = "Empty command implementation"\n""") with pytest.raises(SystemExit): spack.cmd.get_module("bad-cmd") capture = capsys.readouterr() assert "must define function 'bad_cmd'." in capture[1] def test_get_command_paths(config): """Exercise the construction of extension command search paths.""" extensions = ("extension-1", "extension-2") ext_paths = [] expected_cmd_paths = [] for ext in extensions: ext_path = os.path.join("my", "path", "to", "spack-" + ext) ext_paths.append(ext_path) path = os.path.join(ext_path, spack.cmd.python_name(ext), "cmd") path = os.path.abspath(path) expected_cmd_paths.append(path) with spack.config.override("config:extensions", ext_paths): assert spack.extensions.get_command_paths() == expected_cmd_paths def test_variable_in_extension_path(config, working_env): """Test variables in extension paths.""" os.environ["_MY_VAR"] = os.path.join("my", "var") ext_paths = [os.path.join("~", "${_MY_VAR}", "spack-extension-1")] # Home env variable is USERPROFILE on Windows home_env = "USERPROFILE" if sys.platform == "win32" else "HOME" expected_ext_paths = [ os.path.join(os.environ[home_env], os.environ["_MY_VAR"], "spack-extension-1") ] with spack.config.override("config:extensions", ext_paths): assert spack.extensions.get_extension_paths() == expected_ext_paths @pytest.mark.parametrize( "command_name,contents,exception", [ ("bad-cmd", "from oopsie.daisy import bad\n", ImportError), ("bad-cmd", """var = bad_function_call('blech')\n""", NameError), ("bad-cmd", ")\n", SyntaxError), ], ids=["ImportError", "NameError", "SyntaxError"], ) def test_failing_command(command_name, contents, exception, extension_creator): """Ensure that the configured command fails to import with the specified error. """ with extension_creator() as extension: extension.add_command(command_name, contents) with pytest.raises(exception): spack.extensions.get_module(command_name)
Extension
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 54346, "end": 55852 }
class ____(Request): """ get scalar metric data for task :param task: task ID :type task: str :param metric: type of metric :type metric: str """ _service = "events" _action = "get_scalar_metric_data" _version = "2.9" _schema = { "definitions": {}, "properties": { "metric": {"description": "type of metric", "type": ["string", "null"]}, "task": {"description": "task ID", "type": ["string", "null"]}, }, "type": "object", } def __init__(self, task: Optional[str] = None, metric: Optional[str] = None, **kwargs: Any) -> None: super(GetScalarMetricDataRequest, self).__init__(**kwargs) self.task = task self.metric = metric @schema_property("task") def task(self) -> Optional[str]: return self._property_task @task.setter def task(self, value: Optional[str]) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("metric") def metric(self) -> Optional[str]: return self._property_metric @metric.setter def metric(self, value: Optional[str]) -> None: if value is None: self._property_metric = None return self.assert_isinstance(value, "metric", six.string_types) self._property_metric = value
GetScalarMetricDataRequest
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_mac.py
{ "start": 1637, "end": 3785 }
class ____(ColumnMapExpectation): """Expect column values to be valid MAC addresses.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "well_formed_mac": [ "01:23:45:67:89:AB", "01-23-45-67-89-AB", "FF:FF:FF:FF:FF:FF", ], "malformed_mac": [ "01-23-45-67-89", "01-23-45-67-89-AB-CD", "01-23-45-67-89-AH", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "well_formed_mac"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "malformed_mac"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_mac" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": ["experimental", "hackathon", "typed-entities"], "contributors": [ "@voidforall", ], } if __name__ == "__main__": ExpectColumnValuesToBeValidMac().print_diagnostic_checklist()
ExpectColumnValuesToBeValidMac
python
tiangolo__fastapi
docs_src/path_operation_advanced_configuration/tutorial004.py
{ "start": 109, "end": 717 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: Set[str] = set() @app.post("/items/", response_model=Item, summary="Create an item") async def create_item(item: Item): """ Create an item with all the information: - **name**: each item must have a name - **description**: a long description - **price**: required - **tax**: if the item doesn't have tax, you can omit this - **tags**: a set of unique tag strings for this item \f :param item: User input. """ return item
Item
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/black/cases/line_ranges_fmt_off_decorator.py
{ "start": 266, "end": 496 }
class ____: # fmt: off @decorator ( ) # fmt: on def method(): print ( "str" ) @decor( a=1, # fmt: off b=(2, 3), # fmt: on ) def func(): pass
MyClass
python
jina-ai__jina
tests/integration/stateful/stateful_no_snapshot_exec/executor.py
{ "start": 198, "end": 334 }
class ____(TextDoc): id: str tags: Dict[str, str] = {} l: List[str] = [] random_num = random.randint(0, 50000)
TextDocWithId
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 17144, "end": 17856 }
class ____(TypedDict, total=False): type: Required[Literal['model']] cls: Required[type[Any]] schema: Required[CoreSchema] def model_ser_schema(cls: type[Any], schema: CoreSchema) -> ModelSerSchema: """ Returns a schema for serialization using a model. Args: cls: The expected class type, used to generate warnings if the wrong type is passed schema: Internal schema to use to serialize the model dict """ return ModelSerSchema(type='model', cls=cls, schema=schema) SerSchema = Union[ SimpleSerSchema, PlainSerializerFunctionSerSchema, WrapSerializerFunctionSerSchema, FormatSerSchema, ToStringSerSchema, ModelSerSchema, ]
ModelSerSchema
python
wandb__wandb
wandb/sdk/artifacts/_generated/fetch_org_info_from_entity.py
{ "start": 320, "end": 466 }
class ____(GQLResult): organization: Optional[OrgInfoFragment] user: Optional[FetchOrgInfoFromEntityEntityUser]
FetchOrgInfoFromEntityEntity
python
ray-project__ray
python/ray/serve/_private/request_router/common.py
{ "start": 1890, "end": 3602 }
class ____: def __init__( self, *, staleness_timeout_s: float = RAY_SERVE_QUEUE_LENGTH_CACHE_TIMEOUT_S, get_curr_time_s: Optional[Callable[[], float]] = None, ): self._cache: Dict[ReplicaID, ReplicaQueueLengthCacheEntry] = {} self._staleness_timeout_s = staleness_timeout_s self._get_curr_time_s = ( get_curr_time_s if get_curr_time_s is not None else lambda: time.time() ) def _is_timed_out(self, timestamp_s: int) -> bool: return self._get_curr_time_s() - timestamp_s > self._staleness_timeout_s def get(self, replica_id: ReplicaID) -> Optional[int]: """Get the queue length for a replica. Returns `None` if the replica ID is not present or the entry is timed out. """ entry = self._cache.get(replica_id) if entry is None or self._is_timed_out(entry.timestamp): return None return entry.queue_len def update(self, replica_id: ReplicaID, queue_len: int): """Set (or update) the queue length for a replica ID.""" self._cache[replica_id] = ReplicaQueueLengthCacheEntry( queue_len, self._get_curr_time_s() ) def invalidate_key(self, replica_id: ReplicaID): self._cache.pop(replica_id, None) def remove_inactive_replicas(self, *, active_replica_ids: Set[ReplicaID]): """Removes entries for all replica IDs not in the provided active set.""" # NOTE: the size of the cache dictionary changes during this loop. for replica_id in list(self._cache.keys()): if replica_id not in active_replica_ids: self._cache.pop(replica_id)
ReplicaQueueLengthCache
python
getsentry__sentry
src/sentry/integrations/jira/models/create_issue_metadata.py
{ "start": 1279, "end": 2663 }
class ____: schema_type: str """ The Field type. Possible types include: - string - array (has a corresponding `items` field with its subtype) - user - issuetype - issuelink - project (and PROJECT) - date - team - any """ custom: str | None = None """ The very long custom field name corresponding to some namespace, plugin, and custom field name. """ custom_id: int | None = None """ A unique identifier for a field on an issue, in the form of 'customfield_<int>' """ system: str | None = None """ TODO(Gabe): Figure out what this is used for """ items: str | None = None """ Specifies the subtype for aggregate type, such as `array`. For any non-aggregate types, this will be None """ @classmethod def from_dict(cls, data: dict[str, Any]) -> JiraSchema: schema_type = data["type"] custom = data.get("custom") custom_id = data.get("custom_id") system = data.get("system") items = data.get("items") return cls( schema_type=schema_type, custom=custom, custom_id=custom_id, system=system, items=items ) @classmethod def from_dict_list(cls, data: list[dict[str, Any]]) -> list[JiraSchema]: return [cls.from_dict(item) for item in data] @dataclass(frozen=True)
JiraSchema
python
huggingface__transformers
src/transformers/pipelines/token_classification.py
{ "start": 4778, "end": 29932 }
class ____(ChunkPipeline): """ Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition examples](../task_summary#named-entity-recognition) for more information. Example: ```python >>> from transformers import pipeline >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple") >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal" >>> tokens = token_classifier(sentence) >>> tokens [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}] >>> token = tokens[0] >>> # Start and end provide an easy way to highlight words in the original text. >>> sentence[token["start"] : token["end"]] ' jean-baptiste' >>> # Some models use the same idea to do part of speech. >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple") >>> syntaxer("My name is Sarah and I live in London") [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}] ``` Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier: `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous). The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=token-classification). """ default_input_names = "sequences" _load_processor = False _load_image_processor = False _load_feature_extractor = False _load_tokenizer = True def __init__(self, args_parser=TokenClassificationArgumentHandler(), **kwargs): super().__init__(**kwargs) self.check_model_type(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES) self._basic_tokenizer = BasicTokenizer(do_lower_case=False) self._args_parser = args_parser def _sanitize_parameters( self, ignore_labels=None, grouped_entities: bool | None = None, ignore_subwords: bool | None = None, aggregation_strategy: AggregationStrategy | None = None, offset_mapping: list[tuple[int, int]] | None = None, is_split_into_words: bool = False, stride: int | None = None, delimiter: str | None = None, ): preprocess_params = {} preprocess_params["is_split_into_words"] = is_split_into_words if is_split_into_words: preprocess_params["delimiter"] = " " if delimiter is None else delimiter if offset_mapping is not None: preprocess_params["offset_mapping"] = offset_mapping postprocess_params = {} if grouped_entities is not None or ignore_subwords is not None: if grouped_entities and ignore_subwords: aggregation_strategy = AggregationStrategy.FIRST elif grouped_entities and not ignore_subwords: aggregation_strategy = AggregationStrategy.SIMPLE else: aggregation_strategy = AggregationStrategy.NONE if grouped_entities is not None: warnings.warn( "`grouped_entities` is deprecated and will be removed in version v5.0.0, defaulted to" f' `aggregation_strategy="{aggregation_strategy}"` instead.' ) if ignore_subwords is not None: warnings.warn( "`ignore_subwords` is deprecated and will be removed in version v5.0.0, defaulted to" f' `aggregation_strategy="{aggregation_strategy}"` instead.' ) if aggregation_strategy is not None: if isinstance(aggregation_strategy, str): aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()] if ( aggregation_strategy in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE} and not self.tokenizer.is_fast ): raise ValueError( "Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option" ' to `"simple"` or use a fast tokenizer.' ) postprocess_params["aggregation_strategy"] = aggregation_strategy if ignore_labels is not None: postprocess_params["ignore_labels"] = ignore_labels if stride is not None: if stride >= self.tokenizer.model_max_length: raise ValueError( "`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)" ) if aggregation_strategy == AggregationStrategy.NONE: raise ValueError( "`stride` was provided to process all the text but `aggregation_strategy=" f'"{aggregation_strategy}"`, please select another one instead.' ) else: if self.tokenizer.is_fast: tokenizer_params = { "return_overflowing_tokens": True, "padding": True, "stride": stride, } preprocess_params["tokenizer_params"] = tokenizer_params else: raise ValueError( "`stride` was provided to process all the text but you're using a slow tokenizer." " Please use a fast tokenizer." ) return preprocess_params, {}, postprocess_params @overload def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, str]]: ... @overload def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ... def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, str]] | list[list[dict[str, str]]]: """ Classify each token of the text(s) given as inputs. Args: inputs (`str` or `List[str]`): One or several texts (or one list of texts) for token classification. Can be pre-tokenized when `is_split_into_words=True`. Return: A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with the following keys: - **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you want to have the exact string in the original sentence, use `start` and `end`. - **score** (`float`) -- The corresponding probability for `entity`. - **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when *aggregation_strategy* is not `"none"`. - **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding token in the sentence. - **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only exists if the offsets are available within the tokenizer - **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only exists if the offsets are available within the tokenizer """ _inputs, is_split_into_words, offset_mapping, delimiter = self._args_parser(inputs, **kwargs) kwargs["is_split_into_words"] = is_split_into_words kwargs["delimiter"] = delimiter if is_split_into_words and not all(isinstance(input, list) for input in inputs): return super().__call__([inputs], **kwargs) if offset_mapping: kwargs["offset_mapping"] = offset_mapping return super().__call__(inputs, **kwargs) def preprocess(self, sentence, offset_mapping=None, **preprocess_params): tokenizer_params = preprocess_params.pop("tokenizer_params", {}) truncation = self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0 word_to_chars_map = None is_split_into_words = preprocess_params["is_split_into_words"] if is_split_into_words: delimiter = preprocess_params["delimiter"] if not isinstance(sentence, list): raise ValueError("When `is_split_into_words=True`, `sentence` must be a list of tokens.") words = sentence sentence = delimiter.join(words) # Recreate the sentence string for later display and slicing # This map will allows to convert back word => char indices word_to_chars_map = [] delimiter_len = len(delimiter) char_offset = 0 for word in words: word_to_chars_map.append((char_offset, char_offset + len(word))) char_offset += len(word) + delimiter_len # We use `words` as the actual input for the tokenizer text_to_tokenize = words tokenizer_params["is_split_into_words"] = True else: if not isinstance(sentence, str): raise ValueError("When `is_split_into_words=False`, `sentence` must be an untokenized string.") text_to_tokenize = sentence inputs = self.tokenizer( text_to_tokenize, return_tensors="pt", truncation=truncation, return_special_tokens_mask=True, return_offsets_mapping=self.tokenizer.is_fast, **tokenizer_params, ) if is_split_into_words and not self.tokenizer.is_fast: raise ValueError("is_split_into_words=True is only supported with fast tokenizers.") inputs.pop("overflow_to_sample_mapping", None) num_chunks = len(inputs["input_ids"]) for i in range(num_chunks): model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()} if offset_mapping is not None: model_inputs["offset_mapping"] = offset_mapping model_inputs["sentence"] = sentence if i == 0 else None model_inputs["is_last"] = i == num_chunks - 1 if word_to_chars_map is not None: model_inputs["word_ids"] = inputs.word_ids(i) model_inputs["word_to_chars_map"] = word_to_chars_map yield model_inputs def _forward(self, model_inputs): # Forward special_tokens_mask = model_inputs.pop("special_tokens_mask") offset_mapping = model_inputs.pop("offset_mapping", None) sentence = model_inputs.pop("sentence") is_last = model_inputs.pop("is_last") word_ids = model_inputs.pop("word_ids", None) word_to_chars_map = model_inputs.pop("word_to_chars_map", None) output = self.model(**model_inputs) logits = output["logits"] if isinstance(output, dict) else output[0] return { "logits": logits, "special_tokens_mask": special_tokens_mask, "offset_mapping": offset_mapping, "sentence": sentence, "is_last": is_last, "word_ids": word_ids, "word_to_chars_map": word_to_chars_map, **model_inputs, } def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None): if ignore_labels is None: ignore_labels = ["O"] all_entities = [] # Get map from the first output, it's the same for all chunks word_to_chars_map = all_outputs[0].get("word_to_chars_map") for model_outputs in all_outputs: if model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16): logits = model_outputs["logits"][0].to(torch.float32).numpy() else: logits = model_outputs["logits"][0].numpy() sentence = all_outputs[0]["sentence"] input_ids = model_outputs["input_ids"][0] offset_mapping = ( model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None ) special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy() word_ids = model_outputs.get("word_ids") maxes = np.max(logits, axis=-1, keepdims=True) shifted_exp = np.exp(logits - maxes) scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) pre_entities = self.gather_pre_entities( sentence, input_ids, scores, offset_mapping, special_tokens_mask, aggregation_strategy, word_ids=word_ids, word_to_chars_map=word_to_chars_map, ) grouped_entities = self.aggregate(pre_entities, aggregation_strategy) # Filter anything that is in self.ignore_labels entities = [ entity for entity in grouped_entities if entity.get("entity", None) not in ignore_labels and entity.get("entity_group", None) not in ignore_labels ] all_entities.extend(entities) num_chunks = len(all_outputs) if num_chunks > 1: all_entities = self.aggregate_overlapping_entities(all_entities) return all_entities def aggregate_overlapping_entities(self, entities): if len(entities) == 0: return entities entities = sorted(entities, key=lambda x: x["start"]) aggregated_entities = [] previous_entity = entities[0] for entity in entities: if previous_entity["start"] <= entity["start"] < previous_entity["end"]: current_length = entity["end"] - entity["start"] previous_length = previous_entity["end"] - previous_entity["start"] if ( current_length > previous_length or current_length == previous_length and entity["score"] > previous_entity["score"] ): previous_entity = entity else: aggregated_entities.append(previous_entity) previous_entity = entity aggregated_entities.append(previous_entity) return aggregated_entities def gather_pre_entities( self, sentence: str, input_ids: np.ndarray, scores: np.ndarray, offset_mapping: list[tuple[int, int]] | None, special_tokens_mask: np.ndarray, aggregation_strategy: AggregationStrategy, word_ids: list[int | None] | None = None, word_to_chars_map: list[tuple[int, int]] | None = None, ) -> list[dict]: """Fuse various numpy arrays into dicts with all the information needed for aggregation""" pre_entities = [] for idx, token_scores in enumerate(scores): # Filter special_tokens if special_tokens_mask[idx]: continue word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx])) if offset_mapping is not None: start_ind, end_ind = offset_mapping[idx] # If the input is pre-tokenized, we need to rescale the offsets to the absolute sentence. if word_ids is not None and word_to_chars_map is not None: word_index = word_ids[idx] if word_index is not None: start_char, _ = word_to_chars_map[word_index] start_ind += start_char end_ind += start_char if not isinstance(start_ind, int): start_ind = start_ind.item() end_ind = end_ind.item() word_ref = sentence[start_ind:end_ind] if getattr(self.tokenizer, "_tokenizer", None) and getattr( self.tokenizer._tokenizer.model, "continuing_subword_prefix", None ): # This is a BPE, word aware tokenizer, there is a correct way # to fuse tokens is_subword = len(word) != len(word_ref) else: # This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately. if aggregation_strategy in { AggregationStrategy.FIRST, AggregationStrategy.AVERAGE, AggregationStrategy.MAX, }: warnings.warn( "Tokenizer does not support real words, using fallback heuristic", UserWarning, ) is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1] if int(input_ids[idx]) == self.tokenizer.unk_token_id: word = word_ref is_subword = False else: start_ind = None end_ind = None is_subword = False pre_entity = { "word": word, "scores": token_scores, "start": start_ind, "end": end_ind, "index": idx, "is_subword": is_subword, } pre_entities.append(pre_entity) return pre_entities def aggregate(self, pre_entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}: entities = [] for pre_entity in pre_entities: entity_idx = pre_entity["scores"].argmax() score = pre_entity["scores"][entity_idx] entity = { "entity": self.model.config.id2label[entity_idx], "score": score, "index": pre_entity["index"], "word": pre_entity["word"], "start": pre_entity["start"], "end": pre_entity["end"], } entities.append(entity) else: entities = self.aggregate_words(pre_entities, aggregation_strategy) if aggregation_strategy == AggregationStrategy.NONE: return entities return self.group_entities(entities) def aggregate_word(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> dict: word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities]) if aggregation_strategy == AggregationStrategy.FIRST: scores = entities[0]["scores"] idx = scores.argmax() score = scores[idx] entity = self.model.config.id2label[idx] elif aggregation_strategy == AggregationStrategy.MAX: max_entity = max(entities, key=lambda entity: entity["scores"].max()) scores = max_entity["scores"] idx = scores.argmax() score = scores[idx] entity = self.model.config.id2label[idx] elif aggregation_strategy == AggregationStrategy.AVERAGE: scores = np.stack([entity["scores"] for entity in entities]) average_scores = np.nanmean(scores, axis=0) entity_idx = average_scores.argmax() entity = self.model.config.id2label[entity_idx] score = average_scores[entity_idx] else: raise ValueError("Invalid aggregation_strategy") new_entity = { "entity": entity, "score": score, "word": word, "start": entities[0]["start"], "end": entities[-1]["end"], } return new_entity def aggregate_words(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: """ Override tokens from a given word that disagree to force agreement on word boundaries. Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft| company| B-ENT I-ENT """ if aggregation_strategy in { AggregationStrategy.NONE, AggregationStrategy.SIMPLE, }: raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation") word_entities = [] word_group = None for entity in entities: if word_group is None: word_group = [entity] elif entity["is_subword"]: word_group.append(entity) else: word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) word_group = [entity] # Last item if word_group is not None: word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) return word_entities def group_sub_entities(self, entities: list[dict]) -> dict: """ Group together the adjacent tokens with the same entity predicted. Args: entities (`dict`): The entities predicted by the pipeline. """ # Get the first entity in the entity group entity = entities[0]["entity"].split("-", 1)[-1] scores = np.nanmean([entity["score"] for entity in entities]) tokens = [entity["word"] for entity in entities] entity_group = { "entity_group": entity, "score": np.mean(scores), "word": self.tokenizer.convert_tokens_to_string(tokens), "start": entities[0]["start"], "end": entities[-1]["end"], } return entity_group def get_tag(self, entity_name: str) -> tuple[str, str]: if entity_name.startswith("B-"): bi = "B" tag = entity_name[2:] elif entity_name.startswith("I-"): bi = "I" tag = entity_name[2:] else: # It's not in B-, I- format # Default to I- for continuation. bi = "I" tag = entity_name return bi, tag def group_entities(self, entities: list[dict]) -> list[dict]: """ Find and group together the adjacent tokens with the same entity predicted. Args: entities (`dict`): The entities predicted by the pipeline. """ entity_groups = [] entity_group_disagg = [] for entity in entities: if not entity_group_disagg: entity_group_disagg.append(entity) continue # If the current entity is similar and adjacent to the previous entity, # append it to the disaggregated entity group # The split is meant to account for the "B" and "I" prefixes # Shouldn't merge if both entities are B-type bi, tag = self.get_tag(entity["entity"]) last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"]) if tag == last_tag and bi != "B": # Modify subword type to be previous_type entity_group_disagg.append(entity) else: # If the current entity is different from the previous entity # aggregate the disaggregated entity group entity_groups.append(self.group_sub_entities(entity_group_disagg)) entity_group_disagg = [entity] if entity_group_disagg: # it's the last entity, add it to the entity groups entity_groups.append(self.group_sub_entities(entity_group_disagg)) return entity_groups NerPipeline = TokenClassificationPipeline
TokenClassificationPipeline
python
Textualize__textual
src/textual/widget.py
{ "start": 3458, "end": 4795 }
class ____: """An *optional* awaitable returned by [mount][textual.widget.Widget.mount] and [mount_all][textual.widget.Widget.mount_all]. Example: ```python await self.mount(Static("foo")) ``` """ def __init__(self, parent: Widget, widgets: Sequence[Widget]) -> None: self._parent = parent self._widgets = widgets self._caller = get_caller_file_and_line() def __rich_repr__(self) -> rich.repr.Result: yield "parent", self._parent yield "widgets", self._widgets yield "caller", self._caller, None async def __call__(self) -> None: """Allows awaiting via a call operation.""" await self def __await__(self) -> Generator[None, None, None]: async def await_mount() -> None: if self._widgets: aws = [ create_task(widget._mounted_event.wait(), name="await mount") for widget in self._widgets ] if aws: await wait(aws) self._parent.refresh(layout=True) try: self._parent.app._update_mouse_over(self._parent.screen) except NoScreen: pass return await_mount().__await__()
AwaitMount
python
huggingface__transformers
tests/models/chinese_clip/test_modeling_chinese_clip.py
{ "start": 21251, "end": 24196 }
class ____(unittest.TestCase): @slow def test_inference(self): model_name = "OFA-Sys/chinese-clip-vit-base-patch16" model = ChineseCLIPModel.from_pretrained(model_name).to(torch_device) processor = ChineseCLIPProcessor.from_pretrained(model_name) image = prepare_img() inputs = processor( text=["杰尼龟", "妙蛙种子", "小火龙", "皮卡丘"], images=image, padding=True, return_tensors="pt" ).to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits self.assertEqual( outputs.logits_per_image.shape, torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])), ) self.assertEqual( outputs.logits_per_text.shape, torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])), ) probs = outputs.logits_per_image.softmax(dim=1) expected_probs = torch.tensor([[1.2686e-03, 5.4499e-02, 6.7968e-04, 9.4355e-01]], device=torch_device) torch.testing.assert_close(probs, expected_probs, rtol=5e-3, atol=5e-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_name = "OFA-Sys/chinese-clip-vit-base-patch16" model = ChineseCLIPModel.from_pretrained(model_name).to(torch_device) image_processor = ChineseCLIPProcessor.from_pretrained( model_name, size={"height": 180, "width": 180}, crop_size={"height": 180, "width": 180} ) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") inputs = image_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, 122, 768)) self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape) expected_slice = torch.tensor( [[-0.3990, 0.2983, -0.1239], [-0.1452, -0.2759, 0.0403], [-0.3149, -0.4763, 0.8555]] ).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 )
ChineseCLIPModelIntegrationTest
python
Netflix__metaflow
test/core/tests/resume_foreach_split.py
{ "start": 67, "end": 2300 }
class ____(MetaflowTest): """ Resuming from a foreach split should work. Check that data changes in all downstream steps after resume. """ RESUME = True PRIORITY = 3 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] @steps(0, ["start"]) def step_start(self): self.data = "start" self.after = False @steps(0, ["foreach-nested-split", "foreach-split"], required=True) def step_split(self): self.after = True if is_resumed(): self.data = "resume" else: self.data = "run" raise ResumeFromHere() @steps(0, ["foreach-inner"], required=True) def inner(self): self.stack = [ list(map(str, getattr(self, frame.var))) for frame in self._foreach_stack ] self.var = ["".join(str(x[2]) for x in self.foreach_stack())] if self.after: assert_equals("resume", self.data) else: assert_equals("start", self.data) @steps(0, ["join"], required=True) def step_join(self, inputs): from itertools import chain self.var = list(sorted(chain.from_iterable(i.var for i in inputs))) self.data = inputs[0].data self.after = inputs[0].after self.stack = inputs[0].stack if self.after: assert_equals("resume", self.data) else: assert_equals("start", self.data) @steps(2, ["all"]) def step_all(self): if self.after: assert_equals("resume", self.data) else: assert_equals("start", self.data) def check_results(self, flow, checker): from itertools import product checker.assert_artifact("start", "data", "start") checker.assert_artifact("end", "data", "resume") stack = next(iter(checker.artifact_dict("end", "stack").values()))["stack"] expected = sorted("".join(p) for p in product(*stack)) checker.assert_artifact("end", "var", expected)
ResumeForeachSplitTest
python
Textualize__textual
docs/examples/guide/layout/grid_layout_auto.py
{ "start": 80, "end": 534 }
class ____(App): CSS_PATH = "grid_layout_auto.tcss" def compose(self) -> ComposeResult: yield Static("First column", classes="box") yield Static("Two", classes="box") yield Static("Three", classes="box") yield Static("Four", classes="box") yield Static("Five", classes="box") yield Static("Six", classes="box") if __name__ == "__main__": app = GridLayoutExample() app.run()
GridLayoutExample
python
Textualize__rich
rich/syntax.py
{ "start": 7871, "end": 36261 }
class ____(JupyterMixin): """Construct a Syntax object to render syntax highlighted code. Args: code (str): Code to highlight. lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/) theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "monokai". dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False. start_line (int, optional): Starting number for line numbers. Defaults to 1. line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render. A value of None in the tuple indicates the range is open in that direction. highlight_lines (Set[int]): A set of line numbers to highlight. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width. tab_size (int, optional): Size of tabs. Defaults to 4. word_wrap (bool, optional): Enable word wrapping. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None. indent_guides (bool, optional): Show indent guides. Defaults to False. padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding). """ _pygments_style_class: Type[PygmentsStyle] _theme: SyntaxTheme @classmethod def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme: """Get a syntax theme instance.""" if isinstance(name, SyntaxTheme): return name theme: SyntaxTheme if name in RICH_SYNTAX_THEMES: theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name]) else: theme = PygmentsSyntaxTheme(name) return theme def __init__( self, code: str, lexer: Union[Lexer, str], *, theme: Union[str, SyntaxTheme] = DEFAULT_THEME, dedent: bool = False, line_numbers: bool = False, start_line: int = 1, line_range: Optional[Tuple[Optional[int], Optional[int]]] = None, highlight_lines: Optional[Set[int]] = None, code_width: Optional[int] = None, tab_size: int = 4, word_wrap: bool = False, background_color: Optional[str] = None, indent_guides: bool = False, padding: PaddingDimensions = 0, ) -> None: self.code = code self._lexer = lexer self.dedent = dedent self.line_numbers = line_numbers self.start_line = start_line self.line_range = line_range self.highlight_lines = highlight_lines or set() self.code_width = code_width self.tab_size = tab_size self.word_wrap = word_wrap self.background_color = background_color self.background_style = ( Style(bgcolor=background_color) if background_color else Style() ) self.indent_guides = indent_guides self._padding = Padding.unpack(padding) self._theme = self.get_theme(theme) self._stylized_ranges: List[_SyntaxHighlightRange] = [] padding = PaddingProperty() @classmethod def from_path( cls, path: str, encoding: str = "utf-8", lexer: Optional[Union[Lexer, str]] = None, theme: Union[str, SyntaxTheme] = DEFAULT_THEME, dedent: bool = False, line_numbers: bool = False, line_range: Optional[Tuple[int, int]] = None, start_line: int = 1, highlight_lines: Optional[Set[int]] = None, code_width: Optional[int] = None, tab_size: int = 4, word_wrap: bool = False, background_color: Optional[str] = None, indent_guides: bool = False, padding: PaddingDimensions = 0, ) -> "Syntax": """Construct a Syntax object from a file. Args: path (str): Path to file to highlight. encoding (str): Encoding of file. lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content. theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to "emacs". dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True. line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False. start_line (int, optional): Starting number for line numbers. Defaults to 1. line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render. highlight_lines (Set[int]): A set of line numbers to highlight. code_width: Width of code to render (not including line numbers), or ``None`` to use all available width. tab_size (int, optional): Size of tabs. Defaults to 4. word_wrap (bool, optional): Enable word wrapping of code. background_color (str, optional): Optional background color, or None to use theme color. Defaults to None. indent_guides (bool, optional): Show indent guides. Defaults to False. padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding). Returns: [Syntax]: A Syntax object that may be printed to the console """ code = Path(path).read_text(encoding=encoding) if not lexer: lexer = cls.guess_lexer(path, code=code) return cls( code, lexer, theme=theme, dedent=dedent, line_numbers=line_numbers, line_range=line_range, start_line=start_line, highlight_lines=highlight_lines, code_width=code_width, tab_size=tab_size, word_wrap=word_wrap, background_color=background_color, indent_guides=indent_guides, padding=padding, ) @classmethod def guess_lexer(cls, path: str, code: Optional[str] = None) -> str: """Guess the alias of the Pygments lexer to use based on a path and an optional string of code. If code is supplied, it will use a combination of the code and the filename to determine the best lexer to use. For example, if the file is ``index.html`` and the file contains Django templating syntax, then "html+django" will be returned. If the file is ``index.html``, and no templating language is used, the "html" lexer will be used. If no string of code is supplied, the lexer will be chosen based on the file extension.. Args: path (AnyStr): The path to the file containing the code you wish to know the lexer for. code (str, optional): Optional string of code that will be used as a fallback if no lexer is found for the supplied path. Returns: str: The name of the Pygments lexer that best matches the supplied path/code. """ lexer: Optional[Lexer] = None lexer_name = "default" if code: try: lexer = guess_lexer_for_filename(path, code) except ClassNotFound: pass if not lexer: try: _, ext = os.path.splitext(path) if ext: extension = ext.lstrip(".").lower() lexer = get_lexer_by_name(extension) except ClassNotFound: pass if lexer: if lexer.aliases: lexer_name = lexer.aliases[0] else: lexer_name = lexer.name return lexer_name def _get_base_style(self) -> Style: """Get the base style.""" default_style = self._theme.get_background_style() + self.background_style return default_style def _get_token_color(self, token_type: TokenType) -> Optional[Color]: """Get a color (if any) for the given token. Args: token_type (TokenType): A token type tuple from Pygments. Returns: Optional[Color]: Color from theme, or None for no color. """ style = self._theme.get_style_for_token(token_type) return style.color @property def lexer(self) -> Optional[Lexer]: """The lexer for this syntax, or None if no lexer was found. Tries to find the lexer by name if a string was passed to the constructor. """ if isinstance(self._lexer, Lexer): return self._lexer try: return get_lexer_by_name( self._lexer, stripnl=False, ensurenl=True, tabsize=self.tab_size, ) except ClassNotFound: return None @property def default_lexer(self) -> Lexer: """A Pygments Lexer to use if one is not specified or invalid.""" return get_lexer_by_name( "text", stripnl=False, ensurenl=True, tabsize=self.tab_size, ) def highlight( self, code: str, line_range: Optional[Tuple[Optional[int], Optional[int]]] = None, ) -> Text: """Highlight code and return a Text instance. Args: code (str): Code to highlight. line_range(Tuple[int, int], optional): Optional line range to highlight. Returns: Text: A text instance containing highlighted syntax. """ base_style = self._get_base_style() justify: JustifyMethod = ( "default" if base_style.transparent_background else "left" ) text = Text( justify=justify, style=base_style, tab_size=self.tab_size, no_wrap=not self.word_wrap, ) _get_theme_style = self._theme.get_style_for_token lexer = self.lexer or self.default_lexer if lexer is None: text.append(code) else: if line_range: # More complicated path to only stylize a portion of the code # This speeds up further operations as there are less spans to process line_start, line_end = line_range def line_tokenize() -> Iterable[Tuple[Any, str]]: """Split tokens to one per line.""" assert lexer # required to make MyPy happy - we know lexer is not None at this point for token_type, token in lexer.get_tokens(code): while token: line_token, new_line, token = token.partition("\n") yield token_type, line_token + new_line def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]: """Convert tokens to spans.""" tokens = iter(line_tokenize()) line_no = 0 _line_start = line_start - 1 if line_start else 0 # Skip over tokens until line start while line_no < _line_start: try: _token_type, token = next(tokens) except StopIteration: break yield (token, None) if token.endswith("\n"): line_no += 1 # Generate spans until line end for token_type, token in tokens: yield (token, _get_theme_style(token_type)) if token.endswith("\n"): line_no += 1 if line_end and line_no >= line_end: break text.append_tokens(tokens_to_spans()) else: text.append_tokens( (token, _get_theme_style(token_type)) for token_type, token in lexer.get_tokens(code) ) if self.background_color is not None: text.stylize(f"on {self.background_color}") if self._stylized_ranges: self._apply_stylized_ranges(text) return text def stylize_range( self, style: StyleType, start: SyntaxPosition, end: SyntaxPosition, style_before: bool = False, ) -> None: """ Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered. Line numbers are 1-based, while column indexes are 0-based. Args: style (StyleType): The style to apply. start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`. end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`. style_before (bool): Apply the style before any existing styles. """ self._stylized_ranges.append( _SyntaxHighlightRange(style, start, end, style_before) ) def _get_line_numbers_color(self, blend: float = 0.3) -> Color: background_style = self._theme.get_background_style() + self.background_style background_color = background_style.bgcolor if background_color is None or background_color.is_system_defined: return Color.default() foreground_color = self._get_token_color(Token.Text) if foreground_color is None or foreground_color.is_system_defined: return foreground_color or Color.default() new_color = blend_rgb( background_color.get_truecolor(), foreground_color.get_truecolor(), cross_fade=blend, ) return Color.from_triplet(new_color) @property def _numbers_column_width(self) -> int: """Get the number of characters used to render the numbers column.""" column_width = 0 if self.line_numbers: column_width = ( len(str(self.start_line + self.code.count("\n"))) + NUMBERS_COLUMN_DEFAULT_PADDING ) return column_width def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]: """Get background, number, and highlight styles for line numbers.""" background_style = self._get_base_style() if background_style.transparent_background: return Style.null(), Style(dim=True), Style.null() if console.color_system in ("256", "truecolor"): number_style = Style.chain( background_style, self._theme.get_style_for_token(Token.Text), Style(color=self._get_line_numbers_color()), self.background_style, ) highlight_number_style = Style.chain( background_style, self._theme.get_style_for_token(Token.Text), Style(bold=True, color=self._get_line_numbers_color(0.9)), self.background_style, ) else: number_style = background_style + Style(dim=True) highlight_number_style = background_style + Style(dim=False) return background_style, number_style, highlight_number_style def __rich_measure__( self, console: "Console", options: "ConsoleOptions" ) -> "Measurement": _, right, _, left = self.padding padding = left + right if self.code_width is not None: width = self.code_width + self._numbers_column_width + padding + 1 return Measurement(self._numbers_column_width, width) lines = self.code.splitlines() width = ( self._numbers_column_width + padding + (max(cell_len(line) for line in lines) if lines else 0) ) if self.line_numbers: width += 1 return Measurement(self._numbers_column_width, width) def __rich_console__( self, console: Console, options: ConsoleOptions ) -> RenderResult: segments = Segments(self._get_syntax(console, options)) if any(self.padding): yield Padding(segments, style=self._get_base_style(), pad=self.padding) else: yield segments def _get_syntax( self, console: Console, options: ConsoleOptions, ) -> Iterable[Segment]: """ Get the Segments for the Syntax object, excluding any vertical/horizontal padding """ transparent_background = self._get_base_style().transparent_background _pad_top, pad_right, _pad_bottom, pad_left = self.padding horizontal_padding = pad_left + pad_right code_width = ( ( (options.max_width - self._numbers_column_width - 1) if self.line_numbers else options.max_width ) - horizontal_padding if self.code_width is None else self.code_width ) code_width = max(0, code_width) ends_on_nl, processed_code = self._process_code(self.code) text = self.highlight(processed_code, self.line_range) if not self.line_numbers and not self.word_wrap and not self.line_range: if not ends_on_nl: text.remove_suffix("\n") # Simple case of just rendering text style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) if self.indent_guides and not options.ascii_only: text = text.with_indent_guides(self.tab_size, style=style) text.overflow = "crop" if style.transparent_background: yield from console.render( text, options=options.update(width=code_width) ) else: syntax_lines = console.render_lines( text, options.update(width=code_width, height=None, justify="left"), style=self.background_style, pad=True, new_lines=True, ) for syntax_line in syntax_lines: yield from syntax_line return start_line, end_line = self.line_range or (None, None) line_offset = 0 if start_line: line_offset = max(0, start_line - 1) lines: Union[List[Text], Lines] = text.split("\n", allow_blank=ends_on_nl) if self.line_range: if line_offset > len(lines): return lines = lines[line_offset:end_line] if self.indent_guides and not options.ascii_only: style = ( self._get_base_style() + self._theme.get_style_for_token(Comment) + Style(dim=True) + self.background_style ) lines = ( Text("\n") .join(lines) .with_indent_guides(self.tab_size, style=style + Style(italic=False)) .split("\n", allow_blank=True) ) numbers_column_width = self._numbers_column_width render_options = options.update(width=code_width) highlight_line = self.highlight_lines.__contains__ _Segment = Segment new_line = _Segment("\n") line_pointer = "> " if options.legacy_windows else "❱ " ( background_style, number_style, highlight_number_style, ) = self._get_number_styles(console) for line_no, line in enumerate(lines, self.start_line + line_offset): if self.word_wrap: wrapped_lines = console.render_lines( line, render_options.update(height=None, justify="left"), style=background_style, pad=not transparent_background, ) else: segments = list(line.render(console, end="")) if options.no_wrap: wrapped_lines = [segments] else: wrapped_lines = [ _Segment.adjust_line_length( segments, render_options.max_width, style=background_style, pad=not transparent_background, ) ] if self.line_numbers: wrapped_line_left_pad = _Segment( " " * numbers_column_width + " ", background_style ) for first, wrapped_line in loop_first(wrapped_lines): if first: line_column = str(line_no).rjust(numbers_column_width - 2) + " " if highlight_line(line_no): yield _Segment(line_pointer, Style(color="red")) yield _Segment(line_column, highlight_number_style) else: yield _Segment(" ", highlight_number_style) yield _Segment(line_column, number_style) else: yield wrapped_line_left_pad yield from wrapped_line yield new_line else: for wrapped_line in wrapped_lines: yield from wrapped_line yield new_line def _apply_stylized_ranges(self, text: Text) -> None: """ Apply stylized ranges to a text instance, using the given code to determine the right portion to apply the style to. Args: text (Text): Text instance to apply the style to. """ code = text.plain newlines_offsets = [ # Let's add outer boundaries at each side of the list: 0, # N.B. using "\n" here is much faster than using metacharacters such as "^" or "\Z": *[ match.start() + 1 for match in re.finditer("\n", code, flags=re.MULTILINE) ], len(code) + 1, ] for stylized_range in self._stylized_ranges: start = _get_code_index_for_syntax_position( newlines_offsets, stylized_range.start ) end = _get_code_index_for_syntax_position( newlines_offsets, stylized_range.end ) if start is not None and end is not None: if stylized_range.style_before: text.stylize_before(stylized_range.style, start, end) else: text.stylize(stylized_range.style, start, end) def _process_code(self, code: str) -> Tuple[bool, str]: """ Applies various processing to a raw code string (normalises it so it always ends with a line return, dedents it if necessary, etc.) Args: code (str): The raw code string to process Returns: Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return, while the string is the processed code. """ ends_on_nl = code.endswith("\n") processed_code = code if ends_on_nl else code + "\n" processed_code = ( textwrap.dedent(processed_code) if self.dedent else processed_code ) processed_code = processed_code.expandtabs(self.tab_size) return ends_on_nl, processed_code def _get_code_index_for_syntax_position( newlines_offsets: Sequence[int], position: SyntaxPosition ) -> Optional[int]: """ Returns the index of the code string for the given positions. Args: newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet. position (SyntaxPosition): The position to search for. Returns: Optional[int]: The index of the code string for this position, or `None` if the given position's line number is out of range (if it's the column that is out of range we silently clamp its value so that it reaches the end of the line) """ lines_count = len(newlines_offsets) line_number, column_index = position if line_number > lines_count or len(newlines_offsets) < (line_number + 1): return None # `line_number` is out of range line_index = line_number - 1 line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1 # If `column_index` is out of range: let's silently clamp it: column_index = min(line_length, column_index) return newlines_offsets[line_index] + column_index if __name__ == "__main__": # pragma: no cover import argparse import sys parser = argparse.ArgumentParser( description="Render syntax to the console with Rich" ) parser.add_argument( "path", metavar="PATH", help="path to file, or - for stdin", ) parser.add_argument( "-c", "--force-color", dest="force_color", action="store_true", default=None, help="force color for non-terminals", ) parser.add_argument( "-i", "--indent-guides", dest="indent_guides", action="store_true", default=False, help="display indent guides", ) parser.add_argument( "-l", "--line-numbers", dest="line_numbers", action="store_true", help="render line numbers", ) parser.add_argument( "-w", "--width", type=int, dest="width", default=None, help="width of output (default will auto-detect)", ) parser.add_argument( "-r", "--wrap", dest="word_wrap", action="store_true", default=False, help="word wrap long lines", ) parser.add_argument( "-s", "--soft-wrap", action="store_true", dest="soft_wrap", default=False, help="enable soft wrapping mode", ) parser.add_argument( "-t", "--theme", dest="theme", default="monokai", help="pygments theme" ) parser.add_argument( "-b", "--background-color", dest="background_color", default=None, help="Override background color", ) parser.add_argument( "-x", "--lexer", default=None, dest="lexer_name", help="Lexer name", ) parser.add_argument( "-p", "--padding", type=int, default=0, dest="padding", help="Padding" ) parser.add_argument( "--highlight-line", type=int, default=None, dest="highlight_line", help="The line number (not index!) to highlight", ) args = parser.parse_args() from rich.console import Console console = Console(force_terminal=args.force_color, width=args.width) if args.path == "-": code = sys.stdin.read() syntax = Syntax( code=code, lexer=args.lexer_name, line_numbers=args.line_numbers, word_wrap=args.word_wrap, theme=args.theme, background_color=args.background_color, indent_guides=args.indent_guides, padding=args.padding, highlight_lines={args.highlight_line}, ) else: syntax = Syntax.from_path( args.path, lexer=args.lexer_name, line_numbers=args.line_numbers, word_wrap=args.word_wrap, theme=args.theme, background_color=args.background_color, indent_guides=args.indent_guides, padding=args.padding, highlight_lines={args.highlight_line}, ) console.print(syntax, soft_wrap=args.soft_wrap)
Syntax
python
GoogleCloudPlatform__python-docs-samples
people-and-planet-ai/weather-forecasting/serving/weather-model/weather/model.py
{ "start": 1837, "end": 4721 }
class ____(PreTrainedModel): """A custom Hugging Face model. For more information: https://huggingface.co/docs/transformers/main/en/custom_models#writing-a-custom-model """ config_class = WeatherConfig def __init__(self, config: WeatherConfig) -> None: super().__init__(config) self.layers = torch.nn.Sequential( Normalization(config.mean, config.std), MoveDim(-1, 1), # convert to channels-first torch.nn.Conv2d(config.num_inputs, config.num_hidden1, config.kernel_size), torch.nn.ReLU(), torch.nn.ConvTranspose2d( config.num_hidden1, config.num_hidden2, config.kernel_size ), torch.nn.ReLU(), MoveDim(1, -1), # convert to channels-last torch.nn.Linear(config.num_hidden2, config.num_outputs), torch.nn.ReLU(), # precipitation cannot be negative ) def forward( self, inputs: torch.Tensor, labels: torch.Tensor | None = None ) -> dict[str, torch.Tensor]: """Computes predictions as expected by ModelOutputs. If `labels` are passed, it computes the loss between the model's predictions and the actual labels. For more information: https://huggingface.co/docs/transformers/main/en/main_classes/output Args: inputs: Input data. labels: Ground truth data. Returns: {"loss": loss, "logits": predictions} if `labels` is provided. {"logits": predictions} otherwise. """ predictions = self.layers(inputs) if labels is None: return {"logits": predictions} loss_fn = torch.nn.SmoothL1Loss() loss = loss_fn(predictions, labels) return {"loss": loss, "logits": predictions} @staticmethod def create(inputs: Dataset, **kwargs: AnyType) -> WeatherModel: """Creates a new WeatherModel calculating the mean and standard deviation from a dataset.""" data = np.array(inputs, np.float32) mean = data.mean(axis=(0, 1, 2))[None, None, None, :] std = data.std(axis=(0, 1, 2))[None, None, None, :] config = WeatherConfig(mean.tolist(), std.tolist(), **kwargs) return WeatherModel(config) def predict(self, inputs: AnyType) -> np.ndarray: """Predicts a single request.""" return self.predict_batch(torch.as_tensor([inputs]))[0] def predict_batch(self, inputs_batch: AnyType) -> np.ndarray: """Predicts a batch of requests.""" device = "cuda" if torch.cuda.is_available() else "cpu" model = self.to(device) with torch.no_grad(): outputs = model(torch.as_tensor(inputs_batch, device=device)) predictions = outputs["logits"] return predictions.cpu().numpy()
WeatherModel
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 8276, "end": 8577 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__(event_id=38, name="PROJECT_DISABLE", api_name="project.disable") def render(self, audit_log_entry: AuditLogEntry) -> str: return render_project_action(audit_log_entry, "disable")
ProjectDisableAuditLogEvent
python
aimacode__aima-python
csp.py
{ "start": 20241, "end": 23830 }
class ____: """A universal dict maps any key to the same value. We use it here as the domains dict for CSPs in which all variables have the same domain. >>> d = UniversalDict(42) >>> d['life'] 42 """ def __init__(self, value): self.value = value def __getitem__(self, key): return self.value def __repr__(self): return '{{Any: {0!r}}}'.format(self.value) def different_values_constraint(A, a, B, b): """A constraint saying two neighboring variables must differ in value.""" return a != b def MapColoringCSP(colors, neighbors): """Make a CSP for the problem of coloring a map with different colors for any two adjacent regions. Arguments are a list of colors, and a dict of {region: [neighbor,...]} entries. This dict may also be specified as a string of the form defined by parse_neighbors.""" if isinstance(neighbors, str): neighbors = parse_neighbors(neighbors) return CSP(list(neighbors.keys()), UniversalDict(colors), neighbors, different_values_constraint) def parse_neighbors(neighbors): """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for each region name. If you say 'X: Y' you don't need 'Y: X'. >>> parse_neighbors('X: Y Z; Y: Z') == {'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']} True """ dic = defaultdict(list) specs = [spec.split(':') for spec in neighbors.split(';')] for (A, Aneighbors) in specs: A = A.strip() for B in Aneighbors.split(): dic[A].append(B) dic[B].append(A) return dic australia_csp = MapColoringCSP(list('RGB'), """SA: WA NT Q NSW V; NT: WA Q; NSW: Q V; T: """) usa_csp = MapColoringCSP(list('RGBY'), """WA: OR ID; OR: ID NV CA; CA: NV AZ; NV: ID UT AZ; ID: MT WY UT; UT: WY CO AZ; MT: ND SD WY; WY: SD NE CO; CO: NE KA OK NM; NM: OK TX AZ; ND: MN SD; SD: MN IA NE; NE: IA MO KA; KA: MO OK; OK: MO AR TX; TX: AR LA; MN: WI IA; IA: WI IL MO; MO: IL KY TN AR; AR: MS TN LA; LA: MS; WI: MI IL; IL: IN KY; IN: OH KY; MS: TN AL; AL: TN GA FL; MI: OH IN; OH: PA WV KY; KY: WV VA TN; TN: VA NC GA; GA: NC SC FL; PA: NY NJ DE MD WV; WV: MD VA; VA: MD DC NC; NC: SC; NY: VT MA CT NJ; NJ: DE; DE: MD; MD: DC; VT: NH MA; MA: NH RI CT; CT: RI; ME: NH; HI: ; AK: """) france_csp = MapColoringCSP(list('RGBY'), """AL: LO FC; AQ: MP LI PC; AU: LI CE BO RA LR MP; BO: CE IF CA FC RA AU; BR: NB PL; CA: IF PI LO FC BO; CE: PL NB NH IF BO AU LI PC; FC: BO CA LO AL RA; IF: NH PI CA BO CE; LI: PC CE AU MP AQ; LO: CA AL FC; LR: MP AU RA PA; MP: AQ LI AU LR; NB: NH CE PL BR; NH: PI IF CE NB; NO: PI; PA: LR RA; PC: PL CE LI AQ; PI: NH NO CA IF; PL: BR NB CE PC; RA: AU BO FC PA LR""") # ______________________________________________________________________________ # n-Queens Problem def queen_constraint(A, a, B, b): """Constraint is satisfied (true) if A, B are really the same variable, or if they are not in the same row, down diagonal, or up diagonal.""" return A == B or (a != b and A + a != B + b and A - a != B - b)
UniversalDict
python
great-expectations__great_expectations
tests/integration/test_utils/data_source_config/mysql.py
{ "start": 658, "end": 1450 }
class ____(DataSourceTestConfig): @property @override def label(self) -> str: return "mysql" @property @override def pytest_mark(self) -> pytest.MarkDecorator: return pytest.mark.mysql @override def create_batch_setup( self, request: pytest.FixtureRequest, data: pd.DataFrame, extra_data: Mapping[str, pd.DataFrame], context: AbstractDataContext, engine_manager: Optional[SessionSQLEngineManager] = None, ) -> BatchTestSetup: return MySQLBatchTestSetup( data=data, config=self, extra_data=extra_data, table_name=self.table_name, context=context, engine_manager=engine_manager, )
MySQLDatasourceTestConfig
python
python-jsonschema__jsonschema
jsonschema/tests/test_deprecations.py
{ "start": 292, "end": 15754 }
class ____(TestCase): def test_version(self): """ As of v4.0.0, __version__ is deprecated in favor of importlib.metadata. """ message = "Accessing jsonschema.__version__ is deprecated" with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import __version__ self.assertEqual(__version__, importlib.metadata.version("jsonschema")) self.assertEqual(w.filename, __file__) def test_validators_ErrorTree(self): """ As of v4.0.0, importing ErrorTree from jsonschema.validators is deprecated in favor of doing so from jsonschema.exceptions. """ message = "Importing ErrorTree from jsonschema.validators is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema.validators import ErrorTree self.assertEqual(ErrorTree, exceptions.ErrorTree) self.assertEqual(w.filename, __file__) def test_import_ErrorTree(self): """ As of v4.18.0, importing ErrorTree from the package root is deprecated in favor of doing so from jsonschema.exceptions. """ message = "Importing ErrorTree directly from the jsonschema package " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import ErrorTree self.assertEqual(ErrorTree, exceptions.ErrorTree) self.assertEqual(w.filename, __file__) def test_ErrorTree_setitem(self): """ As of v4.20.0, setting items on an ErrorTree is deprecated. """ e = exceptions.ValidationError("some error", path=["foo"]) tree = exceptions.ErrorTree() subtree = exceptions.ErrorTree(errors=[e]) message = "ErrorTree.__setitem__ is " with self.assertWarnsRegex(DeprecationWarning, message) as w: tree["foo"] = subtree self.assertEqual(tree["foo"], subtree) self.assertEqual(w.filename, __file__) def test_import_FormatError(self): """ As of v4.18.0, importing FormatError from the package root is deprecated in favor of doing so from jsonschema.exceptions. """ message = "Importing FormatError directly from the jsonschema package " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import FormatError self.assertEqual(FormatError, exceptions.FormatError) self.assertEqual(w.filename, __file__) def test_import_Validator(self): """ As of v4.19.0, importing Validator from the package root is deprecated in favor of doing so from jsonschema.protocols. """ message = "Importing Validator directly from the jsonschema package " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import Validator self.assertEqual(Validator, protocols.Validator) self.assertEqual(w.filename, __file__) def test_validators_validators(self): """ As of v4.0.0, accessing jsonschema.validators.validators is deprecated. """ message = "Accessing jsonschema.validators.validators is deprecated" with self.assertWarnsRegex(DeprecationWarning, message) as w: value = validators.validators self.assertEqual(value, validators._VALIDATORS) self.assertEqual(w.filename, __file__) def test_validators_meta_schemas(self): """ As of v4.0.0, accessing jsonschema.validators.meta_schemas is deprecated. """ message = "Accessing jsonschema.validators.meta_schemas is deprecated" with self.assertWarnsRegex(DeprecationWarning, message) as w: value = validators.meta_schemas self.assertEqual(value, validators._META_SCHEMAS) self.assertEqual(w.filename, __file__) def test_RefResolver_in_scope(self): """ As of v4.0.0, RefResolver.in_scope is deprecated. """ resolver = validators._RefResolver.from_schema({}) message = "jsonschema.RefResolver.in_scope is deprecated " with self.assertWarnsRegex(DeprecationWarning, message) as w: # noqa: SIM117 with resolver.in_scope("foo"): pass self.assertEqual(w.filename, __file__) def test_Validator_is_valid_two_arguments(self): """ As of v4.0.0, calling is_valid with two arguments (to provide a different schema) is deprecated. """ validator = validators.Draft7Validator({}) message = "Passing a schema to Validator.is_valid is deprecated " with self.assertWarnsRegex(DeprecationWarning, message) as w: result = validator.is_valid("foo", {"type": "number"}) self.assertFalse(result) self.assertEqual(w.filename, __file__) def test_Validator_iter_errors_two_arguments(self): """ As of v4.0.0, calling iter_errors with two arguments (to provide a different schema) is deprecated. """ validator = validators.Draft7Validator({}) message = "Passing a schema to Validator.iter_errors is deprecated " with self.assertWarnsRegex(DeprecationWarning, message) as w: error, = validator.iter_errors("foo", {"type": "number"}) self.assertEqual(error.validator, "type") self.assertEqual(w.filename, __file__) def test_Validator_resolver(self): """ As of v4.18.0, accessing Validator.resolver is deprecated. """ validator = validators.Draft7Validator({}) message = "Accessing Draft7Validator.resolver is " with self.assertWarnsRegex(DeprecationWarning, message) as w: self.assertIsInstance(validator.resolver, validators._RefResolver) self.assertEqual(w.filename, __file__) def test_RefResolver(self): """ As of v4.18.0, RefResolver is fully deprecated. """ message = "jsonschema.RefResolver is deprecated" with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import RefResolver self.assertEqual(w.filename, __file__) with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema.validators import RefResolver # noqa: F401 self.assertEqual(w.filename, __file__) def test_RefResolutionError(self): """ As of v4.18.0, RefResolutionError is deprecated in favor of directly catching errors from the referencing library. """ message = "jsonschema.exceptions.RefResolutionError is deprecated" with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import RefResolutionError self.assertEqual(RefResolutionError, exceptions._RefResolutionError) self.assertEqual(w.filename, __file__) with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema.exceptions import RefResolutionError self.assertEqual(RefResolutionError, exceptions._RefResolutionError) self.assertEqual(w.filename, __file__) def test_catching_Unresolvable_directly(self): """ This behavior is the intended behavior (i.e. it's not deprecated), but given we do "tricksy" things in the iterim to wrap exceptions in a multiple inheritance subclass, we need to be extra sure it works and stays working. """ validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) with self.assertRaises(referencing.exceptions.Unresolvable) as e: validator.validate(12) expected = referencing.exceptions.Unresolvable(ref="urn:nothing") self.assertEqual( (e.exception, str(e.exception)), (expected, "Unresolvable: urn:nothing"), ) def test_catching_Unresolvable_via_RefResolutionError(self): """ Until RefResolutionError is removed, it is still possible to catch exceptions from reference resolution using it, even though they may have been raised by referencing. """ with self.assertWarns(DeprecationWarning): from jsonschema import RefResolutionError validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) with self.assertRaises(referencing.exceptions.Unresolvable) as u: validator.validate(12) with self.assertRaises(RefResolutionError) as e: validator.validate(12) self.assertEqual( (e.exception, str(e.exception)), (u.exception, "Unresolvable: urn:nothing"), ) def test_WrappedReferencingError_hashability(self): """ Ensure the wrapped referencing errors are hashable when possible. """ with self.assertWarns(DeprecationWarning): from jsonschema import RefResolutionError validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) with self.assertRaises(referencing.exceptions.Unresolvable) as u: validator.validate(12) with self.assertRaises(RefResolutionError) as e: validator.validate(12) self.assertIn(e.exception, {u.exception}) self.assertIn(u.exception, {e.exception}) def test_Validator_subclassing(self): """ As of v4.12.0, subclassing a validator class produces an explicit deprecation warning. This was never intended to be public API (and some comments over the years in issues said so, but obviously that's not a great way to make sure it's followed). A future version will explicitly raise an error. """ message = "Subclassing validator classes is " with self.assertWarnsRegex(DeprecationWarning, message) as w: class Subclass(validators.Draft202012Validator): pass self.assertEqual(w.filename, __file__) with self.assertWarnsRegex(DeprecationWarning, message) as w: class AnotherSubclass(validators.create(meta_schema={})): pass def test_FormatChecker_cls_checks(self): """ As of v4.14.0, FormatChecker.cls_checks is deprecated without replacement. """ self.addCleanup(FormatChecker.checkers.pop, "boom", None) message = "FormatChecker.cls_checks " with self.assertWarnsRegex(DeprecationWarning, message) as w: FormatChecker.cls_checks("boom") self.assertEqual(w.filename, __file__) def test_draftN_format_checker(self): """ As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated in favor of Validator.FORMAT_CHECKER. """ message = "Accessing jsonschema.draft202012_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft202012_format_checker self.assertIs( draft202012_format_checker, validators.Draft202012Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) message = "Accessing jsonschema.draft201909_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft201909_format_checker self.assertIs( draft201909_format_checker, validators.Draft201909Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) message = "Accessing jsonschema.draft7_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft7_format_checker self.assertIs( draft7_format_checker, validators.Draft7Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) message = "Accessing jsonschema.draft6_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft6_format_checker self.assertIs( draft6_format_checker, validators.Draft6Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) message = "Accessing jsonschema.draft4_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft4_format_checker self.assertIs( draft4_format_checker, validators.Draft4Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) message = "Accessing jsonschema.draft3_format_checker is " with self.assertWarnsRegex(DeprecationWarning, message) as w: from jsonschema import draft3_format_checker self.assertIs( draft3_format_checker, validators.Draft3Validator.FORMAT_CHECKER, ) self.assertEqual(w.filename, __file__) with self.assertRaises(ImportError): from jsonschema import draft1234_format_checker # noqa: F401 def test_import_cli(self): """ As of v4.17.0, importing jsonschema.cli is deprecated. """ message = "The jsonschema CLI is deprecated and will be removed " with self.assertWarnsRegex(DeprecationWarning, message) as w: import jsonschema.cli importlib.reload(jsonschema.cli) self.assertEqual(w.filename, importlib.__file__) def test_cli(self): """ As of v4.17.0, the jsonschema CLI is deprecated. """ process = subprocess.run( [sys.executable, "-m", "jsonschema"], capture_output=True, check=True, ) self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr) def test_automatic_remote_retrieval(self): """ Automatic retrieval of remote references is deprecated as of v4.18.0. """ ref = "http://bar#/$defs/baz" schema = {"$defs": {"baz": {"type": "integer"}}} if "requests" in sys.modules: # pragma: no cover self.addCleanup( sys.modules.__setitem__, "requests", sys.modules["requests"], ) sys.modules["requests"] = None @contextmanager def fake_urlopen(request): self.assertIsInstance(request, urllib.request.Request) self.assertEqual(request.full_url, "http://bar") # Ha ha urllib.request.Request "normalizes" header names and # Request.get_header does not also normalize them... (header, value), = request.header_items() self.assertEqual(header.lower(), "user-agent") self.assertEqual( value, "python-jsonschema (deprecated $ref resolution)", ) yield BytesIO(json.dumps(schema).encode("utf8")) validator = validators.Draft202012Validator({"$ref": ref}) message = "Automatically retrieving remote references " patch = mock.patch.object(urllib.request, "urlopen", new=fake_urlopen) with patch, self.assertWarnsRegex(DeprecationWarning, message): self.assertEqual( (validator.is_valid({}), validator.is_valid(37)), (False, True), )
TestDeprecations
python
kubernetes-client__python
kubernetes/client/models/v1_expression_warning.py
{ "start": 383, "end": 5228 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'field_ref': 'str', 'warning': 'str' } attribute_map = { 'field_ref': 'fieldRef', 'warning': 'warning' } def __init__(self, field_ref=None, warning=None, local_vars_configuration=None): # noqa: E501 """V1ExpressionWarning - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._field_ref = None self._warning = None self.discriminator = None self.field_ref = field_ref self.warning = warning @property def field_ref(self): """Gets the field_ref of this V1ExpressionWarning. # noqa: E501 The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\" # noqa: E501 :return: The field_ref of this V1ExpressionWarning. # noqa: E501 :rtype: str """ return self._field_ref @field_ref.setter def field_ref(self, field_ref): """Sets the field_ref of this V1ExpressionWarning. The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\" # noqa: E501 :param field_ref: The field_ref of this V1ExpressionWarning. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and field_ref is None: # noqa: E501 raise ValueError("Invalid value for `field_ref`, must not be `None`") # noqa: E501 self._field_ref = field_ref @property def warning(self): """Gets the warning of this V1ExpressionWarning. # noqa: E501 The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler. # noqa: E501 :return: The warning of this V1ExpressionWarning. # noqa: E501 :rtype: str """ return self._warning @warning.setter def warning(self, warning): """Sets the warning of this V1ExpressionWarning. The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler. # noqa: E501 :param warning: The warning of this V1ExpressionWarning. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and warning is None: # noqa: E501 raise ValueError("Invalid value for `warning`, must not be `None`") # noqa: E501 self._warning = warning def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ExpressionWarning): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1ExpressionWarning): return True return self.to_dict() != other.to_dict()
V1ExpressionWarning
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/url_test/package.py
{ "start": 217, "end": 392 }
class ____(Package): """Mock package that fetches from a URL.""" homepage = "http://www.url-fetch-example.com" version("test", url="to-be-filled-in-by-test")
UrlTest