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
mlflow__mlflow
mlflow/models/evaluation/default_evaluator.py
{ "start": 10552, "end": 41950 }
class ____(ModelEvaluator): """ The base class for all evaluators that are built-in to MLflow. Each evaluator is responsible for implementing the `_evaluate()` method, which is called by the `evaluate()` method of this base class. This class contains many helper methods used across built-in evaluators, such as logging metrics, artifacts, and ordering metrics. """ def __init__(self): self.client = MlflowClient() @abstractmethod def _evaluate( self, model: Optional["mlflow.pyfunc.PyFuncModel"], extra_metrics: list[EvaluationMetric], custom_artifacts=None, **kwargs, ) -> EvaluationResult | None: """Implement the evaluation logic for each evaluator.""" def log_metrics(self): """ Helper method to log metrics into specified run. """ self._add_prefix_to_metrics() timestamp = get_current_time_millis() self.client.log_batch( self.run_id, metrics=[ Metric( key=key, value=value, timestamp=timestamp, step=0, model_id=self.model_id, dataset_name=self.dataset.name, dataset_digest=self.dataset.digest, run_id=self.run_id, ) for key, value in self.aggregate_metrics.items() ], ) def _log_image_artifact( self, do_plot, artifact_name, ): from matplotlib import pyplot prefix = self.evaluator_config.get("metric_prefix", "") artifact_file_name = f"{prefix}{artifact_name}.png" artifact_file_local_path = self.temp_dir.path(artifact_file_name) try: pyplot.clf() do_plot() pyplot.savefig(artifact_file_local_path, bbox_inches="tight") except Exception as e: _logger.warning(f"Failed to log image artifact {artifact_name!r}: {e!r}") else: mlflow.log_artifact(artifact_file_local_path) artifact = ImageEvaluationArtifact(uri=mlflow.get_artifact_uri(artifact_file_name)) artifact._load(artifact_file_local_path) self.artifacts[artifact_name] = artifact finally: pyplot.close(pyplot.gcf()) def _evaluate_sklearn_model_score_if_scorable(self, model, y_true, sample_weights): model_loader_module, raw_model = _extract_raw_model(model) if model_loader_module == "mlflow.sklearn" and raw_model is not None: try: score = raw_model.score( self.X.copy_to_avoid_mutation(), y_true, sample_weight=sample_weights ) self.metrics_values.update(_get_aggregate_metrics_values({"score": score})) except Exception as e: _logger.warning( f"Computing sklearn model score failed: {e!r}. Set logging level to " "DEBUG to see the full traceback." ) _logger.debug("", exc_info=True) def _log_custom_metric_artifact(self, artifact_name, raw_artifact, custom_metric_tuple): """ This function logs and returns a custom metric artifact. Two cases: - The provided artifact is a path to a file, the function will make a copy of it with a formatted name in a temporary directory and call mlflow.log_artifact. - Otherwise: will attempt to save the artifact to an temporary path with an inferred type. Then call mlflow.log_artifact. Args: artifact_name: the name of the artifact raw_artifact: the object representing the artifact custom_metric_tuple: an instance of the _CustomMetric namedtuple Returns: EvaluationArtifact """ exception_and_warning_header = ( f"Custom artifact function '{custom_metric_tuple.name}' at index " f"{custom_metric_tuple.index} in the `custom_artifacts` parameter" ) inferred_from_path, inferred_type, inferred_ext = _infer_artifact_type_and_ext( artifact_name, raw_artifact, custom_metric_tuple ) artifact_file_local_path = self.temp_dir.path(artifact_name + inferred_ext) if pathlib.Path(artifact_file_local_path).exists(): raise MlflowException( f"{exception_and_warning_header} produced an artifact '{artifact_name}' that " "cannot be logged because there already exists an artifact with the same name." ) # ParquetEvaluationArtifact isn't explicitly stated here because such artifacts can only # be supplied through file. Which is handled by the first if clause. This is because # DataFrame objects default to be stored as CsvEvaluationArtifact. if inferred_from_path: shutil.copy2(raw_artifact, artifact_file_local_path) elif inferred_type is JsonEvaluationArtifact: with open(artifact_file_local_path, "w") as f: if isinstance(raw_artifact, str): f.write(raw_artifact) else: json.dump(raw_artifact, f, cls=NumpyEncoder) elif inferred_type is CsvEvaluationArtifact: raw_artifact.to_csv(artifact_file_local_path, index=False) elif inferred_type is NumpyEvaluationArtifact: np.save(artifact_file_local_path, raw_artifact, allow_pickle=False) elif inferred_type is ImageEvaluationArtifact: raw_artifact.savefig(artifact_file_local_path) else: # storing as pickle try: with open(artifact_file_local_path, "wb") as f: pickle.dump(raw_artifact, f) _logger.warning( f"{exception_and_warning_header} produced an artifact '{artifact_name}'" f" with type '{type(raw_artifact)}' that is logged as a pickle artifact." ) except pickle.PickleError: raise MlflowException( f"{exception_and_warning_header} produced an unsupported artifact " f"'{artifact_name}' with type '{type(raw_artifact)}' that cannot be pickled. " "Supported object types for artifacts are:\n" "- A string uri representing the file path to the artifact. MLflow" " will infer the type of the artifact based on the file extension.\n" "- A string representation of a JSON object. This will be saved as a " ".json artifact.\n" "- Pandas DataFrame. This will be saved as a .csv artifact." "- Numpy array. This will be saved as a .npy artifact." "- Matplotlib Figure. This will be saved as an .png image artifact." "- Other objects will be attempted to be pickled with default protocol." ) mlflow.log_artifact(artifact_file_local_path) artifact = inferred_type(uri=mlflow.get_artifact_uri(artifact_name + inferred_ext)) artifact._load(artifact_file_local_path) return artifact def _get_column_in_metrics_values(self, column): for metric_name, metric_value in self.metrics_values.items(): if metric_name.split("/")[0] == column: return metric_value def _get_args_for_metrics( self, metric: MetricDefinition, eval_df: pd.DataFrame, input_df: pd.DataFrame, other_output_df: pd.DataFrame | None, ) -> tuple[bool, list[str | pd.DataFrame]]: """ Given a metric_tuple, read the signature of the metric function and get the appropriate arguments from the input/output columns, other calculated metrics, and evaluator_config. Args: metric: The metric definition containing a user provided function and its index in the ``extra_metrics`` parameter of ``mlflow.evaluate``. eval_df: The evaluation dataframe containing the prediction and target columns. input_df: The input dataframe containing the features used to make predictions. other_output_df: A dataframe containing all model output columns but the predictions. Returns: tuple: A tuple of (bool, list) where the bool indicates if the given metric can be calculated with the given eval_df, metrics, and input_df. - If the user is missing "targets" or "predictions" parameters when needed, or we cannot find a column or metric for a parameter to the metric, return (False, list of missing parameters) - If all arguments to the metric function were found, return (True, list of arguments). """ # deepcopying eval_df and builtin_metrics for each custom metric function call, # in case the user modifies them inside their function(s). eval_df_copy = eval_df.copy() parameters = inspect.signature(metric.function).parameters eval_fn_args = [] params_not_found = [] if len(parameters) == 2: param_0_name, param_1_name = parameters.keys() # eval_fn has parameters (eval_df, builtin_metrics) for backwards compatibility if len(parameters) == 2 and param_0_name != "predictions" and param_1_name != "targets": eval_fn_args.append(eval_df_copy) self._update_aggregate_metrics() eval_fn_args.append(copy.deepcopy(self.aggregate_metrics)) # eval_fn can have parameters like (predictions, targets, metrics, random_col) else: for param_name, param in parameters.items(): column = self.col_mapping.get(param_name, param_name) if column in ("predictions", self.predictions, self.dataset.predictions_name): eval_fn_args.append(eval_df_copy["prediction"]) elif column in ("targets", self.dataset.targets_name): if "target" in eval_df_copy: eval_fn_args.append(eval_df_copy["target"]) else: if param.default == inspect.Parameter.empty: params_not_found.append(param_name) else: eval_fn_args.append(param.default) elif column == "metrics": eval_fn_args.append(copy.deepcopy(self.metrics_values)) else: # case when column passed in col_mapping contains the entire column if not isinstance(column, str): eval_fn_args.append(column) # case column in col_mapping is string and the column value # is part of the input_df elif column in input_df.columns: eval_fn_args.append(input_df[column]) # case column in col_mapping is string and the column value # is part of the output_df(other than predictions) elif other_output_df is not None and column in other_output_df.columns: self.other_output_columns_for_eval.add(column) eval_fn_args.append(other_output_df[column]) # case where the param is defined as part of the evaluator_config elif column in self.evaluator_config: eval_fn_args.append(self.evaluator_config.get(column)) # case where this is the name of another metric elif metric_value := self._get_column_in_metrics_values(column): eval_fn_args.append(metric_value) # in the case that: # the metric has not been calculated yet, but is scheduled to be calculated # "before" this metric in self.ordered_metrics, we append None to indicate # that there is not an error in the dependencies elif column in [metric_tuple.name for metric_tuple in self.ordered_metrics]: eval_fn_args.append(None) elif param.default == inspect.Parameter.empty: params_not_found.append(param_name) else: eval_fn_args.append(param.default) if len(params_not_found) > 0: return False, params_not_found return True, eval_fn_args def evaluate_and_log_custom_artifacts( self, custom_artifacts: list[_CustomArtifact], prediction: pd.Series, target: np.ndarray | None = None, ): """Evaluate custom artifacts provided by users.""" if not custom_artifacts: return eval_df = self._get_eval_df(prediction, target) for index, custom_artifact in enumerate(custom_artifacts): with tempfile.TemporaryDirectory() as artifacts_dir: # deepcopying eval_df and builtin_metrics for each custom artifact function call, # in case the user modifies them inside their function(s). custom_artifact_tuple = _CustomArtifact( function=custom_artifact, index=index, name=getattr(custom_artifact, "__name__", repr(custom_artifact)), artifacts_dir=artifacts_dir, ) artifact_results = _evaluate_custom_artifacts( custom_artifact_tuple, eval_df.copy(), copy.deepcopy(self.metrics_values), ) if artifact_results: for artifact_name, raw_artifact in artifact_results.items(): self.artifacts[artifact_name] = self._log_custom_metric_artifact( artifact_name, raw_artifact, custom_artifact_tuple, ) def _get_error_message_missing_columns(self, metric_name, param_names): error_message_parts = [f"Metric '{metric_name}' requires the following:"] special_params = ["targets", "predictions"] error_message_parts.extend( f" - the '{param}' parameter needs to be specified" for param in special_params if param in param_names ) if remaining_params := [param for param in param_names if param not in special_params]: error_message_parts.append( f" - missing columns {remaining_params} need to be defined or mapped" ) return "\n".join(error_message_parts) def _construct_error_message_for_malformed_metrics( self, malformed_results, input_columns, output_columns ): error_messages = [ self._get_error_message_missing_columns(metric_name, param_names) for metric_name, param_names in malformed_results ] joined_error_message = "\n".join(error_messages) full_message = f"""Error: Metric calculation failed for the following metrics: {joined_error_message} Below are the existing column names for the input/output data: Input Columns: {input_columns} Output Columns: {output_columns} To resolve this issue, you may need to: - specify any required parameters - if you are missing columns, check that there are no circular dependencies among your metrics, and you may want to map them to an existing column using the following configuration: evaluator_config={{'col_mapping': {{<missing column name>: <existing column name>}}}}""" return "\n".join(l.lstrip() for l in full_message.splitlines()) def _raise_exception_for_malformed_metrics(self, malformed_results, eval_df, other_output_df): output_columns = [] if other_output_df is None else list(other_output_df.columns) if self.predictions: output_columns.append(self.predictions) elif self.dataset.predictions_name: output_columns.append(self.dataset.predictions_name) else: output_columns.append("predictions") input_columns = list(self.X.copy_to_avoid_mutation().columns) if "target" in eval_df: if self.dataset.targets_name: input_columns.append(self.dataset.targets_name) else: input_columns.append("targets") error_message = self._construct_error_message_for_malformed_metrics( malformed_results, input_columns, output_columns ) raise MlflowException(error_message, error_code=INVALID_PARAMETER_VALUE) def _get_eval_df(self, prediction: pd.Series, target: np.ndarray | None = None): """ Create a DataFrame with "prediction" and "target" columns. This is a standard format that can be passed to the metric functions. """ eval_df = pd.DataFrame({"prediction": copy.deepcopy(prediction)}) if target is not None: eval_df["target"] = target return eval_df def _order_metrics( self, metrics: list[EvaluationMetric], eval_df: pd.DataFrame, other_output_df: pd.DataFrame | None, ): """ Order the list metrics so they can be computed in sequence. Some metrics might use the results of other metrics to compute their own results. This function iteratively resolve this dependency, by checking if each metric can be computed with the current available columns and metrics values. """ remaining_metrics = metrics input_df = self.X.copy_to_avoid_mutation() while len(remaining_metrics) > 0: pending_metrics = [] failed_results = [] did_append_metric = False for metric_tuple in remaining_metrics: can_calculate, eval_fn_args = self._get_args_for_metrics( metric_tuple, eval_df, input_df, other_output_df ) if can_calculate: self.ordered_metrics.append(metric_tuple) did_append_metric = True else: # cannot calculate the metric yet pending_metrics.append(metric_tuple) failed_results.append((metric_tuple.name, eval_fn_args)) # cant calculate any more metrics if not did_append_metric: self._raise_exception_for_malformed_metrics( failed_results, eval_df, other_output_df ) remaining_metrics = pending_metrics return self.ordered_metrics def _test_first_row( self, metrics: list[MetricDefinition], eval_df: pd.DataFrame, other_output_df: pd.DataFrame | None, ): # test calculations on first row of eval_df _logger.info("Testing metrics on first row...") exceptions = [] first_row_df = eval_df.iloc[[0]] first_row_input_df = self.X.copy_to_avoid_mutation().iloc[[0]] for metric in metrics: try: _, eval_fn_args = self._get_args_for_metrics( metric, first_row_df, first_row_input_df, other_output_df ) if metric_value := metric.evaluate(eval_fn_args): name = f"{metric.name}/{metric.version}" if metric.version else metric.name self.metrics_values.update({name: metric_value}) except Exception as e: stacktrace_str = traceback.format_exc() if isinstance(e, MlflowException): exceptions.append( f"Metric '{metric.name}': Error:\n{e.message}\n{stacktrace_str}" ) else: exceptions.append(f"Metric '{metric.name}': Error:\n{e!r}\n{stacktrace_str}") if len(exceptions) > 0: raise MlflowException("\n".join(exceptions)) def evaluate_metrics( self, metrics: list[EvaluationMetric], prediction: pd.Series, target: np.ndarray | None = None, other_output_df: pd.DataFrame | None = None, ): """ Evaluate the metrics on the given prediction and target data. Args: metrics: A list of metrics to evaluate. prediction: A Pandas Series containing the predictions. target: A numpy array containing the target values. other_output_df: A Pandas DataFrame containing other output columns from the model. Returns: None, the metrics values are recorded in the self.metrics_values dictionary. """ eval_df = self._get_eval_df(prediction, target) metrics = [ MetricDefinition.from_index_and_metric(i, metric) for i, metric in enumerate(metrics) ] metrics = self._order_metrics(metrics, eval_df, other_output_df) self._test_first_row(metrics, eval_df, other_output_df) # calculate metrics for the full eval_df input_df = self.X.copy_to_avoid_mutation() for metric in metrics: _, eval_fn_args = self._get_args_for_metrics(metric, eval_df, input_df, other_output_df) if metric_value := metric.evaluate(eval_fn_args): name = f"{metric.name}/{metric.version}" if metric.version else metric.name self.metrics_values.update({name: metric_value}) def log_eval_table(self, y_pred, other_output_columns=None): # only log eval table if there are per row metrics recorded if not any( metric_value.scores is not None or metric_value.justifications is not None for _, metric_value in self.metrics_values.items() ): return metric_prefix = self.evaluator_config.get("metric_prefix", "") if not isinstance(metric_prefix, str): metric_prefix = "" if isinstance(self.dataset.features_data, pd.DataFrame): # Handle DataFrame case if self.dataset.has_targets: data = self.dataset.features_data.assign( **{ self.dataset.targets_name or "target": self.dataset.labels_data, self.dataset.predictions_name or self.predictions or "outputs": y_pred, } ) else: data = self.dataset.features_data.assign(outputs=y_pred) else: # Handle NumPy array case, converting it to a DataFrame data = pd.DataFrame(self.dataset.features_data, columns=self.dataset.feature_names) if self.dataset.has_targets: data = data.assign( **{ self.dataset.targets_name or "target": self.dataset.labels_data, self.dataset.predictions_name or self.predictions or "outputs": y_pred, } ) else: data = data.assign(outputs=y_pred) # Include other_output_columns used in evaluation to the eval table if other_output_columns is not None and len(self.other_output_columns_for_eval) > 0: for column in self.other_output_columns_for_eval: data[column] = other_output_columns[column] columns = {} for metric_name, metric_value in self.metrics_values.items(): scores = metric_value.scores justifications = metric_value.justifications if scores: if metric_name.startswith(metric_prefix) and metric_name[len(metric_prefix) :] in [ _TOKEN_COUNT_METRIC_NAME, _LATENCY_METRIC_NAME, ]: columns[metric_name] = scores else: columns[f"{metric_name}/score"] = scores if justifications: columns[f"{metric_name}/justification"] = justifications data = data.assign(**columns) artifact_file_name = f"{metric_prefix}{_EVAL_TABLE_FILE_NAME}" mlflow.log_table(data, artifact_file=artifact_file_name) if self.eval_results_path: eval_table_spark = self.spark_session.createDataFrame(data) try: eval_table_spark.write.mode(self.eval_results_mode).option( "mergeSchema", "true" ).format("delta").saveAsTable(self.eval_results_path) except Exception as e: _logger.info(f"Saving eval table to delta table failed. Reason: {e}") name = _EVAL_TABLE_FILE_NAME.split(".", 1)[0] self.artifacts[name] = JsonEvaluationArtifact( uri=mlflow.get_artifact_uri(artifact_file_name) ) def _update_aggregate_metrics(self): self.aggregate_metrics = {} for metric_name, metric_value in self.metrics_values.items(): if metric_value.aggregate_results: for agg_name, agg_value in metric_value.aggregate_results.items(): if agg_value is not None: if agg_name == metric_name.split("/")[0]: self.aggregate_metrics[metric_name] = agg_value else: self.aggregate_metrics[f"{metric_name}/{agg_name}"] = agg_value def _add_prefix_to_metrics(self): def _prefix_value(value): aggregate = ( {f"{prefix}{k}": v for k, v in value.aggregate_results.items()} if value.aggregate_results else None ) return MetricValue(value.scores, value.justifications, aggregate) if prefix := self.evaluator_config.get("metric_prefix"): self.metrics_values = { f"{prefix}{k}": _prefix_value(v) for k, v in self.metrics_values.items() } self._update_aggregate_metrics() def evaluate( self, *, model_type, dataset, run_id, evaluator_config, model: "mlflow.pyfunc.PyFuncModel" = None, extra_metrics=None, custom_artifacts=None, predictions=None, model_id=None, **kwargs, ) -> EvaluationResult: if model is None and predictions is None and dataset.predictions_data is None: raise MlflowException( message=( "Either a model or set of predictions must be specified in order to use the" " default evaluator. Either specify the `model` parameter, the `predictions`" " parameter, an MLflow dataset containing the `predictions` column name" " (via the `data` parameter), or a different evaluator (via the `evaluators`" " parameter)." ), error_code=INVALID_PARAMETER_VALUE, ) self.artifacts = {} self.aggregate_metrics = {} self.metrics_values = {} self.ordered_metrics = [] self.other_output_columns_for_eval = set() self.dataset: EvaluationDataset = dataset self.run_id = run_id self.model_type = model_type self.model_id = model_id self.evaluator_config = evaluator_config self.predictions = predictions self.col_mapping = self.evaluator_config.get("col_mapping", {}) self.eval_results_path = self.evaluator_config.get("eval_results_path") self.eval_results_mode = self.evaluator_config.get("eval_results_mode", "overwrite") if self.eval_results_path: from mlflow.utils._spark_utils import _get_active_spark_session self.spark_session = _get_active_spark_session() if not self.spark_session: raise MlflowException( message="eval_results_path is only supported in Spark environment. ", error_code=INVALID_PARAMETER_VALUE, ) if self.eval_results_mode not in ["overwrite", "append"]: raise MlflowException( message="eval_results_mode can only be 'overwrite' or 'append'. ", error_code=INVALID_PARAMETER_VALUE, ) if extra_metrics is None: extra_metrics = [] bad_metrics = [ metric for metric in extra_metrics if not isinstance(metric, EvaluationMetric) ] if len(bad_metrics) > 0: message = "\n".join( [f"- Metric '{m}' has type '{type(m).__name__}'" for m in bad_metrics] ) raise MlflowException( f"In the 'extra_metrics' parameter, the following metrics have the wrong type:\n" f"{message}\n" f"Please ensure that all extra metrics are instances of " f"mlflow.metrics.EvaluationMetric." ) import matplotlib with TempDir() as temp_dir, matplotlib.rc_context(_matplotlib_config): self.temp_dir = temp_dir return self._evaluate(model, extra_metrics, custom_artifacts) @property def X(self) -> pd.DataFrame: """ The features (`X`) portion of the dataset, guarded against accidental mutations. """ return BuiltInEvaluator._MutationGuardedData( _get_dataframe_with_renamed_columns( self.dataset.features_data, self.dataset.feature_names ) ) class _MutationGuardedData: """ Wrapper around a data object that requires explicit API calls to obtain either a copy of the data object, or, in cases where the caller can guaranteed that the object will not be mutated, the original data object. """ def __init__(self, data): """ Args: data: A data object, such as a Pandas DataFrame, numPy array, or list. """ self._data = data def copy_to_avoid_mutation(self): """ Obtain a copy of the data. This method should be called every time the data needs to be used in a context where it may be subsequently mutated, guarding against accidental reuse after mutation. Returns: A copy of the data object. """ if isinstance(self._data, pd.DataFrame): return self._data.copy(deep=True) else: return copy.deepcopy(self._data) def get_original(self): """ Obtain the original data object. This method should only be called if the caller can guarantee that it will not mutate the data during subsequent operations. Returns: The original data object. """ return self._data
BuiltInEvaluator
python
pytorch__pytorch
torch/_dynamo/_trace_wrapped_higher_order_op.py
{ "start": 5070, "end": 6127 }
class ____(TorchFunctionMode): # This is needed since we want to support calling # A[q_idx], where q_idx is a scalar tensor in score_mod. # Today, when q_idx is a scalar tensor, we implicitly convert it to a python # scalar and create a view. We do not want that behavior in this case, so we # use this torchfunctionmode to override that behavior for score_mod # wherever we're running it. def __torch_function__( self, func: OpOverload, types: tuple[torch._C._TensorMeta, ...], args: tuple[object, ...] = (), kwargs: Optional[dict[str, object]] = None, ) -> object: if func is torch.Tensor.__getitem__: index_args = pytree.tree_leaves(args[1]) if all(isinstance(x, torch.Tensor) for x in index_args): return mod_index(args[0], index_args) return func(*args, **(kwargs or {})) def trace_wrapped(*args: Any, **kwargs: Any) -> Any: with torch.no_grad(): return _trace_wrapped_op(*args, **kwargs)
TransformGetItemToIndex
python
PyCQA__pylint
tests/functional/n/no/no_member_dataclasses.py
{ "start": 2029, "end": 2312 }
class ____: attr1: str attr2: str dict_prop = field(default_factory=dict) # No type annotation, not treated as field def some_func(self) -> None: for key, value in self.dict_prop.items(): # [no-member] print(key) print(value)
TestClass3
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-firestore/destination_firestore/writer.py
{ "start": 193, "end": 1182 }
class ____: def __init__(self, project_id: str, credentials_json: Optional[str] = None): connection = {} connection["project"] = project_id if credentials_json: try: json_account_info = json.loads(credentials_json) except ValueError: raise ValueError("The 'credentials_json' field must contain a valid JSON document with service account access data.") credentials = service_account.Credentials.from_service_account_info(json_account_info) connection["credentials"] = credentials self.client = firestore.Client(**connection) def check(self) -> bool: return bool(list(self.client.collections())) def write(self, stream: str, data: Dict[str, Any]) -> None: self.client.collection(stream).add(data) def purge(self, stream: str) -> None: for doc in self.client.collection(stream).stream(): doc.reference.delete()
FirestoreWriter
python
ApeWorX__ape
src/ape/utils/abi.py
{ "start": 20761, "end": 21044 }
class ____(str, Enum): """ Control the display of calldata in Ape. """ abridged = "abridged" """ Show the first and last 4-bytes of the calldata, enough to see the method ID. """ full = "full" """ Show the full calldata. """
CalldataRepr
python
python-pillow__Pillow
src/PIL/ImageTransform.py
{ "start": 3184, "end": 3638 }
class ____(Transform): """ Define a quad image transform. Maps a quadrilateral (a region defined by four corners) from the image to a rectangle of the given size. See :py:meth:`.Image.transform` :param xy: An 8-tuple (x0, y0, x1, y1, x2, y2, x3, y3) which contain the upper left, lower left, lower right, and upper right corner of the source quadrilateral. """ method = Image.Transform.QUAD
QuadTransform
python
getsentry__sentry
src/sentry/analytics/events/relocation_organization_imported.py
{ "start": 89, "end": 289 }
class ____(analytics.Event): organization_id: int relocation_uuid: str owner_id: int slug: str analytics.register(RelocationOrganizationImportedEvent)
RelocationOrganizationImportedEvent
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 204740, "end": 207863 }
class ____(TestH5NetCDFData, FileObjectNetCDF): engine: T_NetcdfEngine = "h5netcdf" def test_open_badbytes(self) -> None: with pytest.raises( ValueError, match=r"match in any of xarray's currently installed IO" ): with open_dataset(b"garbage"): pass with pytest.raises( ValueError, match=r"not the signature of a valid netCDF4 file" ): with open_dataset(b"garbage", engine="h5netcdf"): pass with pytest.raises( ValueError, match=r"not the signature of a valid netCDF4 file" ): with open_dataset(BytesIO(b"garbage"), engine="h5netcdf"): pass def test_open_twice(self) -> None: expected = create_test_data() with create_tmp_file() as tmp_file: expected.to_netcdf(tmp_file, engine=self.engine) with open(tmp_file, "rb") as f: with open_dataset(f, engine=self.engine): with open_dataset(f, engine=self.engine): pass # should not crash @requires_scipy def test_open_fileobj(self) -> None: # open in-memory datasets instead of local file paths expected = create_test_data().drop_vars("dim3") expected.attrs["foo"] = "bar" with create_tmp_file() as tmp_file: expected.to_netcdf(tmp_file, engine="h5netcdf") with open(tmp_file, "rb") as f: with open_dataset(f, engine="h5netcdf") as actual: assert_identical(expected, actual) f.seek(0) with open_dataset(f) as actual: assert_identical(expected, actual) f.seek(0) with BytesIO(f.read()) as bio: with open_dataset(bio, engine="h5netcdf") as actual: assert_identical(expected, actual) f.seek(0) with pytest.raises(TypeError, match="not a valid NetCDF 3"): open_dataset(f, engine="scipy") # TODO: this additional open is required since scipy seems to close the file # when it fails on the TypeError (though didn't when we used # `raises_regex`?). Ref https://github.com/pydata/xarray/pull/5191 with open(tmp_file, "rb") as f: f.seek(8) with open_dataset(f): # ensure file gets closed pass @requires_fsspec def test_fsspec(self) -> None: expected = create_test_data() with create_tmp_file() as tmp_file: expected.to_netcdf(tmp_file, engine="h5netcdf") with fsspec.open(tmp_file, "rb") as f: with open_dataset(f, engine="h5netcdf") as actual: assert_identical(actual, expected) # fsspec.open() creates a pickleable file, unlike open() with pickle.loads(pickle.dumps(actual)) as unpickled: assert_identical(unpickled, expected) @requires_h5netcdf
TestH5NetCDFFileObject
python
sympy__sympy
sympy/functions/special/polynomials.py
{ "start": 39251, "end": 42597 }
class ____(OrthogonalPolynomial): r""" Returns the $n$th Laguerre polynomial in $x$, $L_n(x)$. Examples ======== >>> from sympy import laguerre, diff >>> from sympy.abc import x, n >>> laguerre(0, x) 1 >>> laguerre(1, x) 1 - x >>> laguerre(2, x) x**2/2 - 2*x + 1 >>> laguerre(3, x) -x**3/6 + 3*x**2/2 - 3*x + 1 >>> laguerre(n, x) laguerre(n, x) >>> diff(laguerre(n, x), x) -assoc_laguerre(n - 1, 1, x) Parameters ========== n : int Degree of Laguerre polynomial. Must be `n \ge 0`. See Also ======== jacobi, gegenbauer, chebyshevt, chebyshevt_root, chebyshevu, chebyshevu_root, legendre, assoc_legendre, hermite, hermite_prob, assoc_laguerre, sympy.polys.orthopolys.jacobi_poly sympy.polys.orthopolys.gegenbauer_poly sympy.polys.orthopolys.chebyshevt_poly sympy.polys.orthopolys.chebyshevu_poly sympy.polys.orthopolys.hermite_poly sympy.polys.orthopolys.hermite_prob_poly sympy.polys.orthopolys.legendre_poly sympy.polys.orthopolys.laguerre_poly References ========== .. [1] https://en.wikipedia.org/wiki/Laguerre_polynomial .. [2] https://mathworld.wolfram.com/LaguerrePolynomial.html .. [3] https://functions.wolfram.com/Polynomials/LaguerreL/ .. [4] https://functions.wolfram.com/Polynomials/LaguerreL3/ """ _ortho_poly = staticmethod(laguerre_poly) @classmethod def eval(cls, n, x): if n.is_integer is False: raise ValueError("Error: n should be an integer.") if not n.is_Number: # Symbolic result L_n(x) # L_{n}(-x) ---> exp(-x) * L_{-n-1}(x) # L_{-n}(x) ---> exp(x) * L_{n-1}(-x) if n.could_extract_minus_sign() and not(-n - 1).could_extract_minus_sign(): return exp(x)*laguerre(-n - 1, -x) # We can evaluate for some special values of x if x.is_zero: return S.One elif x is S.NegativeInfinity: return S.Infinity elif x is S.Infinity: return S.NegativeOne**n * S.Infinity else: if n.is_negative: return exp(x)*laguerre(-n - 1, -x) else: return cls._eval_at_order(n, x) def fdiff(self, argindex=2): if argindex == 1: # Diff wrt n raise ArgumentIndexError(self, argindex) elif argindex == 2: # Diff wrt x n, x = self.args return -assoc_laguerre(n - 1, 1, x) else: raise ArgumentIndexError(self, argindex) def _eval_rewrite_as_Sum(self, n, x, **kwargs): from sympy.concrete.summations import Sum # Make sure n \in N_0 if n.is_negative: return exp(x) * self._eval_rewrite_as_Sum(-n - 1, -x, **kwargs) if n.is_integer is False: raise ValueError("Error: n should be an integer.") k = Dummy("k") kern = RisingFactorial(-n, k) / factorial(k)**2 * x**k return Sum(kern, (k, 0, n)) def _eval_rewrite_as_polynomial(self, n, x, **kwargs): # This function is just kept for backwards compatibility # but should not be used return self._eval_rewrite_as_Sum(n, x, **kwargs)
laguerre
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 105004, "end": 107633 }
class ____(LogitsProcessor): """ This processor can be used to detect silence when using Whisper. It should take as input unprocessed logits to follow the original implementation """ def __init__(self, no_speech_token: int, begin_index: int, scores_is_logprobs: bool = False): self.no_speech_token = no_speech_token # offset between <start-of-transcription> token, <SOT>, in paper and first generated token # is equal to the position of the first generated token index self.start_of_trans_offset = begin_index # `self.begin_index` is a running value that is changed on the fly self.begin_index = begin_index self._no_speech_prob = [0.0] self.is_scores_logprobs = scores_is_logprobs # overwritten dynamically self.model = None self.inputs = None def set_model(self, model): self.model = model def set_inputs(self, inputs): # build `cache_position` on the fly seq_length = inputs["input_ids"].shape[1] inputs = self.model._get_initial_cache_position(seq_length, self.model.device, inputs) # prepare other inputs self.inputs = {**self.model.prepare_inputs_for_generation(**inputs), **inputs} self.inputs["input_features"] = self.inputs.pop("inputs") # Whisper encoder-decoder does not accept the input_ids as input if "input_ids" not in inspect.signature(self.model.forward).parameters: self.inputs.pop("input_ids", None) @property def no_speech_prob(self): return self._no_speech_prob def set_begin_index(self, begin_index): self.begin_index = begin_index @add_start_docstrings(LOGITS_PROCESSOR_INPUTS_DOCSTRING) def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor) -> torch.FloatTensor: is_scores_logprobs = self.is_scores_logprobs if input_ids.shape[1] == self.begin_index: if self.start_of_trans_offset > 1: with torch.no_grad(): logits = self.model(**self.inputs).logits no_speech_index = self.begin_index - self.start_of_trans_offset no_speech_scores = logits[:, no_speech_index] is_scores_logprobs = False else: no_speech_scores = scores if is_scores_logprobs: probs = no_speech_scores.exp() else: probs = no_speech_scores.float().softmax(dim=-1) self._no_speech_prob = probs[:, self.no_speech_token] return scores
WhisperNoSpeechDetection
python
Lightning-AI__lightning
tests/tests_pytorch/checkpointing/test_model_checkpoint.py
{ "start": 38150, "end": 38411 }
class ____(BoringModel): def optimizer_step(self, epoch, batch_idx, optimizer, optimizer_closure=None): optimizer.step(closure=optimizer_closure) if self.current_epoch == 1: raise RuntimeError("Trouble!")
TroubledModelOptimizerStep
python
huggingface__transformers
src/transformers/models/llava_onevision/image_processing_llava_onevision_fast.py
{ "start": 1886, "end": 13931 }
class ____(BaseImageProcessorFast): model_input_names = ["pixel_values", "image_sizes", "batch_num_images"] resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"height": 384, "width": 384} default_to_square = False crop_size = None do_resize = True do_center_crop = None do_rescale = True do_normalize = True do_convert_rgb = True do_pad = True image_grid_pinpoints = [[384, 384], [384, 768], [384, 1152], [384, 1536], [384, 1920], [384, 2304], [768, 384], [768, 768], [768, 1152], [768, 1536], [768, 1920], [768, 2304], [1152, 384], [1152, 768], [1152, 1152], [1152, 1536], [1152, 1920], [1152, 2304], [1536, 384], [1536, 768], [1536, 1152], [1536, 1536], [1536, 1920], [1536, 2304], [1920, 384], [1920, 768], [1920, 1152], [1920, 1536], [1920, 1920], [1920, 2304], [2304, 384], [2304, 768], [2304, 1152], [2304, 1536], [2304, 1920], [2304, 2304]] # fmt: skip valid_kwargs = LlavaOnevisionImageProcessorKwargs def __init__(self, **kwargs: Unpack[LlavaOnevisionImageProcessorKwargs]): super().__init__(**kwargs) @auto_docstring def preprocess(self, images: ImageInput, **kwargs: Unpack[LlavaOnevisionImageProcessorKwargs]) -> BatchFeature: if isinstance(images, (tuple, list)) and isinstance(images[0], (tuple, list)): # if the first element is a list, we assume that all elements are lists batch_num_images = [len(x) for x in images] elif isinstance(images, (tuple, list)): # treat this as a single-image case for backward compatibility batch_num_images = [1] * len(images) else: batch_num_images = [1] return super().preprocess(images, batch_num_images, **kwargs) def _resize_for_patching( self, image: "torch.Tensor", target_resolution: tuple, interpolation: "F.InterpolationMode", input_data_format: ChannelDimension, ) -> "torch.Tensor": """ Resizes an image to a target resolution while maintaining aspect ratio. Args: image ("torch.Tensor"): The input image. target_resolution (tuple): The target resolution (height, width) of the image. interpolation (`InterpolationMode`): Resampling filter to use if resizing the image. input_data_format (`ChannelDimension` or `str`): The channel dimension format of the input image. Returns: "torch.Tensor": The resized and padded image. """ new_height, new_width = get_patch_output_size(image, target_resolution, input_data_format) # Resize the image resized_image = self.resize( image=image, size=SizeDict(height=new_height, width=new_width), interpolation=interpolation, ) return resized_image def _get_padding_size(self, original_resolution: tuple, target_resolution: tuple): original_height, original_width = original_resolution target_height, target_width = target_resolution paste_x, r_x = divmod(target_width - original_width, 2) paste_y, r_y = divmod(target_height - original_height, 2) return [paste_x, paste_y, paste_x + r_x, paste_y + r_y] def _pad_for_patching( self, image: "torch.Tensor", target_resolution: tuple, input_data_format: ChannelDimension ) -> "torch.Tensor": """ Pad an image to a target resolution while maintaining aspect ratio. """ new_resolution = get_patch_output_size(image, target_resolution, input_data_format) padding = self._get_padding_size(new_resolution, target_resolution) padded_image = F.pad(image, padding=padding) return padded_image def _get_image_patches( self, image: "torch.Tensor", grid_pinpoints, size: tuple, patch_size: int, interpolation: "F.InterpolationMode", ) -> list["torch.Tensor"]: """ Process an image with variable resolutions by dividing it into patches. Args: image ("torch.Tensor"): The input image to be processed. grid_pinpoints (List): A string representation of a list of possible resolutions. size (`tuple`): Size to resize the original image to. patch_size (`int`): Size of the patches to divide the image into. interpolation (`"InterpolationMode"`): Resampling filter to use if resizing the image. Returns: list["torch.Tensor"]: A list of NumPy arrays containing the processed image patches. """ if not isinstance(grid_pinpoints, list): raise TypeError("grid_pinpoints must be a list of possible resolutions.") possible_resolutions = grid_pinpoints image_size = get_image_size(image, channel_dim=ChannelDimension.FIRST) best_resolution = select_best_resolution(image_size, possible_resolutions) resized_image = self._resize_for_patching( image, best_resolution, interpolation=interpolation, input_data_format=ChannelDimension.FIRST ) padded_image = self._pad_for_patching(resized_image, best_resolution, input_data_format=ChannelDimension.FIRST) patches = divide_to_patches(padded_image, patch_size=patch_size) resized_original_image = F.resize(image, size=size, interpolation=interpolation) image_patches = [resized_original_image] + patches return image_patches def _pad_for_batching( self, pixel_values: list["torch.Tensor"], ) -> list["torch.Tensor"]: """ Pads images on the `num_of_patches` dimension with zeros to form a batch of same number of patches. Args: pixel_values (`list[torch.Tensor]`): An array of pixel values of each images of shape (`batch_size`, `num_patches`, `image_in_3D`) Returns: list[`torch.Tensor`]: The padded images. """ max_patch = max(len(x) for x in pixel_values) pixel_values = [ torch.nn.functional.pad(image, pad=[0, 0, 0, 0, 0, 0, 0, max_patch - image.shape[0]]) for image in pixel_values ] return pixel_values def _preprocess( self, images: list["torch.Tensor"], batch_num_images: list[int], do_resize: bool, size: SizeDict, image_grid_pinpoints: list[list[int]], interpolation: Optional["F.InterpolationMode"], do_center_crop: bool, crop_size: SizeDict, do_rescale: bool, rescale_factor: float, do_normalize: bool, image_mean: Optional[Union[float, list[float]]], image_std: Optional[Union[float, list[float]]], do_pad: bool, disable_grouping: Optional[bool], return_tensors: Optional[Union[str, TensorType]], **kwargs, ) -> BatchFeature: processed_images = [] image_sizes = [] # only single image patching is supported need_patching = [n == 1 for n in batch_num_images for _ in range(n)] # Determine the size tuple if size and size.height and size.width: size_tuple = (size.height, size.width) else: size_tuple = (size.shortest_edge, size.shortest_edge) # Determine the patch size if crop_size and crop_size.height: patch_size = crop_size.height elif size and size.height: patch_size = size.height else: patch_size = size.shortest_edge for i, image in enumerate(images): if need_patching[i]: image_patches = self._get_image_patches( image, image_grid_pinpoints, size=size_tuple, patch_size=patch_size, interpolation=interpolation, ) else: padded_image = self.pad_to_square( images=image, background_color=tuple(int(x * 255) for x in self.image_mean) ) image_patches = [padded_image] # Group images by size for batched processing processed_image_patches_grouped = {} grouped_image_patches, grouped_image_patches_index = group_images_by_shape( image_patches, disable_grouping=disable_grouping ) for shape, stacked_image_patches in grouped_image_patches.items(): if do_resize: stacked_image_patches = self.resize( image=stacked_image_patches, size=size, interpolation=interpolation, ) if do_center_crop: stacked_image_patches = self.center_crop(stacked_image_patches, crop_size) # Fused rescale and normalize stacked_image_patches = self.rescale_and_normalize( stacked_image_patches, do_rescale, rescale_factor, do_normalize, image_mean, image_std ) processed_image_patches_grouped[shape] = stacked_image_patches processed_image_patches = reorder_images(processed_image_patches_grouped, grouped_image_patches_index) processed_image_patches = torch.stack(processed_image_patches, dim=0) processed_images.append(processed_image_patches) image_sizes.append(get_image_size(image, ChannelDimension.FIRST)) if do_pad: processed_images = self._pad_for_batching(processed_images) processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images return BatchFeature( data={"pixel_values": processed_images, "image_sizes": image_sizes, "batch_num_images": batch_num_images}, tensor_type=return_tensors, ) # Copied from transformers.models.llava.image_processing_llava_fast.LlavaImageProcessorFast.pad_to_square def pad_to_square( self, images: "torch.Tensor", background_color: Union[int, tuple[int, int, int]] = 0, ) -> "torch.Tensor": """ Pads an image to a square based on the longest edge. Args: images (`np.ndarray`): The images to pad. background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0): The color to use for the padding. Can be an integer for single channel or a tuple of integers representing for multi-channel images. If passed as integer in multi-channel mode, it will default to `0` in subsequent channels. Returns: `torch.Tensor`: The padded images. """ height, width = get_image_size(images, ChannelDimension.FIRST) if height == width: return images num_channels = images.shape[1] if len(images.shape) == 4 else images.shape[0] if isinstance(background_color, int): background_color = [background_color] + [0] * (num_channels - 1) elif len(background_color) != num_channels: raise ValueError( f"background_color must have no more than {num_channels} elements to match the number of channels" ) max_dim = max(height, width) paste_x_left = (max_dim - width) // 2 paste_y_left = (max_dim - height) // 2 paste_x_right = max_dim - width - paste_x_left paste_y_right = max_dim - height - paste_y_left padded_images = F.pad( images, padding=[paste_x_left, paste_y_left, paste_x_right, paste_y_right], fill=background_color ) return padded_images __all__ = ["LlavaOnevisionImageProcessorFast"]
LlavaOnevisionImageProcessorFast
python
conda__conda
conda/testing/solver_helpers.py
{ "start": 6080, "end": 47104 }
class ____: """Tests for :py:class:`conda.core.solve.Solver` implementations.""" @property def solver_class(self) -> type[Solver]: """Class under test.""" raise NotImplementedError @property def tests_to_skip(self): return {} # skip reason -> list of tests to skip @pytest.fixture(autouse=True) def skip_tests(self, request): for reason, skip_list in self.tests_to_skip.items(): if request.node.name in skip_list: pytest.skip(reason) @pytest.fixture() def env(self): with TemporaryDirectory(prefix="conda-test-repo-") as tmpdir: self.env = SimpleEnvironment(tmpdir, self.solver_class) yield self.env self.env = None def find_package_in_list(self, packages, **kwargs): for record in packages: if all(getattr(record, key) == value for key, value in kwargs.items()): return record def find_package(self, **kwargs): if isinstance(self.env.repo_packages, dict): if "channel" not in kwargs: raise ValueError( "Repo has multiple channels, the `channel` argument must be specified" ) packages = self.env.repo_packages[kwargs["channel"]] else: packages = self.env.repo_packages return self.find_package_in_list(packages, **kwargs) def assert_unsatisfiable(self, exc_info, entries): """Helper to assert that a :py:class:`conda.exceptions.UnsatisfiableError` instance as a the specified set of unsatisfiable specifications. """ assert issubclass(exc_info.type, UnsatisfiableError) if exc_info.type is UnsatisfiableError: assert ( sorted( tuple(map(str, entries)) for entries in exc_info.value.unsatisfiable ) == entries ) def test_empty(self, env): env.repo_packages = index_packages(1) assert env.install() == set() def test_iopro_mkl(self, env): env.repo_packages = index_packages(1) assert env.install("iopro 1.4*", "python 2.7*", "numpy 1.7*") == { "test::iopro-1.4.3-np17py27_p0", "test::numpy-1.7.1-py27_0", "test::openssl-1.0.1c-0", "test::python-2.7.5-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::unixodbc-2.3.1-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py27_1", "test::pip-1.3.1-py27_1", } def test_iopro_nomkl(self, env): env.repo_packages = index_packages(1) assert env.install( "iopro 1.4*", "python 2.7*", "numpy 1.7*", MatchSpec(track_features="mkl") ) == { "test::iopro-1.4.3-np17py27_p0", "test::mkl-rt-11.0-p0", "test::numpy-1.7.1-py27_p0", "test::openssl-1.0.1c-0", "test::python-2.7.5-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::unixodbc-2.3.1-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py27_1", "test::pip-1.3.1-py27_1", } def test_mkl(self, env): env.repo_packages = index_packages(1) assert env.install("mkl") == env.install( "mkl 11*", MatchSpec(track_features="mkl") ) def test_accelerate(self, env): env.repo_packages = index_packages(1) assert env.install("accelerate") == env.install( "accelerate", MatchSpec(track_features="mkl") ) def test_scipy_mkl(self, env): env.repo_packages = index_packages(1) records = env.install( "scipy", "python 2.7*", "numpy 1.7*", MatchSpec(track_features="mkl"), as_specs=True, ) for record in records: if record.name in ("numpy", "scipy"): assert "mkl" in record.features assert "test::numpy-1.7.1-py27_p0" in package_string_set(records) assert "test::scipy-0.12.0-np17py27_p0" in package_string_set(records) def test_anaconda_nomkl(self, env): env.repo_packages = index_packages(1) records = env.install("anaconda 1.5.0", "python 2.7*", "numpy 1.7*") assert len(records) == 107 assert "test::scipy-0.12.0-np17py27_0" in records def test_pseudo_boolean(self, env): env.repo_packages = index_packages(1) # The latest version of iopro, 1.5.0, was not built against numpy 1.5 assert env.install("iopro", "python 2.7*", "numpy 1.5*") == { "test::iopro-1.4.3-np15py27_p0", "test::numpy-1.5.1-py27_4", "test::openssl-1.0.1c-0", "test::python-2.7.5-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::unixodbc-2.3.1-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py27_1", "test::pip-1.3.1-py27_1", } assert env.install( "iopro", "python 2.7*", "numpy 1.5*", MatchSpec(track_features="mkl") ) == { "test::iopro-1.4.3-np15py27_p0", "test::mkl-rt-11.0-p0", "test::numpy-1.5.1-py27_p4", "test::openssl-1.0.1c-0", "test::python-2.7.5-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::unixodbc-2.3.1-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py27_1", "test::pip-1.3.1-py27_1", } def test_unsat_from_r1(self, env): env.repo_packages = index_packages(1) with pytest.raises(UnsatisfiableError) as exc_info: env.install("numpy 1.5*", "scipy 0.12.0b1") self.assert_unsatisfiable( exc_info, [ ("numpy=1.5",), ("scipy==0.12.0b1", "numpy[version='1.6.*|1.7.*']"), ], ) with pytest.raises(UnsatisfiableError) as exc_info: env.install("numpy 1.5*", "python 3*") self.assert_unsatisfiable( exc_info, [ ("numpy=1.5", "nose", "python=3.3"), ("numpy=1.5", "python[version='2.6.*|2.7.*']"), ("python=3",), ], ) with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)) as exc_info: env.install("numpy 1.5*", "numpy 1.6*") if exc_info.type is ResolvePackageNotFound: assert sorted(map(str, exc_info.value.bad_deps)) == [ "numpy[version='1.5.*,1.6.*']", ] def test_unsat_simple(self, env): env.repo_packages = [ helpers.record(name="a", depends=["c >=1,<2"]), helpers.record(name="b", depends=["c >=2,<3"]), helpers.record(name="c", version="1.0"), helpers.record(name="c", version="2.0"), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "b") self.assert_unsatisfiable( exc_info, [ ("a", "c[version='>=1,<2']"), ("b", "c[version='>=2,<3']"), ], ) def test_get_dists(self, env): env.repo_packages = index_packages(1) records = env.install("anaconda 1.4.0") assert "test::anaconda-1.4.0-np17py33_0" in records assert "test::freetype-2.4.10-0" in records def test_unsat_shortest_chain_1(self, env): env.repo_packages = [ helpers.record(name="a", depends=["d", "c <1.3.0"]), helpers.record(name="b", depends=["c"]), helpers.record( name="c", version="1.3.6", ), helpers.record( name="c", version="1.2.8", ), helpers.record(name="d", depends=["c >=0.8.0"]), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("c=1.3.6", "a", "b") self.assert_unsatisfiable( exc_info, [ ("a", "c[version='<1.3.0']"), ("a", "d", "c[version='>=0.8.0']"), ("b", "c"), ("c=1.3.6",), ], ) def test_unsat_shortest_chain_2(self, env): env.repo_packages = [ helpers.record(name="a", depends=["d", "c >=0.8.0"]), helpers.record(name="b", depends=["c"]), helpers.record( name="c", version="1.3.6", ), helpers.record( name="c", version="1.2.8", ), helpers.record(name="d", depends=["c <1.3.0"]), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("c=1.3.6", "a", "b") self.assert_unsatisfiable( exc_info, [ ("a", "c[version='>=0.8.0']"), ("a", "d", "c[version='<1.3.0']"), ("b", "c"), ("c=1.3.6",), ], ) def test_unsat_shortest_chain_3(self, env): env.repo_packages = [ helpers.record(name="a", depends=["f", "e"]), helpers.record(name="b", depends=["c"]), helpers.record( name="c", version="1.3.6", ), helpers.record( name="c", version="1.2.8", ), helpers.record(name="d", depends=["c >=0.8.0"]), helpers.record(name="e", depends=["c <1.3.0"]), helpers.record(name="f", depends=["d"]), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("c=1.3.6", "a", "b") self.assert_unsatisfiable( exc_info, [ ("a", "e", "c[version='<1.3.0']"), ("b", "c"), ("c=1.3.6",), ], ) def test_unsat_shortest_chain_4(self, env): env.repo_packages = [ helpers.record(name="a", depends=["py =3.7.1"]), helpers.record(name="py_req_1"), helpers.record(name="py_req_2"), helpers.record( name="py", version="3.7.1", depends=["py_req_1", "py_req_2"] ), helpers.record( name="py", version="3.6.1", depends=["py_req_1", "py_req_2"] ), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "py=3.6.1") self.assert_unsatisfiable( exc_info, [ ("a", "py=3.7.1"), ("py=3.6.1",), ], ) def test_unsat_chain(self, env): # a -> b -> c=1.x -> d=1.x # e -> c=2.x -> d=2.x env.repo_packages = [ helpers.record(name="a", depends=["b"]), helpers.record(name="b", depends=["c >=1,<2"]), helpers.record(name="c", version="1.0", depends=["d >=1,<2"]), helpers.record(name="d", version="1.0"), helpers.record(name="e", depends=["c >=2,<3"]), helpers.record(name="c", version="2.0", depends=["d >=2,<3"]), helpers.record(name="d", version="2.0"), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "e") self.assert_unsatisfiable( exc_info, [ ("a", "b", "c[version='>=1,<2']"), ("e", "c[version='>=2,<3']"), ], ) def test_unsat_any_two_not_three(self, env): # can install any two of a, b and c but not all three env.repo_packages = [ helpers.record(name="a", version="1.0", depends=["d >=1,<2"]), helpers.record(name="a", version="2.0", depends=["d >=2,<3"]), helpers.record(name="b", version="1.0", depends=["d >=1,<2"]), helpers.record(name="b", version="2.0", depends=["d >=3,<4"]), helpers.record(name="c", version="1.0", depends=["d >=2,<3"]), helpers.record(name="c", version="2.0", depends=["d >=3,<4"]), helpers.record(name="d", version="1.0"), helpers.record(name="d", version="2.0"), helpers.record(name="d", version="3.0"), ] # a and b can be installed installed = env.install("a", "b", as_specs=True) assert any(k.name == "a" and k.version == "1.0" for k in installed) assert any(k.name == "b" and k.version == "1.0" for k in installed) # a and c can be installed installed = env.install("a", "c", as_specs=True) assert any(k.name == "a" and k.version == "2.0" for k in installed) assert any(k.name == "c" and k.version == "1.0" for k in installed) # b and c can be installed installed = env.install("b", "c", as_specs=True) assert any(k.name == "b" and k.version == "2.0" for k in installed) assert any(k.name == "c" and k.version == "2.0" for k in installed) # a, b and c cannot be installed with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "b", "c") self.assert_unsatisfiable( exc_info, [ ("a", "d[version='>=1,<2|>=2,<3']"), ("b", "d[version='>=1,<2|>=3,<4']"), ("c", "d[version='>=2,<3|>=3,<4']"), ], ) def test_unsat_expand_single(self, env): env.repo_packages = [ helpers.record(name="a", depends=["b", "c"]), helpers.record(name="b", depends=["d >=1,<2"]), helpers.record(name="c", depends=["d >=2,<3"]), helpers.record(name="d", version="1.0"), helpers.record(name="d", version="2.0"), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("a") self.assert_unsatisfiable( exc_info, [ ("b", "d[version='>=1,<2']"), ("c", "d[version='>=2,<3']"), ], ) def test_unsat_missing_dep(self, env): env.repo_packages = [ helpers.record(name="a", depends=["b", "c"]), helpers.record(name="b", depends=["c >=2,<3"]), helpers.record(name="c", version="1.0"), ] with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "b") self.assert_unsatisfiable( exc_info, [ ("a", "b"), ("b",), ], ) def test_nonexistent(self, env): with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)): env.install("notarealpackage 2.0*") with pytest.raises((ResolvePackageNotFound, PackagesNotFoundError)): env.install("numpy 1.5") def test_timestamps_and_deps(self, env): env.repo_packages = index_packages(1) + [ helpers.record( name="mypackage", version="1.0", build="hash12_0", timestamp=1, depends=["libpng 1.2.*"], ), helpers.record( name="mypackage", version="1.0", build="hash15_0", timestamp=0, depends=["libpng 1.5.*"], ), ] # libpng 1.2 records_12 = env.install("libpng 1.2.*", "mypackage") assert "test::libpng-1.2.50-0" in records_12 assert "test::mypackage-1.0-hash12_0" in records_12 # libpng 1.5 records_15 = env.install("libpng 1.5.*", "mypackage") assert "test::libpng-1.5.13-1" in records_15 assert "test::mypackage-1.0-hash15_0" in records_15 # this is testing that previously installed reqs are not disrupted # by newer timestamps. regression test of sorts for # https://github.com/conda/conda/issues/6271 assert ( env.install("mypackage", *env.install("libpng 1.2.*", as_specs=True)) == records_12 ) assert ( env.install("mypackage", *env.install("libpng 1.5.*", as_specs=True)) == records_15 ) # unspecified python version should maximize libpng (v1.5), # even though it has a lower timestamp assert env.install("mypackage") == records_15 def test_nonexistent_deps(self, env): env.repo_packages = index_packages(1) + [ helpers.record( name="mypackage", version="1.0", depends=["nose", "python 3.3*", "notarealpackage 2.0*"], ), helpers.record( name="mypackage", version="1.1", depends=["nose", "python 3.3*"], ), helpers.record( name="anotherpackage", version="1.0", depends=["nose", "mypackage 1.1"], ), helpers.record( name="anotherpackage", version="2.0", depends=["nose", "mypackage"], ), ] # XXX: missing find_matches and reduced_index assert env.install("mypackage") == { "test::mypackage-1.1-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } assert env.install("anotherpackage 1.0") == { "test::anotherpackage-1.0-0", "test::mypackage-1.1-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } assert env.install("anotherpackage") == { "test::anotherpackage-2.0-0", "test::mypackage-1.1-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } # Add 1s to make sure the new repodata.jsons have different mod times time.sleep(1) # This time, the latest version is messed up env.repo_packages = index_packages(1) + [ helpers.record( name="mypackage", version="1.0", depends=["nose", "python 3.3*"], ), helpers.record( name="mypackage", version="1.1", depends=["nose", "python 3.3*", "notarealpackage 2.0*"], ), helpers.record( name="anotherpackage", version="1.0", depends=["nose", "mypackage 1.0"], ), helpers.record( name="anotherpackage", version="2.0", depends=["nose", "mypackage"], ), ] # XXX: missing find_matches and reduced_index assert env.install("mypackage") == { "test::mypackage-1.0-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } # TODO: We need UnsatisfiableError here because mamba does not # have more granular exceptions yet. with pytest.raises((ResolvePackageNotFound, UnsatisfiableError)): env.install("mypackage 1.1") assert env.install("anotherpackage 1.0") == { "test::anotherpackage-1.0-0", "test::mypackage-1.0-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } # If recursive checking is working correctly, this will give # anotherpackage 2.0, not anotherpackage 1.0 assert env.install("anotherpackage") == { "test::anotherpackage-2.0-0", "test::mypackage-1.0-0", "test::nose-1.3.0-py33_0", "test::openssl-1.0.1c-0", "test::python-3.3.2-0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", "test::distribute-0.6.36-py33_1", "test::pip-1.3.1-py33_1", } def test_install_package_with_feature(self, env): env.repo_packages = index_packages(1) + [ helpers.record( name="mypackage", version="1.0", depends=["python 3.3*"], features="feature", ), helpers.record( name="feature", version="1.0", depends=["python 3.3*"], track_features="feature", ), ] # should not raise env.install("mypackage", "feature 1.0") def test_unintentional_feature_downgrade(self, env): # See https://github.com/conda/conda/issues/6765 # With the bug in place, this bad build of scipy # will be selected for install instead of a later # build of scipy 0.11.0. good_rec_match = MatchSpec("channel-1::scipy==0.11.0=np17py33_3") good_rec = next( prec for prec in index_packages(1) if good_rec_match.match(prec) ) bad_deps = tuple(d for d in good_rec.depends if not d.startswith("numpy")) bad_rec = PackageRecord.from_objects( good_rec, channel="test", build=good_rec.build.replace("_3", "_x0"), build_number=0, depends=bad_deps, fn=good_rec.fn.replace("_3", "_x0"), url=good_rec.url.replace("_3", "_x0"), ) env.repo_packages = index_packages(1) + [bad_rec] records = env.install("scipy 0.11.0") assert "test::scipy-0.11.0-np17py33_x0" not in records assert "test::scipy-0.11.0-np17py33_3" in records def test_circular_dependencies(self, env): env.repo_packages = index_packages(1) + [ helpers.record( name="package1", depends=["package2"], ), helpers.record( name="package2", depends=["package1"], ), ] assert ( env.install("package1", "package2") == env.install("package1") == env.install("package2") ) def test_irrational_version(self, env): env.repo_packages = index_packages(1) assert env.install("pytz 2012d", "python 3*") == { "test::distribute-0.6.36-py33_1", "test::openssl-1.0.1c-0", "test::pip-1.3.1-py33_1", "test::python-3.3.2-0", "test::pytz-2012d-py33_0", "test::readline-6.2-0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } def test_no_features(self, env): env.repo_packages = index_packages(1) assert env.install("python 2.6*", "numpy 1.6*", "scipy 0.11*") == { "test::distribute-0.6.36-py26_1", "test::numpy-1.6.2-py26_4", "test::openssl-1.0.1c-0", "test::pip-1.3.1-py26_1", "test::python-2.6.8-6", "test::readline-6.2-0", "test::scipy-0.11.0-np16py26_3", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } assert env.install( "python 2.6*", "numpy 1.6*", "scipy 0.11*", MatchSpec(track_features="mkl") ) == { "test::distribute-0.6.36-py26_1", "test::mkl-rt-11.0-p0", "test::numpy-1.6.2-py26_p4", "test::openssl-1.0.1c-0", "test::pip-1.3.1-py26_1", "test::python-2.6.8-6", "test::readline-6.2-0", "test::scipy-0.11.0-np16py26_p3", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } env.repo_packages += [ helpers.record( name="pandas", version="0.12.0", build="np16py27_0", depends=[ "dateutil", "numpy 1.6*", "python 2.7*", "pytz", ], ), helpers.record( name="numpy", version="1.6.2", build="py27_p5", build_number=0, depends=[ "mkl-rt 11.0", "python 2.7", ], features="mkl", ), ] assert env.install("pandas 0.12.0 np16py27_0", "python 2.7*") == { "test::dateutil-2.1-py27_1", "test::distribute-0.6.36-py27_1", "test::numpy-1.6.2-py27_4", "test::openssl-1.0.1c-0", "test::pandas-0.12.0-np16py27_0", "test::pip-1.3.1-py27_1", "test::python-2.7.5-0", "test::pytz-2013b-py27_0", "test::readline-6.2-0", "test::six-1.3.0-py27_0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } assert env.install( "pandas 0.12.0 np16py27_0", "python 2.7*", MatchSpec(track_features="mkl") ) == { "test::dateutil-2.1-py27_1", "test::distribute-0.6.36-py27_1", "test::mkl-rt-11.0-p0", "test::numpy-1.6.2-py27_p4", "test::openssl-1.0.1c-0", "test::pandas-0.12.0-np16py27_0", "test::pip-1.3.1-py27_1", "test::python-2.7.5-0", "test::pytz-2013b-py27_0", "test::readline-6.2-0", "test::six-1.3.0-py27_0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } @pytest.mark.xfail(reason="CONDA_CHANNEL_PRIORITY does not seem to have any effect") def test_channel_priority_1(self, monkeypatch, env): # XXX: Test is skipped because CONDA_CHANNEL_PRIORITY does not seems to # have any effect. I have also tried conda.common.io.env_var like # the other tests but no luck. env.repo_packages = {} env.repo_packages["channel-A"] = [] env.repo_packages["channel-1"] = index_packages(1) pandas_0 = self.find_package( channel="channel-1", name="pandas", version="0.10.1", build="np17py27_0", ) env.repo_packages["channel-A"].append(pandas_0) # channel-1 has pandas np17py27_1, channel-A only has np17py27_0 # when priority is set, it channel-A should take precedence and # np17py27_0 be installed, otherwise np17py27_1 should be installed as # it has a higher build version monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") assert "channel-A::pandas-0.11.0-np16py27_0" in env.install( "pandas", "python 2.7*", "numpy 1.6*" ) monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "False") assert "channel-1::pandas-0.11.0-np16py27_1" in env.install( "pandas", "python 2.7*", "numpy 1.6*" ) # now lets revert the channels env.repo_packages = dict(reversed(env.repo_packages.items())) monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") assert "channel-1::pandas-0.11.0-np16py27_1" in env.install( "pandas", "python 2.7*", "numpy 1.6*" ) @pytest.mark.xfail(reason="CONDA_CHANNEL_PRIORITY does not seem to have any effect") def test_unsat_channel_priority(self, monkeypatch, env): # XXX: Test is skipped because CONDA_CHANNEL_PRIORITY does not seems to # have any effect. I have also tried conda.common.io.env_var like # the other tests but no luck. env.repo_packages = {} # higher priority env.repo_packages["channel-1"] = [ helpers.record( name="a", version="1.0", depends=["c"], ), helpers.record( name="b", version="1.0", depends=["c >=2,<3"], ), helpers.record( name="c", version="1.0", ), ] # lower priority, missing c 2.0 env.repo_packages["channel-2"] = [ helpers.record( name="a", version="2.0", depends=["c"], ), helpers.record( name="b", version="2.0", depends=["c >=2,<3"], ), helpers.record( name="c", version="1.0", ), helpers.record( name="c", version="2.0", ), ] monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") records = env.install("a", "b", as_specs=True) # channel-1 a and b packages (1.0) installed assert any(k.name == "a" and k.version == "1.0" for k in records) assert any(k.name == "b" and k.version == "1.0" for k in records) monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "False") records = env.install("a", "b", as_specs=True) # no channel priority, largest version of a and b (2.0) installed assert any(k.name == "a" and k.version == "2.0" for k in records) assert any(k.name == "b" and k.version == "2.0" for k in records) monkeypatch.setenv("CONDA_CHANNEL_PRIORITY", "True") with pytest.raises(UnsatisfiableError) as exc_info: env.install("a", "b") self.assert_unsatisfiable(exc_info, [("b", "c[version='>=2,<3']")]) @pytest.mark.xfail( reason="There is some weird global state making " "this test fail when the whole test suite is run" ) def test_remove(self, env): env.repo_packages = index_packages(1) records = env.install("pandas", "python 2.7*", as_specs=True) assert package_string_set(records) == { "test::dateutil-2.1-py27_1", "test::distribute-0.6.36-py27_1", "test::numpy-1.7.1-py27_0", "test::openssl-1.0.1c-0", "test::pandas-0.11.0-np17py27_1", "test::pip-1.3.1-py27_1", "test::python-2.7.5-0", "test::pytz-2013b-py27_0", "test::readline-6.2-0", "test::scipy-0.12.0-np17py27_0", "test::six-1.3.0-py27_0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } env.installed_packages = records assert env.remove("pandas") == { "test::dateutil-2.1-py27_1", "test::distribute-0.6.36-py27_1", "test::numpy-1.7.1-py27_0", "test::openssl-1.0.1c-0", "test::pip-1.3.1-py27_1", "test::python-2.7.5-0", "test::pytz-2013b-py27_0", "test::readline-6.2-0", "test::scipy-0.12.0-np17py27_0", "test::six-1.3.0-py27_0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } assert env.remove("numpy") == { "test::dateutil-2.1-py27_1", "test::distribute-0.6.36-py27_1", "test::openssl-1.0.1c-0", "test::pip-1.3.1-py27_1", "test::python-2.7.5-0", "test::pytz-2013b-py27_0", "test::readline-6.2-0", "test::six-1.3.0-py27_0", "test::sqlite-3.7.13-0", "test::system-5.8-1", "test::tk-8.5.13-0", "test::zlib-1.2.7-0", } def test_surplus_features_1(self, env): env.repo_packages += [ helpers.record( name="feature", track_features="feature", ), helpers.record( name="package1", features="feature", ), helpers.record( name="package2", version="1.0", features="feature", depends=["package1"], ), helpers.record( name="package2", version="2.0", features="feature", ), ] assert env.install("package2", "feature") == { "test::package2-2.0-0", "test::feature-1.0-0", } def test_surplus_features_2(self, env): env.repo_packages += [ helpers.record( name="feature", track_features="feature", ), helpers.record( name="package1", features="feature", ), helpers.record( name="package2", version="1.0", build_number=0, features="feature", depends=["package1"], ), helpers.record( name="package2", version="1.0", build_number=1, features="feature", ), ] assert env.install("package2", "feature") == { "test::package2-1.0-0", "test::feature-1.0-0", } def test_get_reduced_index_broadening_with_unsatisfiable_early_dep(self, env): # Test that spec broadening reduction doesn't kill valid solutions # In other words, the order of packages in the index should not affect the # overall result of the reduced index. # see discussion at https://github.com/conda/conda/pull/8117#discussion_r249249815 env.repo_packages += [ helpers.record( name="a", version="1.0", # not satisfiable. This record should come first, so that its c==2 # constraint tries to mess up the inclusion of the c record below, # which should be included as part of b's deps, but which is # broader than this dep. depends=["b", "c==2"], ), helpers.record( name="a", version="2.0", depends=["b"], ), helpers.record( name="b", depends=["c"], ), helpers.record( name="c", ), ] assert env.install("a") == { "test::a-2.0-0", "test::b-1.0-0", "test::c-1.0-0", } def test_get_reduced_index_broadening_preferred_solution(self, env): # test that order of index reduction does not eliminate what should be a preferred solution # https://github.com/conda/conda/pull/8117#discussion_r249216068 env.repo_packages += [ helpers.record( name="top", version="1.0", # this is the first processed record, and imposes a broadening constraint on bottom # if things are overly restricted, we'll end up with bottom 1.5 in our solution # instead of the preferred (latest) 2.5 depends=["middle", "bottom==1.5"], ), helpers.record( name="top", version="2.0", depends=["middle"], ), helpers.record( name="middle", depends=["bottom"], ), helpers.record( name="bottom", version="1.5", ), helpers.record( name="bottom", version="2.5", ), ] for record in env.install("top", as_specs=True): if record.name == "top": assert record.version == "2.0", ( f"top version should be 2.0, but is {record.version}" ) elif record.name == "bottom": assert record.version == "2.5", ( f"bottom version should be 2.5, but is {record.version}" ) def test_arch_preferred_over_noarch_when_otherwise_equal(self, env): env.repo_packages += [ helpers.record( name="package1", subdir="noarch", ), helpers.record( name="package1", ), ] records = env.install("package1", as_specs=True) assert len(records) == 1 assert records[0].subdir == context.subdir def test_noarch_preferred_over_arch_when_version_greater(self, env): env.repo_packages += [ helpers.record( name="package1", version="2.0", subdir="noarch", ), helpers.record( name="package1", version="1.0", ), ] records = env.install("package1", as_specs=True) assert len(records) == 1 assert records[0].subdir == "noarch" def test_noarch_preferred_over_arch_when_version_greater_dep(self, env): env.repo_packages += [ helpers.record( name="package1", version="1.0", ), helpers.record( name="package1", version="2.0", subdir="noarch", ), helpers.record( name="package2", depends=["package1"], ), ] records = env.install("package2", as_specs=True) package1 = self.find_package_in_list(records, name="package1") assert package1.subdir == "noarch" def test_noarch_preferred_over_arch_when_build_greater(self, env): env.repo_packages += [ helpers.record( name="package1", build_number=0, ), helpers.record( name="package1", build_number=1, subdir="noarch", ), ] records = env.install("package1", as_specs=True) assert len(records) == 1 assert records[0].subdir == "noarch" def test_noarch_preferred_over_arch_when_build_greater_dep(self, env): env.repo_packages += [ helpers.record( name="package1", build_number=0, ), helpers.record( name="package1", build_number=1, subdir="noarch", ), helpers.record( name="package2", depends=["package1"], ), ] records = env.install("package2", as_specs=True) package1 = self.find_package_in_list(records, name="package1") assert package1.subdir == "noarch"
SolverTests
python
python-openxml__python-docx
src/docx/section.py
{ "start": 10254, "end": 14443 }
class ____(BlockItemContainer): """Base class for header and footer classes.""" def __init__( self, sectPr: CT_SectPr, document_part: DocumentPart, header_footer_index: WD_HEADER_FOOTER, ): self._sectPr = sectPr self._document_part = document_part self._hdrftr_index = header_footer_index @property def is_linked_to_previous(self) -> bool: """``True`` if this header/footer uses the definition from the prior section. ``False`` if this header/footer has an explicit definition. Assigning ``True`` to this property removes the header/footer definition for this section, causing it to "inherit" the corresponding definition of the prior section. Assigning ``False`` causes a new, empty definition to be added for this section, but only if no definition is already present. """ # ---absence of a header/footer part indicates "linked" behavior--- return not self._has_definition @is_linked_to_previous.setter def is_linked_to_previous(self, value: bool) -> None: new_state = bool(value) # ---do nothing when value is not being changed--- if new_state == self.is_linked_to_previous: return if new_state is True: self._drop_definition() else: self._add_definition() @property def part(self) -> HeaderPart | FooterPart: """The |HeaderPart| or |FooterPart| for this header/footer. This overrides `BlockItemContainer.part` and is required to support image insertion and perhaps other content like hyperlinks. """ # ---should not appear in documentation; # ---not an interface property, even though public return self._get_or_add_definition() def _add_definition(self) -> HeaderPart | FooterPart: """Return newly-added header/footer part.""" raise NotImplementedError("must be implemented by each subclass") @property def _definition(self) -> HeaderPart | FooterPart: """|HeaderPart| or |FooterPart| object containing header/footer content.""" raise NotImplementedError("must be implemented by each subclass") def _drop_definition(self) -> None: """Remove header/footer part containing the definition of this header/footer.""" raise NotImplementedError("must be implemented by each subclass") @property def _element(self): """`w:hdr` or `w:ftr` element, root of header/footer part.""" return self._get_or_add_definition().element def _get_or_add_definition(self) -> HeaderPart | FooterPart: """Return HeaderPart or FooterPart object for this section. If this header/footer inherits its content, the part for the prior header/footer is returned; this process continue recursively until a definition is found. If the definition cannot be inherited (because the header/footer belongs to the first section), a new definition is added for that first section and then returned. """ # ---note this method is called recursively to access inherited definitions--- # ---case-1: definition is not inherited--- if self._has_definition: return self._definition # ---case-2: definition is inherited and belongs to second-or-later section--- prior_headerfooter = self._prior_headerfooter if prior_headerfooter: return prior_headerfooter._get_or_add_definition() # ---case-3: definition is inherited, but belongs to first section--- return self._add_definition() @property def _has_definition(self) -> bool: """True if this header/footer has a related part containing its definition.""" raise NotImplementedError("must be implemented by each subclass") @property def _prior_headerfooter(self) -> _Header | _Footer | None: """|_Header| or |_Footer| proxy on prior sectPr element. Returns None if this is first section. """ raise NotImplementedError("must be implemented by each subclass")
_BaseHeaderFooter
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py
{ "start": 19782, "end": 26280 }
class ____(Sam2VideoModel): _checkpoint_conversion_mapping = { r"tracker_model.(.+)": r"\1", # the regex allows to remove the prefix, and add it back in revert mode "detector_model.vision_encoder.backbone.": "vision_encoder.backbone.", "tracker_neck.": "vision_encoder.neck.", } _keys_to_ignore_on_load_unexpected = [r"^detector_model."] _tied_weights_keys = {} _keys_to_ignore_on_load_missing = [] def __init__(self, config: Sam3TrackerVideoConfig, remove_vision_encoder: bool = False): r""" remove_vision_encoder (`bool`, *optional*, defaults to `False`): Whether to remove the vision encoder. If True, the vision encoder will be set to None. """ # loading from a sam3_video config if hasattr(config, "tracker_config") and config.tracker_config is not None: tracker_config = config.tracker_config if isinstance(tracker_config, dict): tracker_config = Sam3TrackerVideoConfig(**tracker_config) config = tracker_config Sam3TrackerVideoPreTrainedModel.__init__(config) self.shared_image_embedding = Sam3TrackerVideoPositionalEmbedding(config.prompt_encoder_config) self.vision_encoder = AutoModel.from_config(config.vision_config) if not remove_vision_encoder else None self.prompt_encoder = Sam3TrackerVideoPromptEncoder(config.prompt_encoder_config) # The module using it is not a PreTrainedModel subclass so we need this config.mask_decoder_config._attn_implementation = config._attn_implementation self.mask_decoder = Sam3TrackerVideoMaskDecoder(config.mask_decoder_config) self.backbone_feature_sizes = config.vision_config.backbone_feature_sizes # a single token to indicate no memory embedding from previous frames self.hidden_dim = config.vision_config.fpn_hidden_size self.no_memory_embedding = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) self.config = config # For video sequence inference self.image_size = config.image_size self.memory_attention = Sam3TrackerVideoMemoryAttention(config) self.memory_encoder = Sam3TrackerVideoMemoryEncoder(config) self.no_memory_positional_encoding = torch.nn.Parameter( torch.zeros(1, 1, config.vision_config.fpn_hidden_size) ) self.mem_dim = config.memory_encoder_output_channels self.num_maskmem = config.num_maskmem # Number of memories accessible # Temporal encoding of the memories self.memory_temporal_positional_encoding = torch.nn.Parameter( torch.zeros(self.num_maskmem, 1, 1, self.mem_dim) ) self.no_object_pointer = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) # A conv layer to downsample the mask prompt to stride 4 (the same stride as # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, # so that it can be fed into the SAM mask decoder to generate a pointer. self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) # a feedforward layer on SAM output tokens to turn them into object pointers self.object_pointer_proj = Sam3TrackerVideoFeedForward(self.hidden_dim, self.hidden_dim, self.hidden_dim, 3) if self.config.enable_temporal_pos_encoding_for_object_pointers: # a linear projection on temporal positional encoding in object pointers to # avoid potential interference with spatial positional encoding self.temporal_positional_encoding_projection_layer = torch.nn.Linear(self.hidden_dim, self.mem_dim) else: self.temporal_positional_encoding_projection_layer = torch.nn.Identity() self.occlusion_spatial_embedding_parameter = None # compatibility with Sam2 if config.enable_occlusion_spatial_embedding: self.occlusion_spatial_embedding_parameter = torch.nn.Parameter(torch.zeros(1, self.mem_dim)) self.post_init() def get_image_features( self, pixel_values: torch.FloatTensor, **kwargs: Unpack[TransformersKwargs], ) -> tuple[ list[torch.Tensor], list[torch.Tensor], Optional[tuple[torch.FloatTensor, ...]], Optional[tuple[torch.FloatTensor, ...]], ]: r""" Extract and preprocess image features using the vision encoder. Args: pixel_values (`torch.FloatTensor`): Input pixel values of shape `(batch_size, num_channels, height, width)`. Returns: `tuple`: A tuple containing: - feature_maps (`list[torch.Tensor]`): List of feature maps from different levels. - feature_maps_position_embeddings (`list[torch.Tensor]`): List of positional embeddings for each feature level. - vision_hidden_states (`tuple[torch.FloatTensor]`, *optional*): Hidden states from the vision encoder. - vision_attentions (`tuple[torch.FloatTensor]`, *optional*): Attention weights from the vision encoder. """ vision_outputs: Sam3TrackerVideoVisionEncoderOutput = self.vision_encoder( pixel_values, **kwargs, ) feature_maps = vision_outputs.fpn_hidden_states feature_maps_position_embeddings = vision_outputs.fpn_position_encoding # precompute projected level 0 and level 1 features in SAM decoder # to avoid running it again on every SAM click feature_maps = list(feature_maps[:-1]) feature_maps[0] = self.mask_decoder.conv_s0(feature_maps[0]) feature_maps[1] = self.mask_decoder.conv_s1(feature_maps[1]) # flatten NxCxHxW to HWxNxC feature_maps = [feature_map.flatten(2).permute(2, 0, 1) for feature_map in feature_maps] feature_maps_position_embeddings = [ feature_map_position_embedding.flatten(2).permute(2, 0, 1) for feature_map_position_embedding in feature_maps_position_embeddings[:-1] ] return feature_maps, feature_maps_position_embeddings, vision_outputs.hidden_states, vision_outputs.attentions __all__ = [ "Sam3TrackerVideoMaskDecoderConfig", "Sam3TrackerVideoPromptEncoderConfig", "Sam3TrackerVideoConfig", "Sam3TrackerVideoModel", "Sam3TrackerVideoInferenceSession", "Sam3TrackerVideoPreTrainedModel", "Sam3TrackerVideoProcessor", ]
Sam3TrackerVideoModel
python
doocs__leetcode
solution/3100-3199/3153.Sum of Digit Differences of All Pairs/Solution.py
{ "start": 0, "end": 398 }
class ____: def sumDigitDifferences(self, nums: List[int]) -> int: n = len(nums) m = int(log10(nums[0])) + 1 ans = 0 for _ in range(m): cnt = Counter() for i, x in enumerate(nums): nums[i], y = divmod(x, 10) cnt[y] += 1 ans += sum(v * (n - v) for v in cnt.values()) // 2 return ans
Solution
python
readthedocs__readthedocs.org
readthedocs/api/v3/routers.py
{ "start": 162, "end": 590 }
class ____(APIRootView): # Overridden only to add documentation for BrowsableAPIRenderer. # noqa """ Each request requires an `Authorization` HTTP header with `Token <your-token>`, find the token in [your account](/accounts/tokens/). Read the full documentation at <https://docs.readthedocs.io/page/api/v3.html>. """ def get_view_name(self): return "Read the Docs API v3"
DocsAPIRootView
python
falconry__falcon
tests/test_httperror.py
{ "start": 5365, "end": 5563 }
class ____: def on_get(self, req, resp): raise falcon.HTTPContentTooLarge( title='Request Rejected', description='Request Body Too Large' )
RequestEntityTooLongResource
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox34.py
{ "start": 315, "end": 863 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox34.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_textbox("E9", "This is some text", {"text_rotation": 90}) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
mlflow__mlflow
mlflow/server/graphql/graphql_errors.py
{ "start": 221, "end": 432 }
class ____(graphene.ObjectType): code = graphene.String() message = graphene.String() help_url = graphene.String() trace_id = graphene.String() error_details = graphene.List(ErrorDetail)
ApiError
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/_stubs.py
{ "start": 378, "end": 471 }
class ____(dj_template.context.RenderContext): template: dj_template.Template
RenderContext
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_S.py
{ "start": 15918, "end": 17166 }
class ____(Benchmark): r""" Schwefel 22 objective function. This class defines the Schwefel 22 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Schwefel22}}(x) = \sum_{i=1}^n \lvert x_i \rvert + \prod_{i=1}^n \lvert x_i \rvert Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-100, 100]` for :math:`i = 1, ..., n`. *Global optimum*: :math:`f(x) = 0` for :math:`x_i = 0` for :math:`i = 1, ..., n` .. [1] Jamil, M. & Yang, X.-S. A Literature Survey of Benchmark Functions For Global Optimization Problems Int. Journal of Mathematical Modelling and Numerical Optimisation, 2013, 4, 150-194. """ change_dimensionality = True def __init__(self, dimensions=2): Benchmark.__init__(self, dimensions) self._bounds = list(zip([-100.0] * self.N, [100.0] * self.N)) self.custom_bounds = ([-10.0, 10.0], [-10.0, 10.0]) self.global_optimum = [[0.0 for _ in range(self.N)]] self.fglob = 0.0 def fun(self, x, *args): self.nfev += 1 return sum(abs(x)) + prod(abs(x))
Schwefel22
python
keras-team__keras
keras/src/models/sequential_test.py
{ "start": 404, "end": 12649 }
class ____(testing.TestCase): def test_basic_flow_with_input(self): model = Sequential(name="seq") model.add(Input(shape=(2,), batch_size=3)) model.add(layers.Dense(4)) model.add(layers.Dense(5)) model.summary() self.assertEqual(len(model.layers), 2) self.assertTrue(model.built) self.assertEqual(len(model.weights), 4) # Test eager call x = np.random.random((3, 2)) y = model(x) self.assertEqual(type(model._functional), Functional) self.assertEqual(y.shape, (3, 5)) # Test symbolic call x = backend.KerasTensor((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 5)) # Test `layers` constructor arg model = Sequential( layers=[ Input(shape=(2,), batch_size=3), layers.Dense(4), layers.Dense(5), ] ) self.assertEqual(len(model.layers), 2) self.assertTrue(model.built) self.assertEqual(len(model.weights), 4) x = np.random.random((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 5)) # Test pop model.pop() self.assertEqual(len(model.layers), 1) self.assertTrue(model.built) self.assertEqual(len(model.weights), 2) x = np.random.random((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 4)) def test_legacy_flow_with_input_shape(self): model = Sequential(name="seq") model.add(layers.Dense(4, input_shape=(2,))) model.add(layers.Dense(5)) self.assertEqual(len(model.layers), 2) self.assertTrue(model.built) self.assertEqual(len(model.weights), 4) self.assertEqual(type(model._functional), Functional) # Input_dim works too model = Sequential(name="seq") model.add(layers.Dense(4, input_dim=2)) model.add(layers.Dense(5)) self.assertEqual(len(model.layers), 2) self.assertTrue(model.built) self.assertEqual(len(model.weights), 4) self.assertEqual(type(model._functional), Functional) # Subsequent input_shapes are ignored model = Sequential(name="seq") model.add(layers.Dense(4, input_shape=(2,))) model.add(layers.Dense(5, input_shape=(3, 4))) self.assertEqual(len(model.layers), 2) self.assertTrue(model.built) self.assertEqual(len(model.weights), 4) self.assertEqual(type(model._functional), Functional) def test_basic_flow_deferred(self): model = Sequential(name="seq") model.add(layers.Dense(4)) model.add(layers.Dense(5)) model.summary() self.assertEqual(len(model.layers), 2) # Test eager call x = np.random.random((3, 2)) y = model(x) self.assertTrue(model.built) model.summary() self.assertEqual(type(model._functional), Functional) self.assertEqual(y.shape, (3, 5)) # Test symbolic call x = backend.KerasTensor((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 5)) # Test `layers` constructor arg model = Sequential( layers=[ layers.Dense(4), layers.Dense(5), ] ) x = np.random.random((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 5)) # Test pop model.pop() self.assertEqual(len(model.layers), 1) self.assertTrue(model.built) self.assertEqual(len(model.weights), 2) x = np.random.random((3, 2)) y = model(x) self.assertEqual(y.shape, (3, 4)) def test_basic_flow_as_a_submodel(self): # Build submodel submodel = Sequential() submodel.add(layers.Flatten()) self.assertFalse(submodel.built) inputs = Input((None, 4)) outputs = layers.TimeDistributed(submodel)(inputs) model = Model(inputs=inputs, outputs=outputs) x = np.random.random((2, 3, 4)) y = model(x) self.assertEqual(y.shape, (2, 3, 4)) def test_basic_flow_with_functional_model_as_first_layer(self): # Build functional model inputs = Input((16, 16, 3)) outputs = layers.Conv2D(4, 3, padding="same")(inputs) functional_model = Model(inputs=inputs, outputs=outputs) model = Sequential( [functional_model, layers.Flatten(), layers.Dense(1)] ) model.summary() self.assertEqual(len(model.layers), 3) self.assertTrue(model.built) for layer in model.layers: self.assertTrue(layer.built) # Test eager call x = np.random.random((1, 16, 16, 3)) y = model(x) self.assertEqual(type(model._functional), Functional) self.assertEqual(tuple(y.shape), (1, 1)) # Test symbolic call x = backend.KerasTensor((1, 16, 16, 3)) y = model(x) self.assertEqual(y.shape, (1, 1)) def test_basic_flow_with_sequential_model_as_first_layer(self): # Build sequential model sequential_model = Sequential( [Input((16, 16, 3)), layers.Conv2D(4, 3, padding="same")] ) model = Sequential( [sequential_model, layers.Flatten(), layers.Dense(1)] ) model.summary() self.assertEqual(len(model.layers), 3) self.assertTrue(model.built) for layer in model.layers: self.assertTrue(layer.built) # Test eager call x = np.random.random((1, 16, 16, 3)) y = model(x) self.assertEqual(type(model._functional), Functional) self.assertEqual(tuple(y.shape), (1, 1)) # Test symbolic call x = backend.KerasTensor((1, 16, 16, 3)) y = model(x) self.assertEqual(y.shape, (1, 1)) def test_dict_inputs(self): class DictLayer(layers.Layer): def call(self, inputs): assert isinstance(inputs, dict) return inputs model = Sequential([DictLayer()]) x = {"a": np.random.random((3, 2)), "b": np.random.random((3, 2))} y = model(x) self.assertEqual(type(y), dict) model.summary() def test_list_inputs(self): class ListLayer(layers.Layer): def call(self, inputs): assert isinstance(inputs, list) return inputs model = Sequential([ListLayer()]) x = [np.random.random((3, 2)), np.random.random((3, 2))] y = model(x) self.assertEqual(type(y), list) model.summary() def test_nested_sequential(self): # https://github.com/keras-team/keras/issues/20203 model = Sequential() model.add(Input(shape=(16,))) Sequential([model]) def test_errors(self): # Trying to pass 2 Inputs model = Sequential() model.add(Input(shape=(2,), batch_size=3)) with self.assertRaisesRegex(ValueError, "already been configured"): model.add(Input(shape=(2,), batch_size=3)) with self.assertRaisesRegex(ValueError, "already been configured"): model.add(layers.InputLayer(shape=(2,), batch_size=3)) # Same name 2x model = Sequential() model.add(layers.Dense(2, name="dense")) with self.assertRaisesRegex(ValueError, "should have unique names"): model.add(layers.Dense(2, name="dense")) # No layers model = Sequential() x = np.random.random((3, 2)) with self.assertRaisesRegex(ValueError, "no layers"): model(x) # Build conflict model = Sequential() model.add(Input(shape=(2,), batch_size=3)) model.add(layers.Dense(2)) with self.assertRaisesRegex(ValueError, "already been configured"): model.build((3, 4)) # But this works model.build((3, 2)) def test_shape_inference_failure(self): class DynamicLayer(layers.Layer): def call(self, inputs): return inputs + 1.0 def compute_output_spec(self, *args, **kwargs): raise NotImplementedError model = Sequential([DynamicLayer()]) x = np.random.random((3, 2)) y = model(x) self.assertAllClose(y, x + 1) model.summary() def test_serialization(self): # Unbuilt deferred model = Sequential(name="seq") model.add(layers.Dense(4)) model.add(layers.Dense(5)) revived = self.run_class_serialization_test(model) self.assertLen(revived.layers, 2) # Built deferred model.build((2, 3)) revived = self.run_class_serialization_test(model) self.assertLen(revived.layers, 2) # Regular model = Sequential(name="seq") model.add(Input(shape=(2,), batch_size=3)) model.add(layers.Dense(4)) model.add(layers.Dense(5)) model.add(layers.Dense(6)) revived = self.run_class_serialization_test(model) self.assertLen(revived.layers, 3) # Weird class DictLayer(layers.Layer): def call(self, inputs): assert isinstance(inputs, dict) return inputs model = Sequential([DictLayer()]) revived = self.run_class_serialization_test( model, custom_objects={"DictLayer": DictLayer} ) self.assertLen(revived.layers, 1) def test_serialization_with_lambda_layer(self): # https://github.com/keras-team/keras/issues/20074 inputs = np.random.random(size=(1, 10, 4)).astype("float32") CONV_WIDTH = 3 model = Sequential([layers.Lambda(lambda x: x[:, -CONV_WIDTH:, :])]) outputs = model(inputs) temp = self.get_temp_dir() save_path = f"{temp}/model.keras" model.save(save_path) revived = saving.load_model(save_path, safe_mode=False) revived_outputs = revived(inputs) self.assertLen(revived.layers, 1) self.assertAllClose(revived_outputs, outputs) def test_functional_properties(self): model = Sequential(name="seq") inputs = Input(shape=(2,)) model.add(inputs) model.add(layers.Dense(4)) self.assertEqual(model.inputs, [inputs]) self.assertEqual(model.outputs, [model.layers[-1].output]) self.assertEqual(model.input_shape, (None, 2)) self.assertEqual(model.output_shape, (None, 4)) def test_pickleable(self): model = Sequential(name="seq") model.add(layers.Dense(4)) result = pickle.loads(pickle.dumps(model)) assert len(result.layers) == 1 def test_bad_layer(self): model = Sequential(name="seq") with self.assertRaisesRegex(ValueError, "Only instances of"): model.add({}) model = Sequential(name="seq") class BadLayer(layers.Layer): def call(self, inputs, training): return inputs model.add(BadLayer()) with self.assertRaisesRegex( ValueError, "can only have a single positional" ): model.build((None, 2)) def test_compute_output_shape(self): layer = Sequential([layers.Dense(4), layers.Dense(8)]) output_shape = layer.compute_output_shape((1, 2)) self.assertEqual(output_shape, (1, 8)) def test_hasattr(self): model = Sequential() self.assertFalse(hasattr(model, "input_shape")) self.assertFalse(hasattr(model, "output_shape")) self.assertFalse(hasattr(model, "inputs")) self.assertFalse(hasattr(model, "outputs")) model = Sequential([layers.Input((4,)), layers.Dense(8)]) self.assertTrue(hasattr(model, "input_shape")) self.assertTrue(hasattr(model, "output_shape")) self.assertTrue(hasattr(model, "inputs")) self.assertTrue(hasattr(model, "outputs")) def test_layers_setter(self): model = Sequential() with self.assertRaisesRegex( AttributeError, r"Use `add\(\)` and `pop\(\)`" ): model.layers = [layers.Dense(4)]
SequentialTest
python
doocs__leetcode
solution/0400-0499/0423.Reconstruct Original Digits from English/Solution.py
{ "start": 0, "end": 557 }
class ____: def originalDigits(self, s: str) -> str: counter = Counter(s) cnt = [0] * 10 cnt[0] = counter['z'] cnt[2] = counter['w'] cnt[4] = counter['u'] cnt[6] = counter['x'] cnt[8] = counter['g'] cnt[3] = counter['h'] - cnt[8] cnt[5] = counter['f'] - cnt[4] cnt[7] = counter['s'] - cnt[6] cnt[1] = counter['o'] - cnt[0] - cnt[2] - cnt[4] cnt[9] = counter['i'] - cnt[5] - cnt[6] - cnt[8] return ''.join(cnt[i] * str(i) for i in range(10))
Solution
python
getsentry__sentry
src/sentry/integrations/on_call/metrics.py
{ "start": 1820, "end": 2068 }
class ____(StrEnum): """ Reasons why on on call integration method may halt without success/failure. """ INVALID_TEAM = "invalid_team" INVALID_SERVICE = "invalid_service" INVALID_KEY = "invalid_key"
OnCallIntegrationsHaltReason
python
getsentry__sentry
src/sentry/quotas/base.py
{ "start": 886, "end": 1140 }
class ____(IntEnum): ORGANIZATION = 1 PROJECT = 2 KEY = 3 GLOBAL = 4 def api_name(self): return self.name.lower() AbuseQuotaScope = Literal[QuotaScope.ORGANIZATION, QuotaScope.PROJECT, QuotaScope.GLOBAL] @dataclass
QuotaScope
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 254996, "end": 258612 }
class ____(multi_rv_frozen): def __init__(self, mu=None, kappa=1, seed=None): """Create a frozen von Mises-Fisher distribution. Parameters ---------- mu : array_like, default: None Mean direction of the distribution. kappa : float, default: 1 Concentration parameter. Must be positive. seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. """ self._dist = vonmises_fisher_gen(seed) self.dim, self.mu, self.kappa = ( self._dist._process_parameters(mu, kappa) ) def logpdf(self, x): """ Parameters ---------- x : array_like Points at which to evaluate the log of the probability density function. The last axis of `x` must correspond to unit vectors of the same dimensionality as the distribution. Returns ------- logpdf : ndarray or scalar Log of probability density function evaluated at `x`. """ return self._dist._logpdf(x, self.dim, self.mu, self.kappa) def pdf(self, x): """ Parameters ---------- x : array_like Points at which to evaluate the log of the probability density function. The last axis of `x` must correspond to unit vectors of the same dimensionality as the distribution. Returns ------- pdf : ndarray or scalar Probability density function evaluated at `x`. """ return np.exp(self.logpdf(x)) def rvs(self, size=1, random_state=None): """Draw random variates from the Von Mises-Fisher distribution. Parameters ---------- size : int or tuple of ints, optional Given a shape of, for example, (m,n,k), m*n*k samples are generated, and packed in an m-by-n-by-k arrangement. Because each sample is N-dimensional, the output shape is (m,n,k,N). If no shape is specified, a single (N-D) sample is returned. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `N`), where `N` is the dimension of the distribution. """ random_state = self._dist._get_random_state(random_state) return self._dist._rvs(self.dim, self.mu, self.kappa, size, random_state) def entropy(self): """ Calculate the differential entropy of the von Mises-Fisher distribution. Returns ------- h: float Entropy of the Von Mises-Fisher distribution. """ return self._dist._entropy(self.dim, self.kappa)
vonmises_fisher_frozen
python
pennersr__django-allauth
allauth/mfa/webauthn/stages.py
{ "start": 172, "end": 507 }
class ____(LoginStage): key = LoginStageKey.MFA_SIGNUP_WEBAUTHN.value urlname = "mfa_signup_webauthn" def handle(self): response, cont = None, True if self.login.state.get("passkey_signup"): response = headed_redirect_response("mfa_signup_webauthn") return response, cont
PasskeySignupStage
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 40515, "end": 41111 }
class ____( SQLCoreOperations[_T_co], roles.ExpressionElementRole[_T_co], TypingOnly ): """A type that may be used to indicate any SQL column element or object that acts in place of one. :class:`.SQLColumnExpression` is a base of :class:`.ColumnElement`, as well as within the bases of ORM elements such as :class:`.InstrumentedAttribute`, and may be used in :pep:`484` typing to indicate arguments or return values that should behave as column expressions. .. versionadded:: 2.0.0b4 """ __slots__ = () _SQO = SQLCoreOperations
SQLColumnExpression
python
openai__openai-python
src/openai/types/responses/response_input_item.py
{ "start": 12271, "end": 13282 }
class ____(BaseModel): id: str """The unique ID of the tool call.""" arguments: str """A JSON string of the arguments passed to the tool.""" name: str """The name of the tool that was run.""" server_label: str """The label of the MCP server running the tool.""" type: Literal["mcp_call"] """The type of the item. Always `mcp_call`.""" approval_request_id: Optional[str] = None """ Unique identifier for the MCP tool call approval request. Include this value in a subsequent `mcp_approval_response` input to approve or reject the corresponding tool call. """ error: Optional[str] = None """The error from the tool call, if any.""" output: Optional[str] = None """The output from the tool call.""" status: Optional[Literal["in_progress", "completed", "incomplete", "calling", "failed"]] = None """The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`. """
McpCall
python
mlflow__mlflow
mlflow/types/llm.py
{ "start": 25094, "end": 25905 }
class ____(_BaseDataclass): """ Stats about the number of tokens used during inference. Args: prompt_tokens (int): The number of tokens in the prompt. **Optional**, defaults to ``None`` completion_tokens (int): The number of tokens in the generated completion. **Optional**, defaults to ``None`` total_tokens (int): The total number of tokens used. **Optional**, defaults to ``None`` """ prompt_tokens: int | None = None completion_tokens: int | None = None total_tokens: int | None = None def __post_init__(self): self._validate_field("prompt_tokens", int, False) self._validate_field("completion_tokens", int, False) self._validate_field("total_tokens", int, False) @dataclass
TokenUsageStats
python
google__jax
jax/_src/dtypes.py
{ "start": 23847, "end": 40818 }
class ____(ValueError): pass # We don't use util.memoize because there is no implicit X64 dependence. @functools.lru_cache(512) def _least_upper_bound(jax_numpy_dtype_promotion: config.NumpyDtypePromotion, x64: bool, *nodes: JAXType) -> JAXType: """Compute the least upper bound of a set of nodes. Args: nodes: sequence of entries from _jax_types + _weak_types Returns: the _jax_type representing the least upper bound of the input nodes on the promotion lattice. """ # This function computes the least upper bound of a set of nodes N within a partially # ordered set defined by the lattice generated above. # Given a partially ordered set S, let the set of upper bounds of n ∈ S be # UB(n) ≡ {m ∈ S | n ≤ m} # Further, for a set of nodes N ⊆ S, let the set of common upper bounds be given by # CUB(N) ≡ {a ∈ S | ∀ b ∈ N: a ∈ UB(b)} # Then the least upper bound of N is defined as # LUB(N) ≡ {c ∈ CUB(N) | ∀ d ∈ CUB(N), c ≤ d} # The definition of an upper bound implies that c ≤ d if and only if d ∈ UB(c), # so the LUB can be expressed: # LUB(N) = {c ∈ CUB(N) | ∀ d ∈ CUB(N): d ∈ UB(c)} # or, equivalently: # LUB(N) = {c ∈ CUB(N) | CUB(N) ⊆ UB(c)} # By definition, LUB(N) has a cardinality of 1 for a partially ordered set. # Note a potential algorithmic shortcut: from the definition of CUB(N), we have # ∀ c ∈ N: CUB(N) ⊆ UB(c) # So if N ∩ CUB(N) is nonempty, if follows that LUB(N) = N ∩ CUB(N). N = set(nodes) if jax_numpy_dtype_promotion == config.NumpyDtypePromotion.STRICT: UB = _strict_lattice_ubs elif jax_numpy_dtype_promotion == config.NumpyDtypePromotion.STANDARD: if x64: UB = _standard_x64_lattice_ubs else: UB = _standard_x32_lattice_ubs else: raise ValueError( f"Unexpected value of jax_numpy_dtype_promotion={jax_numpy_dtype_promotion!r}") try: bounds = [UB[n] for n in N] except KeyError: dtype = next(n for n in N if n not in UB) raise ValueError(f"{dtype=} is not a valid dtype for JAX type promotion.") CUB = set.intersection(*bounds) LUB = (CUB & N) or {c for c in CUB if CUB.issubset(UB[c])} if len(LUB) == 1: return LUB.pop() elif len(LUB) == 0: if config.numpy_dtype_promotion.value == config.NumpyDtypePromotion.STRICT: msg = ( f"Input dtypes {tuple(str(n) for n in nodes)} have no available implicit dtype " "promotion path when jax_numpy_dtype_promotion=strict. Try explicitly casting " "inputs to the desired output type, or set jax_numpy_dtype_promotion=standard.") elif any(n in _float8_dtypes for n in nodes): msg = ( f"Input dtypes {tuple(str(n) for n in nodes)} have no available implicit dtype " "promotion path. To avoid unintended promotion, 8-bit floats do not support " "implicit promotion. If you'd like your inputs to be promoted to another type, " "you can do so explicitly using e.g. x.astype('float32')") elif any(n in _float4_dtypes for n in nodes): msg = ( f"Input dtypes {tuple(str(n) for n in nodes)} have no available implicit dtype " "promotion path. To avoid unintended promotion, 4-bit floats do not support " "implicit promotion. If you'd like your inputs to be promoted to another type, " "you can do so explicitly using e.g. x.astype('float32')") elif any(n in _intn_dtypes for n in nodes): msg = ( f"Input dtypes {tuple(str(n) for n in nodes)} have no available implicit dtype " "promotion path. To avoid unintended promotion, 2-bit and 4-bit integers do not " "support implicit promotion. If you'd like your inputs to be promoted to another " "type, you can do so explicitly using e.g. x.astype('int32')") else: msg = ( f"Input dtypes {tuple(str(n) for n in nodes)} have no available implicit dtype " "promotion path. Try explicitly casting inputs to the desired output type.") raise TypePromotionError(msg) else: # If we get here, it means the lattice is ill-formed. raise TypePromotionError( f"Internal Type Promotion error: {nodes} do not have a unique least upper bound " f"on the specified lattice; options are {LUB}. This is an unexpected error in " "JAX's internal logic; please report it to the JAX maintainers." ) @set_module('jax.numpy') def promote_types(a: DTypeLike, b: DTypeLike) -> DType: """Returns the type to which a binary operation should cast its arguments. JAX implementation of :func:`numpy.promote_types`. For details of JAX's type promotion semantics, see :ref:`type-promotion`. Args: a: a :class:`numpy.dtype` or a dtype specifier. b: a :class:`numpy.dtype` or a dtype specifier. Returns: A :class:`numpy.dtype` object. Examples: Type specifiers may be strings, dtypes, or scalar types, and the return value is always a dtype: >>> jnp.promote_types('int32', 'float32') # strings dtype('float32') >>> jnp.promote_types(jnp.dtype('int32'), jnp.dtype('float32')) # dtypes dtype('float32') >>> jnp.promote_types(jnp.int32, jnp.float32) # scalar types dtype('float32') Built-in scalar types (:type:`int`, :type:`float`, or :type:`complex`) are treated as weakly-typed and will not change the bit width of a strongly-typed counterpart (see discussion in :ref:`type-promotion`): >>> jnp.promote_types('uint8', int) dtype('uint8') >>> jnp.promote_types('float16', float) dtype('float16') This differs from the NumPy version of this function, which treats built-in scalar types as equivalent to 64-bit types: >>> import numpy >>> numpy.promote_types('uint8', int) dtype('int64') >>> numpy.promote_types('float16', float) dtype('float64') """ # Note: we deliberately avoid `if a in _weak_types` here because we want to check # object identity, not object equality, due to the behavior of np.dtype.__eq__ a_tp = cast(JAXType, a if any(a is t for t in _weak_types) else np.dtype(a)) b_tp = cast(JAXType, b if any(b is t for t in _weak_types) else np.dtype(b)) return np.dtype(_least_upper_bound( config.numpy_dtype_promotion.value, config.enable_x64.value, a_tp, b_tp)) def register_weak_scalar_type(typ: type): """Register a scalar type as a weak type.""" _registered_weak_types.add(typ) _registered_weak_types: set[JAXType] = { literals.TypedInt, literals.TypedFloat, literals.TypedComplex, } def is_weakly_typed(x: Any) -> bool: if type(x) in _weak_types or type(x) in _registered_weak_types: return True if isinstance(x, literals.TypedNdArray): return x.weak_type try: return x.aval.weak_type except AttributeError: return False def is_python_scalar(x: Any) -> bool: try: return x.aval.weak_type and np.ndim(x) == 0 except AttributeError: return type(x) in python_scalar_types def check_valid_dtype(dtype: DType) -> None: if dtype not in _jax_dtype_set: raise TypeError(f"Dtype {dtype} is not a valid JAX array " "type. Only arrays of numeric types are supported by JAX.") def _maybe_canonicalize_explicit_dtype(dtype: DType, fun_name: str) -> DType: "Canonicalizes explicitly requested dtypes, per explicit_x64_dtypes." allow = config.explicit_x64_dtypes.value if allow == config.ExplicitX64Mode.ALLOW or config.enable_x64.value: return dtype canonical_dtype = canonicalize_dtype(dtype) if canonical_dtype == dtype: return dtype fun_name = f" requested in {fun_name}" if fun_name else "" if allow == config.ExplicitX64Mode.ERROR: msg = ("Explicitly requested dtype {}{} is not available. To enable more " "dtypes, set the jax_enable_x64 or allow_explicit_x64_dtypes " "configuration options." "See https://github.com/jax-ml/jax#current-gotchas for more.") msg = msg.format(dtype, fun_name, canonical_dtype.name) raise ValueError(msg) else: # WARN msg = ("Explicitly requested dtype {}{} is not available, " "and will be truncated to dtype {}. To enable more dtypes, set the " "jax_enable_x64 configuration option or the JAX_ENABLE_X64 shell " "environment variable. " "See https://github.com/jax-ml/jax#current-gotchas for more.") msg = msg.format(dtype, fun_name, canonical_dtype.name) warnings.warn(msg, stacklevel=4) return canonical_dtype _types_whose_dtype_should_not_be_canonicalized = ( Array, literals.TypedNdArray, literals.TypedInt, literals.TypedFloat, literals.TypedComplex, ) def dtype(x: Any) -> DType: """Return the dtype object for a value or type. Python scalars, Python scalar types, NumPy scalar type, NumPy dtypes, and non-JAX arrays will have their dtypes canonicalized. Note: this is not the same function as jax.numpy.dtype, which simply aliases numpy.dtype.""" # TODO(phawkins): in the future, we would like to: # - return the default dtype for Python scalar types and values # - canonicalize NumPy array and scalar types # - return NumPy dtypes as-is, uncanonicalized. if x is None: raise ValueError(f"Invalid argument to dtype: {x}.") if isinstance(x, type): # Python scalar types, e.g., int, float if (dt := python_scalar_types_to_dtypes.get(x)) is not None: return canonicalize_dtype(dt) # Numpy scalar types, e.g., np.int32, np.float32 if _issubclass(x, np.generic): dt = np.dtype(x) return _maybe_canonicalize_explicit_dtype(dt, "dtype") # Python scalar values, e.g., int(3), float(3.14) elif (dt := python_scalar_types_to_dtypes.get(type(x))) is not None: return canonicalize_dtype(dt) # Jax Arrays, literal arrays, and scalars. # We intentionally do not canonicalize these types: once we've formed an x64 # value, that is something we respect irrespective of the x64 mode. elif isinstance(x, _types_whose_dtype_should_not_be_canonicalized): return x.dtype if isinstance(x, str): x = np.dtype(x) if isinstance(x, np.dtype): if x not in _jax_dtype_set and not issubdtype(x, extended): raise TypeError(f"Value '{x}' with dtype {dt} is not a valid JAX array " "type. Only arrays of numeric types are supported by JAX.") return _maybe_canonicalize_explicit_dtype(x, "dtype") if issubdtype(getattr(x, 'dtype', None), extended): dt = x.dtype else: try: dt = np.result_type(x) except TypeError as err: raise TypeError(f"Cannot determine dtype of {x}") from err if dt not in _jax_dtype_set and not issubdtype(dt, extended): raise TypeError(f"Value '{x}' with dtype {dt} is not a valid JAX array " "type. Only arrays of numeric types are supported by JAX.") # TODO(jakevdp): fix return type annotation and remove this ignore. return canonicalize_dtype(dt, allow_extended_dtype=True) # type: ignore[return-value] def lattice_result_type(*args: Any) -> tuple[DType, bool]: dtypes, weak_types = zip(*(_dtype_and_weaktype(arg) for arg in args)) if len(dtypes) == 1: out_dtype = dtypes[0] out_weak_type = weak_types[0] elif len(set(dtypes)) == 1 and not all(weak_types): # Trivial promotion case. This allows extended dtypes through. out_dtype = dtypes[0] out_weak_type = False elif all(weak_types) and config.numpy_dtype_promotion.value != config.NumpyDtypePromotion.STRICT: # If all inputs are weakly typed, we compute the bound of the strongly-typed # counterparts and apply the weak type at the end. This avoids returning the # incorrect result with non-canonical weak types (e.g. weak int16). # TODO(jakevdp): explore removing this special case. result_type = _least_upper_bound( config.numpy_dtype_promotion.value, config.enable_x64.value, *{_jax_type(dtype, False) for dtype in dtypes}) out_dtype = dtype(result_type) out_weak_type = True else: result_type = _least_upper_bound( config.numpy_dtype_promotion.value, config.enable_x64.value, *{_jax_type(d, w) for d, w in zip(dtypes, weak_types)}) out_dtype = dtype(result_type) out_weak_type = any(result_type is t for t in _weak_types) return out_dtype, (out_dtype != bool_) and out_weak_type @overload def result_type(*args: Any, return_weak_type_flag: Literal[True]) -> tuple[DType, bool]: ... @overload def result_type(*args: Any, return_weak_type_flag: Literal[False] = False) -> DType: ... @overload def result_type(*args: Any, return_weak_type_flag: bool = False) -> DType | tuple[DType, bool]: ... @export def result_type(*args: Any, return_weak_type_flag: bool = False) -> DType | tuple[DType, bool]: """Convenience function to apply JAX argument dtype promotion. Args: return_weak_type_flag : if True, then return a ``(dtype, weak_type)`` tuple. If False, just return `dtype` Returns: dtype or (dtype, weak_type) depending on the value of the ``return_weak_type`` argument. """ if len(args) == 0: raise ValueError("at least one array or dtype is required") dtype: DType | ExtendedDType dtype, weak_type = lattice_result_type(*(default_float_dtype() if arg is None else arg for arg in args)) if weak_type: dtype = default_types['f' if dtype in _custom_float_dtypes else dtype.kind]() # TODO(jakevdp): fix return type annotation and remove this ignore. return (dtype, weak_type) if return_weak_type_flag else dtype # type: ignore[return-value] def check_and_canonicalize_user_dtype(dtype, fun_name=None) -> DType: """Checks validity of a user-provided dtype, and returns its canonical form. For Python scalar types this function returns the corresponding default dtype. """ if dtype is None: raise ValueError("dtype must be specified.") if isinstance(dtype, Array): raise ValueError("Passing an array as a dtype argument is no longer " "supported; instead of dtype=arr use dtype=arr.dtype.") if issubdtype(dtype, extended): return dtype # Avoid using `dtype in [...]` because of numpy dtype equality overloading. if isinstance(dtype, type) and (f := _DEFAULT_TYPEMAP.get(dtype)) is not None: return f() np_dtype = np.dtype(dtype) if np_dtype not in _jax_dtype_set: msg = ( f'JAX only supports number, bool, and string dtypes, got dtype {dtype}' ) msg += f" in {fun_name}" if fun_name else "" raise TypeError(msg) return _maybe_canonicalize_explicit_dtype(np_dtype, fun_name) def safe_to_cast(input_dtype_or_value: Any, output_dtype_or_value: Any) -> bool: """Check if a dtype/value is safe to cast to another dtype/value Args: input_dtype_or_value: a dtype or value (to be passed to result_type) representing the source dtype. output_dtype_or_value: a dtype or value (to be passed to result_type) representing the target dtype. Returns: boolean representing whether the values are safe to cast according to default type promotion semantics. Raises: TypePromotionError: if the inputs have differing types and no type promotion path under the current jax_numpy_dtype_promotion setting. Examples: >>> safe_to_cast('int16', 'float32') True >>> safe_to_cast('float32', 'int16') False >>> safe_to_cast('float32', 'complex64') True >>> safe_to_cast('complex64', 'float32') False """ input_dtype = dtype(input_dtype_or_value) output_dtype = dtype(output_dtype_or_value) if input_dtype == output_dtype: return True # We deliberately use output_dtype rather than output_dtype_or_value here: # this effectively treats the output dtype as always strongly-typed. return result_type(input_dtype_or_value, output_dtype) == output_dtype def primal_tangent_dtype(primal_dtype, tangent_dtype, name: str | None = None) -> ExtendedDType: primal_dtype, tangent_dtype = map(dtype, (primal_dtype, tangent_dtype)) name_ = name or (f'PrimalTangentDType{{{short_dtype_name(primal_dtype)}' f'/{short_dtype_name(tangent_dtype)}}}') rules = types.SimpleNamespace( physical_element_aval= lambda dtype: types.SimpleNamespace(shape=(), dtype=primal_dtype), tangent_dtype=lambda dtype: tangent_dtype, allow_conversion=True) class primal_tangent_dtype_scalar(extended): ... @dataclasses.dataclass(frozen=True) class PrimalTangentDType(ExtendedDType): name = name_ _rules = rules type = primal_tangent_dtype_scalar __repr__ = lambda _: name_ return PrimalTangentDType() @functools.cache def short_dtype_name(dtype) -> str: if isinstance(dtype, ExtendedDType): return str(dtype) else: return (dtype.name.replace('float', 'f').replace('uint' , 'u') .replace('int' , 'i').replace('complex', 'c')) def is_string_dtype(dtype: DTypeLike | None) -> bool: return dtype in _string_types
TypePromotionError
python
euske__pdfminer
pdfminer/pdffont.py
{ "start": 2413, "end": 4888 }
class ____(PSStackParser): KEYWORD_BEGIN = KWD(b'begin') KEYWORD_END = KWD(b'end') KEYWORD_DEF = KWD(b'def') KEYWORD_PUT = KWD(b'put') KEYWORD_DICT = KWD(b'dict') KEYWORD_ARRAY = KWD(b'array') KEYWORD_READONLY = KWD(b'readonly') KEYWORD_FOR = KWD(b'for') KEYWORD_FOR = KWD(b'for') def __init__(self, data): PSStackParser.__init__(self, data) self._cid2unicode = {} return def get_encoding(self): while 1: try: (cid, name) = self.nextobject() except PSEOF: break try: self._cid2unicode[cid] = name2unicode(name) except KeyError: pass return self._cid2unicode def do_keyword(self, pos, token): if token is self.KEYWORD_PUT: ((_, key), (_, value)) = self.pop(2) if (isinstance(key, int) and isinstance(value, PSLiteral)): self.add_results((key, literal_name(value))) return NIBBLES = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'e', 'e-', None, '-') ## CFFFont ## (Format specified in Adobe Technical Note: #5176 ## "The Compact Font Format Specification") ## def getdict(data): d = {} fp = BytesIO(data) stack = [] while 1: c = fp.read(1) if not c: break b0 = ord(c) if b0 <= 21: d[b0] = stack stack = [] continue if b0 == 30: s = '' loop = True while loop: b = ord(fp.read(1)) for n in (b >> 4, b & 15): if n == 15: loop = False else: s += NIBBLES[n] value = float(s) elif 32 <= b0 and b0 <= 246: value = b0-139 else: b1 = ord(fp.read(1)) if 247 <= b0 and b0 <= 250: value = ((b0-247) << 8)+b1+108 elif 251 <= b0 and b0 <= 254: value = -((b0-251) << 8)-b1-108 else: b2 = ord(fp.read(1)) if 128 <= b1: b1 -= 256 if b0 == 28: value = b1 << 8 | b2 else: value = b1 << 24 | b2 << 16 | struct.unpack('>H', fp.read(2))[0] stack.append(value) return d
Type1FontHeaderParser
python
django__django
tests/generic_views/test_base.py
{ "start": 23622, "end": 24444 }
class ____(SimpleTestCase): rf = RequestFactory() def test_use_queryset_from_view(self): test_view = views.CustomMultipleObjectMixinView() test_view.get(self.rf.get("/")) # Don't pass queryset as argument context = test_view.get_context_data() self.assertEqual(context["object_list"], test_view.queryset) def test_overwrite_queryset(self): test_view = views.CustomMultipleObjectMixinView() test_view.get(self.rf.get("/")) queryset = [{"name": "Lennon"}, {"name": "Ono"}] self.assertNotEqual(test_view.queryset, queryset) # Overwrite the view's queryset with queryset from kwarg context = test_view.get_context_data(object_list=queryset) self.assertEqual(context["object_list"], queryset)
UseMultipleObjectMixinTest
python
jackfrued__Python-100-Days
Day31-35/code/example14.py
{ "start": 1222, "end": 1940 }
class ____(): """玩家""" def __init__(self, name): self.name = name self.cards = [] def get_card(self, card): """摸牌""" self.cards.append(card) def arrange(self): """整理手上的牌""" self.cards.sort(key=lambda card: (card.suite, card.face)) def main(): """主函数""" poker = Poker() poker.shuffle() players = [ Player('东邪'), Player('西毒'), Player('南帝'), Player('北丐') ] while poker.has_more: for player in players: player.get_card(poker.deal()) for player in players: player.arrange() print(player.name, end=': ') print(player.cards) if __name__ == '__main__': main()
Player
python
huggingface__transformers
src/transformers/models/dinov3_vit/modular_dinov3_vit.py
{ "start": 11822, "end": 11863 }
class ____(ArceeMLP): pass
DINOv3ViTMLP
python
joke2k__faker
faker/providers/address/nl_BE/__init__.py
{ "start": 45, "end": 64941 }
class ____(AddressProvider): building_number_formats = ("#", "##", "###", "#", "##", "###") street_suffixes = ( "baan", "boulevard", "dreef", "hof", "laan", "lei", "pad", "ring", "singel", "steeg", "straat", "weg", ) # the 4 digit numerical part of Belgium postal codes is between 1000 and 9999; # see https://nl.wikipedia.org/wiki/Postcode#Postnummers_in_België postcode_formats = ("%###",) city_formats = ("{{city}}",) # countries are from http://nl.wikipedia.org/wiki/ISO_3166-1 countries = ( "Afghanistan", "Albanië", "Algerije", "Amerikaans-Samoa", "Amerikaanse Maagdeneilanden", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua en Barbuda", "Argentinië", "Armenië", "Aruba", "Australië", "Azerbeidzjan", "Bahama's", "Bahrein", "Bangladesh", "Barbados", "België", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bonaire, Sint Eustatius en Saba", "Bosnië en Herzegovina", "Botswana", "Bouveteiland", "Brazilië", "Brits Indische Oceaanterritorium", "Britse Maagdeneilanden", "Brunei", "Bulgarije", "Burkina Faso", "Burundi", "Cambodja", "Canada", "Centraal-Afrikaanse Republiek", "Chili", "China", "Christmaseiland", "Cocoseilanden", "Colombia", "Comoren", "Congo-Brazzaville", "Congo-Kinshasa", "Cookeilanden", "Costa Rica", "Cuba", "Curaçao", "Cyprus", "Denemarken", "Djibouti", "Dominica", "Dominicaanse Republiek", "Duitsland", "Ecuador", "Egypte", "El Salvador", "Equatoriaal-Guinea", "Eritrea", "Estland", "Ethiopië", "Faeröer", "Falklandeilanden", "Fiji", "Filipijnen", "Finland", "Frankrijk", "Frans-Guyana", "Frans-Polynesië", "Franse Zuidelijke en Antarctische Gebieden", "Gabon", "Gambia", "Georgië", "Ghana", "Gibraltar", "Grenada", "Griekenland", "Groenland", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinee", "Guinee-Bissau", "Guyana", "Haïti", "Heard en McDonaldeilanden", "Honduras", "Hongarije", "Hongkong", "IJsland", "Ierland", "India", "Indonesië", "Irak", "Iran", "Israël", "Italië", "Ivoorkust", "Jamaica", "Japan", "Jemen", "Jersey", "Jordanië", "Kaaimaneilanden", "Kaapverdië", "Kameroen", "Kazachstan", "Kenia", "Kirgizië", "Kiribati", "Kleine Pacifische eilanden van de Verenigde Staten", "Koeweit", "Kroatië", "Laos", "Lesotho", "Letland", "Libanon", "Liberia", "Libië", "Liechtenstein", "Litouwen", "Luxemburg", "Macau", "Madagaskar", "Malawi", "Maldiven", "Maleisië", "Mali", "Malta", "Man", "Marokko", "Marshalleilanden", "Martinique", "Mauritanië", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldavië", "Monaco", "Mongolië", "Montenegro", "Montserrat", "Mozambique", "Myanmar", "Namibië", "Nauru", "Nederland", "Nepal", "Nicaragua", "Nieuw-Caledonië", "Nieuw-Zeeland", "Niger", "Nigeria", "Niue", "Noord-Korea", "Noord-Macedonië", "Noordelijke Marianen", "Noorwegen", "Norfolk", "Oeganda", "Oekraïne", "Oezbekistan", "Oman", "Oost-Timor", "Oostenrijk", "Pakistan", "Palau", "Palestina", "Panama", "Papoea-Nieuw-Guinea", "Paraguay", "Peru", "Pitcairneilanden", "Polen", "Portugal", "Puerto Rico", "Qatar", "Roemenië", "Rusland", "Rwanda", "Réunion", "Saint Kitts en Nevis", "Saint Lucia", "Saint Vincent en de Grenadines", "Saint-Barthélemy", "Saint-Pierre en Miquelon", "Salomonseilanden", "Samoa", "San Marino", "Sao Tomé en Principe", "Saoedi-Arabië", "Senegal", "Servië", "Seychellen", "Sierra Leone", "Singapore", "Sint Maarten", "Sint-Helena, Ascension en Tristan da Cunha", "Sint-Maarten", "Slovenië", "Slowakije", "Soedan", "Somalië", "Spanje", "Spitsbergen en Jan Mayen", "Sri Lanka", "Suriname", "Swaziland", "Syrië", "Tadzjikistan", "Taiwan", "Tanzania", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad en Tobago", "Tsjaad", "Tsjechië", "Tunesië", "Turkije", "Turkmenistan", "Turks- en Caicoseilanden", "Tuvalu", "Uruguay", "Vanuatu", "Vaticaanstad", "Venezuela", "Verenigd Koninkrijk", "Verenigde Arabische Emiraten", "Verenigde Staten", "Vietnam", "Wallis en Futuna", "Westelijke Sahara", "Wit-Rusland", "Zambia", "Zimbabwe", "Zuid-Afrika", "Zuid-Georgia en de Zuidelijke Sandwicheilanden", "Zuid-Korea", "Zuid-Soedan", "Zweden", "Zwitserland", "Åland", ) # cities as listed on "postcodezoeker" # http://www.postcodes-maps.be/postcodelijst.php cities = ( "'s Herenelderen", "'s-Gravenvoeren", "'s-Gravenwezel", "Aaigem", "Aalbeke", "Aalst", "Aalter", "Aarschot", "Aarsele", "Aartrijke", "Aartselaar", "Abolens", "Abée", "Achel", "Achet", "Achêne", "Acosse", "Acoz", "Adegem", "Adinkerke", "Affligem", "Afsnee", "Agimont", "Aineffe", "Aische-en-Refail", "Aiseau", "Aiseau-Presles", "Aisemont", "Alken", "Alle", "Alleur", "Alsemberg", "Alveringem", "Amay", "Amberloup", "Ambly", "Ambresin", "Amel", "Amonines", "Amougies", "Ampsin", "Andenne", "Anderlecht", "Anderlues", "Andrimont", "Angleur", "Angre", "Angreau", "Anhée", "Anlier", "Anloy", "Annevoie-Rouillon", "Ans", "Anseremme", "Anseroeul", "Antheit", "Anthisnes", "Anthée", "Antoing", "Antwerpen", "Anvaing", "Anzegem", "Appels", "Appelterre-Eichem", "Arbre", "Arbrefontaine", "Arc-Ainières", "Arc-Wattripont", "Archennes", "Ardooie", "Arendonk", "Argenteau", "Arlon", "Arquennes", "Arsimont", "Arville", "As", "Aspelare", "Asper", "Asquillies", "Asse", "Assebroek", "Assenede", "Assenois", "Assent", "Assesse", "Astene", "Ath", "Athis", "Athus", "Attenhoven", "Attenrode", "Attert", "Attre", "Aubange", "Aubechies", "Aubel", "Aublain", "Auby-sur-Semois", "Audregnies", "Aulnois", "Autelbas", "Autre-Eglise", "Autreppe", "Auvelais", "Ave-et-Auffe", "Avekapelle", "Avelgem", "Avennes", "Averbode", "Avernas-le-Bauduin", "Avin", "Awans", "Awenne", "Awirs", "Aye", "Ayeneux", "Aywaille", "Baaigem", "Baal", "Baardegem", "Baarle-Hertog", "Baasrode", "Bachte-Maria-Leerne", "Baelen", "Bagimont", "Baileux", "Bailièvre", "Baillamont", "Bailleul", "Baillonville", "Baisieux", "Baisy-Thy", "Balegem", "Balen", "Balâtre", "Bambrugge", "Bande", "Barbençon", "Barchon", "Baronville", "Barry", "Barvaux-Condroz", "Barvaux-sur-Ourthe", "Bas-Oha", "Basse-Bodeux", "Bassenge", "Bassevelde", "Bassilly", "Bastogne", "Basècles", "Batsheers", "Battice", "Battignies", "Baudour", "Bauffe", "Baugnies", "Baulers", "Bavegem", "Bavikhove", "Bazel", "Beaufays", "Beaumont", "Beauraing", "Beausaint", "Beauvoorde", "Beauwelz", "Beclers", "Beek", "Beerlegem", "Beernem", "Beerse", "Beersel", "Beerst", "Beert", "Beervelde", "Beerzel", "Beez", "Beffe", "Begijnendijk", "Beho", "Beigem", "Bekegem", "Bekkerzeel", "Bekkevoort", "Belgrade", "Bellaire", "Bellecourt", "Bellefontaine", "Bellegem", "Bellem", "Bellevaux", "Bellevaux-Ligneuville", "Bellingen", "Beloeil", "Belsele", "Ben-Ahin", "Bende", "Berbroek", "Berchem", "Berendrecht", "Berg", "Bergilers", "Beringen", "Berlaar", "Berlare", "Berlingen", "Berloz", "Berneau", "Bernissart", "Bersillies-l'Abbaye", "Bertem", "Bertogne", "Bertrix", "Bertrée", "Berzée", "Beselare", "Betekom", "Bettincourt", "Beuzet", "Bevekom", "Bevel", "Bever", "Bevercé", "Bevere", "Beveren-Leie", "Beveren-Roeselare", "Beveren-Waas", "Beveren-aan-den-Ijzer", "Beverlo", "Beverst", "Beyne-Heusay", "Bienne-lez-Happart", "Bierbeek", "Biercée", "Bierges", "Bierghes", "Bierset", "Bierwart", "Biesme", "Biesme-sous-Thuin", "Biesmerée", "Biez", "Bihain", "Bikschote", "Bilstain", "Bilzen", "Binche", "Binderveld", "Binkom", "Bioul", "Bissegem", "Bizet", "Bièvre", "Blaasveld", "Blaimont", "Blandain", "Blanden", "Blankenberge", "Blaregnies", "Blaton", "Blaugies", "Blehen", "Bleid", "Bleret", "Blicquy", "Blégny", "Bléharies", "Bocholt", "Boechout", "Boekhout", "Boekhoute", "Boezinge", "Bogaarden", "Bohan", "Boignée", "Boirs", "Bois-d'Haine", "Bois-de-Lessines", "Bois-de-Villers", "Bois-et-Borsu", "Bolinne", "Bolland", "Bomal", "Bomal-sur-Ourthe", "Bombaye", "Bommershoven", "Bon-Secours", "Boncelles", "Boneffe", "Bonheiden", "Boninne", "Bonlez", "Bonnert", "Bonneville", "Bonsin", "Booischot", "Booitshoeke", "Boom", "Boorsem", "Boortmeerbeek", "Borchtlombeek", "Borgerhout", "Borgloon", "Borlez", "Borlo", "Borlon", "Bornem", "Bornival", "Borsbeek", "Borsbeke", "Bossière", "Bossuit", "Bossut-Gottechain", "Bost", "Bothey", "Bottelare", "Bouffioulx", "Bouge", "Bougnies", "Bouillon", "Bourlers", "Bourseigne-Neuve", "Bourseigne-Vieille", "Boussoit", "Boussu", "Boussu-en-Fagne", "Boussu-lez-Walcourt", "Bousval", "Boutersem", "Bouvignes-sur-Meuse", "Bouvignies", "Bouwel", "Bovekerke", "Bovelingen", "Bovenistier", "Bovesse", "Bovigny", "Boëlhe", "Bra", "Braffe", "Braibant", "Braine-l'Alleud", "Braine-le-Château", "Braine-le-Comte", "Braives", "Brakel", "Branchon", "Bras", "Brasmenil", "Brasschaat", "Bray", "Brecht", "Bredene", "Bree", "Breendonk", "Bressoux", "Briegden", "Brielen", "Broechem", "Broekom", "Brugelette", "Brugge", "Brunehaut", "Brussegem", "Brussel", "Brustem", "Bruyelle", "Brye", "Brûly", "Brûly-de-Pesche", "Budingen", "Buggenhout", "Buissenal", "Buissonville", "Buizingen", "Buken", "Bulskamp", "Bunsbeek", "Burcht", "Burdinne", "Bure", "Burg-Reuland", "Burst", "Bury", "Buvingen", "Buvrinnes", "Buzenol", "Buzet", "Büllingen", "Bütgenbach", "Callenelle", "Calonne", "Cambron-Casteau", "Cambron-Saint-Vincent", "Carlsbourg", "Carnières", "Casteau", "Castillon", "Celles", "Cerfontaine", "Chaineux", "Chairière", "Champion", "Champlon", "Chanly", "Chantemelle", "Chapelle-lez-Herlaimont", "Chapelle-à-Oie", "Chapelle-à-Wattines", "Chapon-Seraing", "Charleroi", "Charneux", "Chassepierre", "Chastre", "Chastre-Villeroux-Blanmont", "Chastrès", "Chaudfontaine", "Chaumont-Gistoux", "Chaussée-Notre-Dame-Louvignies", "Cherain", "Cheratte", "Chercq", "Chevetogne", "Chevron", "Chimay", "Chiny", "Chièvres", "Chokier", "Châtelet", "Châtelineau", "Châtillon", "Chênée", "Ciergnon", "Ciney", "Ciplet", "Ciply", "Clabecq", "Clavier", "Clermont", "Clermont-sous-Huy", "Cognelée", "Colfontaine", "Comblain-Fairon", "Comblain-au-Pont", "Comblain-la-Tour", "Conneux", "Corbais", "Corbion", "Cordes", "Corenne", "Cornesse", "Cornimont", "Corroy-le-Château", "Corroy-le-Grand", "Corswarem", "Cortil-Noirmont", "Cortil-Wodon", "Couillet", "Cour-sur-Heure", "Courcelles", "Courrière", "Court-Saint-Etienne", "Couthuin", "Coutisse", "Couture-Saint-Germain", "Couvin", "Cras-Avernas", "Crehen", "Crisnée", "Croix-lez-Rouveroy", "Crombach", "Crupet", "Cuesmes", "Cugnon", "Cul-des-Sarts", "Custinne", "Cérexhe-Heuseux", "Céroux-Mousty", "Dadizele", "Dailly", "Daknam", "Dalhem", "Damme", "Dampicourt", "Dampremy", "Darion", "Daussois", "Daussoulx", "Dave", "Daverdisse", "De Haan", "De Klinge", "De Moeren", "De Panne", "De Pinte", "Deerlijk", "Deftinge", "Deinze", "Denderbelle", "Denderhoutem", "Denderleeuw", "Dendermonde", "Denderwindeke", "Dentergem", "Denée", "Dergneau", "Dessel", "Desselgem", "Destelbergen", "Desteldonk", "Deurle", "Deurne", "Deux-Acren", "Dhuy", "Diepenbeek", "Diest", "Diets-Heur", "Dikkebus", "Dikkele", "Dikkelvenne", "Diksmuide", "Dilbeek", "Dilsen-Stokkem", "Dinant", "Dion", "Dion-Valmont", "Dison", "Dochamps", "Doel", "Dohan", "Doische", "Dolembreux", "Donceel", "Dongelberg", "Donk", "Donstiennes", "Dorinne", "Dormaal", "Dottenijs", "Dour", "Dourbes", "Dranouter", "Driekapellen", "Drieslinter", "Drogenbos", "Drongen", "Dréhance", "Dudzele", "Duffel", "Duisburg", "Duras", "Durbuy", "Durnal", "Dworp", "Eben-Emael", "Ebly", "Ecaussinnes", "Ecaussinnes-Lalaing", "Ecaussinnes-d'Enghien", "Edegem", "Edelare", "Edingen", "Eeklo", "Eernegem", "Egem", "Eggewaartskapelle", "Eghezée", "Ehein", "Eigenbilzen", "Eindhout", "Eine", "Eisden", "Eke", "Ekeren", "Eksaarde", "Eksel", "Elen", "Elene", "Elewijt", "Eliksem", "Elingen", "Ellemelle", "Ellezelles", "Ellignies-Sainte-Anne", "Ellignies-lez-Frasnes", "Ellikom", "Elouges", "Elsegem", "Elsenborn", "Elsene", "Elst", "Elverdinge", "Elversele", "Emblem", "Embourg", "Emelgem", "Emines", "Emptinne", "Ename", "Engelmanshoven", "Engis", "Enines", "Ensival", "Epinois", "Eppegem", "Eprave", "Erbaut", "Erbisoeul", "Ere", "Erembodegem", "Erezée", "Ermeton-sur-Biert", "Ernage", "Erneuville", "Ernonheid", "Erondegem", "Erpe", "Erpe-Mere", "Erpent", "Erpion", "Erps-Kwerps", "Erquelinnes", "Erquennes", "Ertvelde", "Erwetegem", "Escanaffles", "Esen", "Esneux", "Esplechin", "Esquelmes", "Essen", "Essene", "Estaimbourg", "Estaimpuis", "Estinnes", "Estinnes-au-Mont", "Estinnes-au-Val", "Etalle", "Ethe", "Etikhove", "Ettelgem", "Etterbeek", "Eugies", "Eupen", "Evegnée", "Evelette", "Everbeek", "Everberg", "Evere", "Evergem", "Evregnies", "Evrehailles", "Eynatten", "Ezemaal", "Fagnolle", "Faimes", "Falaën", "Falisolle", "Fallais", "Falmagne", "Falmignoul", "Familleureux", "Farciennes", "Faulx-les-Tombes", "Fauroeulx", "Fauvillers", "Faymonville", "Fays-les-Veneurs", "Fayt-le-Franc", "Fayt-lez-Manage", "Felenne", "Feluy", "Feneur", "Fernelmont", "Ferrières", "Feschaux", "Fexhe-Slins", "Fexhe-le-Haut-Clocher", "Filot", "Finnevaux", "Fize-Fontaine", "Fize-le-Marsal", "Flamierge", "Flavion", "Flawinne", "Fleurus", "Floreffe", "Florennes", "Florenville", "Floriffoux", "Florée", "Flostoy", "Flémalle", "Flémalle-Grande", "Flémalle-Haute", "Flénu", "Fléron", "Flône", "Focant", "Folx-les-Caves", "Fontaine-Valmont", "Fontaine-l'Evêque", "Fontenelle", "Fontenoille", "Fontenoy", "Fooz", "Forchies-la-Marche", "Forest", "Forges", "Forges-Philippe", "Forrières", "Forville", "Forêt", "Fosse", "Fosses-la-Ville", "Fouleng", "Fourbechies", "Foy-Notre-Dame", "Fraipont", "Fraire", "Fraiture", "Frameries", "Framont", "Franc-Waret", "Franchimont", "Francorchamps", "Franière", "Frasnes", "Frasnes-lez-Anvaing", "Frasnes-lez-Buissenal", "Frasnes-lez-Gosselies", "Freloux", "Freux", "Froidchapelle", "Froidfontaine", "Froidmont", "Fronville", "Froyennes", "Fumal", "Furfooz", "Furnaux", "Gaasbeek", "Gages", "Gallaix", "Galmaarden", "Ganshoren", "Gaurain-Ramecroix", "Gavere", "Gedinne", "Geel", "Geer", "Geest-Gérompont-Petit-Rosière", "Geetbets", "Gelbressée", "Gelinden", "Gellik", "Gelrode", "Geluveld", "Geluwe", "Gembes", "Gembloux", "Gemmenich", "Genappe", "Genk", "Genly", "Genoelselderen", "Gent", "Gentbrugge", "Gentinnes", "Genval", "Geraardsbergen", "Gerdingen", "Gerin", "Gerpinnes", "Gestel", "Gesves", "Ghislenghien", "Ghlin", "Ghoy", "Gibecq", "Gierle", "Gijverinkhove", "Gijzegem", "Gijzelbrechtegem", "Gijzenzele", "Gilly", "Gimnée", "Gingelom", "Gistel", "Gits", "Givry", "Glabais", "Glabbeek-Zuurbemde", "Glain", "Gleixhe", "Glimes", "Glons", "Gochenée", "Godarville", "Godinne", "Godveerdegem", "Goeferdinge", "Goegnies-Chaussée", "Goesnes", "Goetsenhoven", "Gomzé-Andoumont", "Gondregnies", "Gonrieux", "Gontrode", "Gooik", "Gors-Opleeuw", "Gorsem", "Gosselies", "Gotem", "Gottem", "Gottignies", "Gougnies", "Gourdinne", "Goutroux", "Gouvy", "Gouy-lez-Piéton", "Gozée", "Goé", "Graide", "Grammene", "Grand-Axhe", "Grand-Hallet", "Grand-Halleux", "Grand-Leez", "Grand-Manil", "Grand-Rechain", "Grand-Reng", "Grand-Rosière-Hottomont", "Grandglise", "Grandhan", "Grandmenil", "Grandmetz", "Grandrieu", "Grandville", "Grandvoir", "Grapfontaine", "Graty", "Graux", "Grazen", "Grembergen", "Grez-Doiceau", "Grimbergen", "Grimminge", "Grivegnée", "Grobbendonk", "Groot-Bijgaarden", "Groot-Gelmen", "Groot-Loon", "Gros-Fays", "Grosage", "Grote-Brogel", "Grote-Spouwen", "Grotenberge", "Gruitrode", "Grune", "Grupont", "Grâce-Berleur", "Grâce-Hollogne", "Guignies", "Guigoven", "Guirsch", "Gullegem", "Gutschoven", "Gérompont", "Gérouville", "Haacht", "Haaltert", "Haasdonk", "Haasrode", "Habay", "Habay-la-Neuve", "Habay-la-Vieille", "Habergy", "Haccourt", "Hachy", "Hacquegnies", "Haillot", "Haine-Saint-Paul", "Haine-Saint-Pierre", "Hainin", "Hakendover", "Halanzy", "Halen", "Hallaar", "Halle", "Halle-Booienhoven", "Halleux", "Halma", "Halmaal", "Haltinne", "Ham", "Ham-sur-Heure", "Ham-sur-Heure-Nalinnes", "Ham-sur-Sambre", "Hamipré", "Hamme", "Hamme-Mille", "Hamoir", "Hamois", "Hamont", "Hamont-Achel", "Hampteau", "Han-sur-Lesse", "Handzame", "Haneffe", "Hannut", "Hannêche", "Hanret", "Hansbeke", "Hantes-Wihéries", "Hanzinelle", "Hanzinne", "Harchies", "Harelbeke", "Haren", "Haren-Borgloon", "Haren-Tongeren", "Hargimont", "Harmignies", "Harnoncourt", "Harre", "Harsin", "Harveng", "Harzé", "Hasselt", "Hastière", "Hastière-Lavaux", "Hastière-par-Delà", "Hatrival", "Haulchin", "Hauset", "Haut-Fays", "Haut-Ittre", "Haut-le-Wastia", "Hautrage", "Havay", "Havelange", "Haversin", "Havinnes", "Havré", "Hechtel", "Hechtel-Eksel", "Heer", "Heers", "Hees", "Heestert", "Heffen", "Heikruis", "Heindonk", "Heinsch", "Heist-aan-Zee", "Heist-op-den-Berg", "Hekelgem", "Heks", "Helchteren", "Heldergem", "Helen-Bos", "Helkijn", "Hellebecq", "Hemelveerdegem", "Hemiksem", "Hemptinne", "Hemptinne-lez-Florennes", "Hendrieken", "Henis", "Hennuyères", "Henri-Chapelle", "Henripont", "Hensies", "Heppen", "Heppenbach", "Heppignies", "Herbeumont", "Herchies", "Herderen", "Herdersem", "Herent", "Herentals", "Herenthout", "Herfelingen", "Hergenrath", "Herk-de-Stad", "Hermalle-sous-Argenteau", "Hermalle-sous-Huy", "Hermeton-sur-Meuse", "Hermée", "Herne", "Herquegies", "Herseaux", "Herselt", "Herstal", "Herstappe", "Hertain", "Herten", "Hertsberge", "Herve", "Herzele", "Heule", "Heure", "Heure-le-Romain", "Heurne", "Heusden", "Heusden-Zolder", "Heusy", "Heuvelland", "Hever", "Heverlee", "Heyd", "Hillegem", "Hingene", "Hingeon", "Hives", "Hoboken", "Hodeige", "Hodister", "Hody", "Hoegaarden", "Hoeilaart", "Hoeke", "Hoelbeek", "Hoeleden", "Hoepertingen", "Hoeselt", "Hoevenen", "Hofstade", "Hogne", "Hognoul", "Hollain", "Hollange", "Hollebeke", "Hollogne-aux-Pierres", "Hollogne-sur-Geer", "Holsbeek", "Hombeek", "Hombourg", "Hompré", "Hondelange", "Honnay", "Honnelles", "Hooglede", "Hoogstade", "Hoogstraten", "Horebeke", "Horion-Hozémont", "Hornu", "Horpmaal", "Horrues", "Hotton", "Houdemont", "Houdeng-Aimeries", "Houdeng-Goegnies", "Houdremont", "Houffalize", "Hour", "Housse", "Houtain-Saint-Siméon", "Houtain-le-Val", "Houtaing", "Houtave", "Houtem", "Houthalen", "Houthalen-Helchteren", "Houthem", "Houthulst", "Houtvenne", "Houwaart", "Houx", "Houyet", "Hove", "Hoves", "Howardries", "Huccorgne", "Huise", "Huissignies", "Huizingen", "Huldenberg", "Hulshout", "Hulsonniaux", "Hulste", "Humain", "Humbeek", "Hundelgem", "Huppaye", "Huy", "Hyon", "Hélécine", "Hérinnes-lez-Pecq", "Héron", "Hévillers", "Ichtegem", "Iddergem", "Idegem", "Ieper", "Impe", "Incourt", "Ingelmunster", "Ingooigem", "Irchonwelz", "Isières", "Isnes", "Itegem", "Itterbeek", "Ittre", "Ivoz-Ramet", "Izegem", "Izel", "Izenberge", "Izier", "Jabbeke", "Jalhay", "Jallet", "Jamagne", "Jambes", "Jamiolle", "Jamioulx", "Jamoigne", "Jandrain-Jandrenouille", "Jauche", "Jauchelette", "Javingue", "Jehay", "Jehonville", "Jemappes", "Jemelle", "Jemeppe-sur-Meuse", "Jemeppe-sur-Sambre", "Jeneffe", "Jesseren", "Jette", "Jeuk", "Jodoigne", "Jodoigne-Souveraine", "Jollain-Merlin", "Joncret", "Julémont", "Jumet", "Jupille-sur-Meuse", "Juprelle", "Jurbise", "Juseret", "Kaaskerke", "Kachtem", "Kaggevinne", "Kain", "Kalken", "Kallo", "Kallo-Kieldrecht", "Kalmthout", "Kampenhout", "Kanegem", "Kanne", "Kapelle-op-den-Bos", "Kapellen", "Kaprijke", "Kaster", "Kasterlee", "Kaulille", "Keerbergen", "Keiem", "Kelmis", "Kemexhe", "Kemmel", "Kemzeke", "Kerkhove", "Kerkom", "Kerkom-bij-Sint-Truiden", "Kerksken", "Kermt", "Kerniel", "Kersbeek-Miskom", "Kessel", "Kessel-Lo", "Kessenich", "Kester", "Kettenis", "Keumiée", "Kieldrecht", "Kinrooi", "Klein-Gelmen", "Kleine-Brogel", "Kleine-Spouwen", "Klemskerke", "Klerken", "Kluisbergen", "Kluizen", "Knesselare", "Knokke", "Knokke-Heist", "Kobbegem", "Koekelare", "Koekelberg", "Koersel", "Koksijde", "Kolmont-Borgloon", "Kolmont-Tongeren", "Komen", "Komen-Waasten", "Koningshooikt", "Koninksem", "Kontich", "Kooigem", "Koolkerke", "Koolskamp", "Korbeek-Dijle", "Korbeek-Lo", "Kortemark", "Kortenaken", "Kortenberg", "Kortessem", "Kortijs", "Kortrijk", "Kortrijk-Dutsel", "Kozen", "Kraainem", "Krombeke", "Kruibeke", "Kruishoutem", "Kumtich", "Kuringen", "Kuttekoven", "Kuurne", "Kwaadmechelen", "Kwaremont", "La", "La Bruyère", "La Glanerie", "La Gleize", "La Hestre", "La Hulpe", "La Louvière", "La bouverie", "La-Roche-en-Ardenne", "Laakdal", "Laar", "Laarne", "Labuissière", "Lacuisine", "Ladeuze", "Laforêt", "Lahamaide", "Laken", "Lamain", "Lambermont", "Lambusart", "Lamine", "Lamontzée", "Lamorteau", "Lampernisse", "Lanaken", "Lanaye", "Landegem", "Landelies", "Landen", "Landenne", "Landskouter", "Laneffe", "Langdorp", "Langemark", "Langemark-Poelkapelle", "Lanklaar", "Lanquesaint", "Lantin", "Lantremange", "Laplaigne", "Lapscheure", "Lasne", "Lasne-Chapelle-Saint-Lambert", "Lathuy", "Latinne", "Latour", "Lauw", "Lauwe", "Lavacherie", "Lavaux-Sainte-Anne", "Lavoir", "Le Mesniel", "Le Roeulx", "Le Roux", "Lebbeke", "Lede", "Ledeberg", "Ledegem", "Leefdaal", "Leerbeek", "Leernes", "Leers-Nord", "Leers-et-Fosteau", "Leest", "Leeuwergem", "Leffinge", "Leignon", "Leisele", "Leke", "Lembeek", "Lembeke", "Lemberge", "Lendelede", "Lennik", "Lens", "Lens-Saint-Remy", "Lens-Saint-Servais", "Lens-sur-Geer", "Leopoldsburg", "Les Avins", "Les Bons", "Les Bulles", "Les Hayons", "Les Waleffes", "Lesdain", "Lessines", "Lessive", "Lesterny", "Lesve", "Lettelingen", "Letterhoutem", "Leugnies", "Leupegem", "Leut", "Leuven", "Leuze", "Leuze-en-Hainaut", "Leval-Chaudeville", "Leval-Trahegnies", "Liberchies", "Libin", "Libramont", "Libramont-Chevigny", "Lichtaart", "Lichtervelde", "Liedekerke", "Lieferinge", "Lier", "Lierde", "Lierneux", "Liernu", "Liers", "Liezele", "Ligne", "Ligney", "Ligny", "Lille", "Lillo", "Lillois-Witterzée", "Limal", "Limbourg", "Limelette", "Limerlé", "Limont", "Lincent", "Linden", "Linkebeek", "Linkhout", "Linsmeau", "Lint", "Linter", "Lippelo", "Lisogne", "Lissewege", "Lives-sur-Meuse", "Lixhe", "Liège", "Lo", "Lo-Reninge", "Lobbes", "Lochristi", "Lodelinsart", "Loenhout", "Loker", "Lokeren", "Loksbergen", "Lombardsijde", "Lombise", "Lommel", "Lommersweiler", "Lompret", "Lomprez", "Loncin", "Londerzeel", "Longchamps", "Longlier", "Longueville", "Longvilly", "Lontzen", "Lonzée", "Loonbeek", "Loppem", "Lorcé", "Lot", "Lotenhulle", "Louette-Saint-Denis", "Louette-Saint-Pierre", "Loupoigne", "Louvain-la-Neuve", "Louveigné", "Lovendegem", "Lovenjoel", "Loverval", "Loyers", "Lubbeek", "Luingne", "Lummen", "Lustin", "Luttre", "Léglise", "Maarke-Kerkem", "Maarkedal", "Maaseik", "Maasmechelen", "Mabompré", "Machelen", "Macon", "Macquenoise", "Maffe", "Maffle", "Magnée", "Maillen", "Mainvault", "Maisières", "Maissin", "Maizeret", "Mal", "Maldegem", "Malderen", "Malempré", "Malle", "Malmedy", "Malonne", "Malvoisin", "Malèves-Sainte-Marie-Wastines", "Manage", "Manderfeld", "Manhay", "Mannekensvere", "Maransart", "Marbais", "Marbaix", "Marbehan", "Marche-en-Famenne", "Marche-les-Dames", "Marche-lez-Ecaussinnes", "Marchienne-au-Pont", "Marchin", "Marchipont", "Marchovelette", "Marcinelle", "Marcourt", "Marenne", "Mariakerke", "Mariekerke", "Mariembourg", "Marilles", "Mark", "Marke", "Markegem", "Marneffe", "Marquain", "Martelange", "Martenslinde", "Martouzin-Neuville", "Masbourg", "Masnuy-Saint-Jean", "Masnuy-Saint-Pierre", "Massemen", "Massenhoven", "Matagne-la-Grande", "Matagne-la-Petite", "Mater", "Maubray", "Maulde", "Maurage", "Mazenzele", "Mazy", "Mazée", "Mechelen", "Mechelen-Bovelingen", "Mechelen-aan-de-Maas", "Meeffe", "Meensel-Kiezegem", "Meer", "Meerbeek", "Meerbeke", "Meerdonk", "Meerhout", "Meerle", "Meeswijk", "Meetkerke", "Meeuwen", "Meeuwen-Gruitrode", "Mehaigne", "Meigem", "Meilegem", "Meise", "Meix-devant-Virton", "Meix-le-Tige", "Melden", "Meldert", "Melen", "Melkwezer", "Melle", "Mellery", "Melles", "Mellet", "Mellier", "Melsbroek", "Melsele", "Melsen", "Membach", "Membre", "Membruggen", "Mendonk", "Menen", "Merbes-Sainte-Marie", "Merbes-le-Château", "Merchtem", "Merdorp", "Mere", "Merelbeke", "Merendree", "Merkem", "Merksem", "Merksplas", "Merlemont", "Mesen", "Meslin-l'Evêque", "Mesnil-Eglise", "Mesnil-Saint-Blaise", "Mespelare", "Messancy", "Messelbroek", "Mesvin", "Mettekoven", "Mettet", "Meulebeke", "Meux", "Meyerode", "Michelbeke", "Micheroux", "Middelburg", "Middelkerke", "Mielen-boven-Aalst", "Mignault", "Millen", "Milmort", "Minderhout", "Mirwart", "Miécret", "Modave", "Moelingen", "Moen", "Moerbeke", "Moerbeke-Waas", "Moere", "Moerkerke", "Moerzeke", "Moeskroen", "Moha", "Mohiville", "Moignelée", "Moircy", "Mol", "Molenbaix", "Molenbeek-Wersbeek", "Molenbeersel", "Molenstede", "Mollem", "Momalle", "Momignies", "Monceau-Imbrechies", "Monceau-en-Ardenne", "Monceau-sur-Sambre", "Mons", "Mons-lez-Liège", "Monstreux", "Mont", "Mont-Gauthier", "Mont-Saint-André", "Mont-Saint-Aubert", "Mont-Saint-Guibert", "Mont-Sainte-Aldegonde", "Mont-Sainte-Geneviève", "Mont-de-l'Enclus", "Mont-sur-Marchienne", "Montbliart", "Montegnée", "Montenaken", "Montignies-Saint-Christophe", "Montignies-lez-Lens", "Montignies-sur-Roc", "Montignies-sur-Sambre", "Montigny-le-Tilleul", "Montleban", "Montroeul-au-Bois", "Montroeul-sur-Haine", "Montzen", "Moorsel", "Moorsele", "Moorslede", "Moortsele", "Mopertingen", "Moregem", "Moresnet", "Morhet", "Morialmé", "Morkhoven", "Morlanwelz", "Morlanwelz-Mariemont", "Mormont", "Mornimont", "Mortier", "Mortroux", "Mortsel", "Morville", "Moulbaix", "Mourcourt", "Moustier", "Moustier-sur-Sambre", "Mouzaive", "Moxhe", "Mozet", "Muizen", "Mullem", "Munkzwalm", "Muno", "Munsterbilzen", "Munte", "Musson", "Mussy-la-Ville", "My", "Méan", "Mélin", "Mévergnies-lez-Lens", "Naast", "Nadrin", "Nafraiture", "Nalinnes", "Namur", "Namêche", "Nandrin", "Naninne", "Naomé", "Nassogne", "Natoye", "Nazareth", "Neder-over-Heembeek", "Nederboelare", "Nederbrakel", "Nederename", "Nederhasselt", "Nederokkerzeel", "Nederzwalm-Hermelgem", "Neerglabbeek", "Neerharen", "Neerhespen", "Neerheylissem", "Neerijse", "Neerlanden", "Neerlinter", "Neeroeteren", "Neerpelt", "Neerrepen", "Neervelp", "Neerwaasten", "Neerwinden", "Neigem", "Nerem", "Nessonvaux", "Nethen", "Nettinne", "Neu-Moresnet", "Neufchâteau", "Neufmaison", "Neufvilles", "Neupré", "Neuville", "Neuville-en-Condroz", "Nevele", "Niel", "Niel-bij-As", "Niel-bij-Sint-Truiden", "Nieuwenhove", "Nieuwenrode", "Nieuwerkerken", "Nieuwkapelle", "Nieuwkerke", "Nieuwkerken-Waas", "Nieuwmunster", "Nieuwpoort", "Nieuwrode", "Nijlen", "Nil-Saint-Vincent-Saint-Martin", "Nimy", "Ninove", "Nismes", "Nivelles", "Niverlée", "Nives", "Nobressart", "Nodebais", "Noduwez", "Noirchain", "Noirefontaine", "Noiseux", "Nokere", "Nollevaux", "Noorderwijk", "Noordschote", "Nossegem", "Nothomb", "Nouvelles", "Noville", "Noville-les-Bois", "Noville-sur-Méhaigne", "Nukerke", "Néchin", "Obaix", "Obigies", "Obourg", "Ochamps", "Ocquier", "Odeigne", "Odeur", "Oedelem", "Oekene", "Oelegem", "Oeren", "Oeselgem", "Oetingen", "Oeudeghien", "Oevel", "Offagne", "Ogy", "Ohain", "Ohey", "Oignies-en-Thiérache", "Oisquercq", "Oizy", "Okegem", "Olen", "Oleye", "Ollignies", "Olloy-sur-Viroin", "Olmen", "Olne", "Olsene", "Omal", "Ombret", "Omezée", "On", "Onhaye", "Onkerzele", "Onnezies", "Onoz", "Onze-Lieve-Vrouw-Lombeek", "Onze-Lieve-Vrouw-Waver", "Ooigem", "Ooike", "Oombergen", "Oorbeek", "Oordegem", "Oostakker", "Oostduinkerke", "Oosteeklo", "Oostende", "Oosterzele", "Oostham", "Oostkamp", "Oostkerke-Damme", "Oostkerke-Diksmuide", "Oostmalle", "Oostnieuwkerke", "Oostrozebeke", "Oostvleteren", "Oostwinkel", "Opbrakel", "Opdorp", "Opglabbeek", "Opgrimbie", "Ophain-Bois-Seigneur-Isaac", "Ophasselt", "Opheers", "Opheylissem", "Ophoven", "Opitter", "Oplinter", "Opoeteren", "Opont", "Opprebais", "Oppuurs", "Opvelp", "Opwijk", "Orbais", "Orchimont", "Orcq", "Ordingen", "Oret", "Oreye", "Orgeo", "Ormeignies", "Orp-Jauche", "Orp-le-Grand", "Orroir", "Orsmaal-Gussenhoven", "Ortho", "Ostiches", "Otegem", "Oteppe", "Othée", "Otrange", "Ottenburg", "Ottergem", "Ottignies", "Ottignies-Louvain-la-Neuve", "Oud-Heverlee", "Oud-Turnhout", "Oudegem", "Oudekapelle", "Oudenaarde", "Oudenaken", "Oudenburg", "Oudergem", "Ouffet", "Ougrée", "Oupeye", "Outer", "Outgaarden", "Outrelouxhe", "Outrijve", "Ouwegem", "Overboelare", "Overhespen", "Overijse", "Overmere", "Overpelt", "Overrepen", "Overwinden", "Paal", "Paifve", "Pailhe", "Paliseul", "Pamel", "Papignies", "Parike", "Passendale", "Patignies", "Paturages", "Paulatem", "Pecq", "Peer", "Peissant", "Pellaines", "Pellenberg", "Pepingen", "Pepinster", "Perk", "Pervijze", "Perwez", "Perwez-Haillot", "Pesche", "Pessoux", "Petegem-aan-de-Leie", "Petegem-aan-de-Schelde", "Petigny", "Petit-Fays", "Petit-Hallet", "Petit-Rechain", "Petit-Roeulx-lez-Braine", "Petit-Roeulx-lez-Nivelles", "Petit-Thier", "Petite-Chapelle", "Peutie", "Philippeville", "Pipaix", "Piringen", "Pironchamps", "Pittem", "Piéton", "Piétrain", "Piétrebais", "Plainevaux", "Plancenoit", "Ploegsteert", "Plombières", "Poederlee", "Poeke", "Poelkapelle", "Poesele", "Pollare", "Polleur", "Pollinkhove", "Pommeroeul", "Pondrôme", "Pont-de-Loup", "Pont-à-Celles", "Pontillas", "Poperinge", "Poppel", "Popuelles", "Porcheresse", "Pottes", "Poucet", "Poulseur", "Poupehan", "Pousset", "Presgaux", "Presles", "Profondeville", "Proven", "Pry", "Pulderbos", "Pulle", "Purnode", "Pussemange", "Putte", "Puurs", "Péronnes-lez-Antoing", "Péronnes-lez-Binche", "Péruwelz", "Quaregnon", "Quartes", "Quenast", "Queue-du-Bois", "Quevaucamps", "Quiévrain", "Quévy", "Quévy-le-Grand", "Quévy-le-Petit", "Rachecourt", "Racour", "Raeren", "Ragnies", "Rahier", "Ramegnies", "Ramegnies-Chin", "Ramelot", "Ramillies-Offus", "Ramsdonk", "Ramsel", "Ramskapelle-Knokke-Heist", "Ramskapelle-Nieuwpoort", "Rance", "Ransart", "Ransberg", "Ranst", "Ravels", "Rebaix", "Rebecq", "Rebecq-Rognon", "Recht", "Recogne", "Redu", "Reet", "Rekem", "Rekkem", "Relegem", "Remagne", "Remersdaal", "Remicourt", "Rendeux", "Reninge", "Reningelst", "Renlies", "Reppel", "Ressaix", "Ressegem", "Resteigne", "Retie", "Retinne", "Reuland", "Rhisnes", "Richelle", "Riemst", "Rienne", "Rijkel", "Rijkevorsel", "Rijkhoven", "Rijmenam", "Riksingen", "Rillaar", "Rivière", "Rixensart", "Rièzes", "Robechies", "Robelmont", "Robertville", "Roborst", "Rochefort", "Rochehaut", "Rocherath", "Roclenge-sur-Geer", "Rocourt", "Roesbrugge-Haringe", "Roeselare", "Rognée", "Roisin", "Roksem", "Rollegem", "Rollegem-Kapelle", "Roloux", "Roly", "Romedenne", "Romershoven", "Romerée", "Romsée", "Rongy", "Ronquières", "Ronse", "Ronsele", "Roosbeek", "Roosdaal", "Roselies", "Rosières", "Rosmeer", "Rosoux-Crenwick", "Rossignol", "Rosée", "Rotem", "Rotheux-Rimière", "Rotselaar", "Roucourt", "Rouveroy", "Rouvreux", "Rouvroy", "Roux", "Roux-Miroir", "Roy", "Rozebeke", "Ruddervoorde", "Ruette", "Ruien", "Ruisbroek", "Ruiselede", "Rukkelingen-Loon", "Rulles", "Rumbeke", "Rumes", "Rumillies", "Rummen", "Rumsdorp", "Rumst", "Runkelen", "Rupelmonde", "Russeignies", "Rutten", "Rèves", "Saint-Amand", "Saint-André", "Saint-Aubin", "Saint-Denis", "Saint-Denis-Bovesse", "Saint-Georges-sur-Meuse", "Saint-Germain", "Saint-Ghislain", "Saint-Gérard", "Saint-Géry", "Saint-Hubert", "Saint-Jean-Geest", "Saint-Léger", "Saint-Marc", "Saint-Mard", "Saint-Martin", "Saint-Maur", "Saint-Médard", "Saint-Nicolas", "Saint-Pierre", "Saint-Remy", "Saint-Remy-Geest", "Saint-Sauveur", "Saint-Servais", "Saint-Symphorien", "Saint-Séverin", "Saint-Vaast", "Saint-Vincent", "Sainte-Cécile", "Sainte-Marie-Chevigny", "Sainte-Marie-sur-Semois", "Sainte-Ode", "Saintes", "Saive", "Salles", "Samart", "Sambreville", "Samrée", "Sankt-Vith", "Sars-la-Bruyère", "Sars-la-Buissière", "Sart-Bernard", "Sart-Custinne", "Sart-Dames-Avelines", "Sart-Eustache", "Sart-Saint-Laurent", "Sart-en-Fagne", "Sart-lez-Spa", "Sautin", "Sautour", "Sauvenière", "Schaarbeek", "Schaffen", "Schalkhoven", "Schaltin", "Schelderode", "Scheldewindeke", "Schelle", "Schellebelle", "Schendelbeke", "Schepdaal", "Scherpenheuvel", "Scherpenheuvel-Zichem", "Schilde", "Schoonaarde", "Schore", "Schorisse", "Schoten", "Schriek", "Schuiferskapelle", "Schulen", "Schönberg", "Sclayn", "Scy", "Seilles", "Seloignes", "Semmerzake", "Seneffe", "Sensenruth", "Seny", "Senzeille", "Septon", "Seraing", "Seraing-le-Château", "Serinchamps", "Serskamp", "Serville", "Sibret", "Signeulx", "Sijsele", "Silenrieux", "Silly", "Sinaai-Waas", "Sinsin", "Sint-Agatha-Berchem", "Sint-Agatha-Rode", "Sint-Amands", "Sint-Amandsberg", "Sint-Andries", "Sint-Antelinks", "Sint-Baafs-Vijve", "Sint-Blasius-Boekel", "Sint-Denijs", "Sint-Denijs-Boekel", "Sint-Denijs-Westrem", "Sint-Eloois-Vijve", "Sint-Eloois-Winkel", "Sint-Genesius-Rode", "Sint-Gillis", "Sint-Gillis-Waas", "Sint-Gillis-bij-Dendermonde", "Sint-Goriks-Oudenhove", "Sint-Huibrechts-Hern", "Sint-Huibrechts-Lille", "Sint-Jacobs-Kapelle", "Sint-Jan", "Sint-Jan-in-Eremo", "Sint-Jans-Molenbeek", "Sint-Job-in-'t-Goor", "Sint-Joost-ten-Node", "Sint-Joris-Beernem", "Sint-Joris-Nieuwpoort", "Sint-Joris-Weert", "Sint-Joris-Winge", "Sint-Katelijne-Waver", "Sint-Katherina-Lombeek", "Sint-Kornelis-Horebeke", "Sint-Kruis", "Sint-Kruis-Winkel", "Sint-Kwintens-Lennik", "Sint-Lambrechts-Herk", "Sint-Lambrechts-Woluwe", "Sint-Laureins", "Sint-Laureins-Berchem", "Sint-Lenaarts", "Sint-Lievens-Esse", "Sint-Lievens-Houtem", "Sint-Margriete", "Sint-Margriete-Houtem", "Sint-Maria-Horebeke", "Sint-Maria-Latem", "Sint-Maria-Lierde", "Sint-Maria-Oudenhove-Brakel", "Sint-Maria-Oudenhove-Zottegem", "Sint-Martens-Bodegem", "Sint-Martens-Latem", "Sint-Martens-Leerne", "Sint-Martens-Lennik", "Sint-Martens-Lierde", "Sint-Martens-Voeren", "Sint-Michiels", "Sint-Niklaas", "Sint-Pauwels", "Sint-Pieters-Kapelle", "Sint-Pieters-Leeuw", "Sint-Pieters-Rode", "Sint-Pieters-Voeren", "Sint-Pieters-Woluwe", "Sint-Rijkers", "Sint-Stevens-Woluwe", "Sint-Truiden", "Sint-Ulriks-Kapelle", "Sippenaeken", "Sirault", "Sivry", "Sivry-Rance", "Sleidinge", "Slijpe", "Slins", "Sluizen", "Smeerebbe-Vloerzegem", "Smetlede", "Smuid", "Snaaskerke", "Snellegem", "Soheit-Tinlot", "Sohier", "Soignies", "Soiron", "Solre-Saint-Géry", "Solre-sur-Sambre", "Sombreffe", "Somme-Leuze", "Sommethonne", "Sommière", "Somzée", "Sorinne-la-Longue", "Sorinnes", "Sorée", "Sosoye", "Sougné-Remouchamps", "Soulme", "Soumagne", "Soumoy", "Sourbrodt", "Souvret", "Sovet", "Soy", "Soye", "Spa", "Spalbeek", "Spermalie", "Spiennes", "Spiere", "Spiere-Helkijn", "Spontin", "Spouwen", "Sprimont", "Spy", "Stabroek", "Staden", "Stalhille", "Stambruges", "Stave", "Stavele", "Stavelot", "Steendorp", "Steenhuffel", "Steenhuize-Wijnhuize", "Steenkerke", "Steenkerque", "Steenokkerzeel", "Stekene", "Stembert", "Stene", "Sterrebeek", "Stevoort", "Stokrooie", "Stoumont", "Straimont", "Strijpen", "Strijtem", "Strombeek-Bever", "Strée", "Strée-lez-Huy", "Strépy-Bracquegnies", "Stuivekenskerke", "Suarlée", "Sugny", "Surice", "Suxy", "Sélange", "Tailles", "Taintignies", "Tamines", "Tarcienne", "Tavier", "Taviers", "Tavigny", "Tellin", "Templeuve", "Temploux", "Temse", "Tenneville", "Teralfene", "Terhagen", "Termes", "Ternat", "Tertre", "Tervuren", "Terwagne", "Tessenderlo", "Testelt", "Teuven", "Theux", "Thiaumont", "Thieu", "Thieulain", "Thieusies", "Thimister", "Thimister-Clermont", "Thimougies", "Thiméon", "Thines", "Thirimont", "Thisnes", "Thommen", "Thon", "Thorembais-Saint-Trond", "Thorembais-les-Béguines", "Thoricourt", "Thuillies", "Thuin", "Thulin", "Thumaide", "Thy-le-Bauduin", "Thy-le-Château", "Thynes", "Thys", "Tiegem", "Tielen", "Tielrode", "Tielt", "Tielt-Winge", "Tienen", "Tignée", "Tihange", "Tildonk", "Tilff", "Tillet", "Tilleur", "Tillier", "Tilly", "Tinlot", "Tintange", "Tintigny", "Tisselt", "Toernich", "Tohogne", "Tollembeek", "Tongeren", "Tongerlo", "Tongre-Notre-Dame", "Tongre-Saint-Martin", "Tongrinne", "Tontelange", "Torgny", "Torhout", "Tourinne", "Tourinnes-Saint-Lambert", "Tournai", "Tournay", "Tourpes", "Transinne", "Trazegnies", "Treignes", "Trembleur", "Tremelo", "Trivières", "Trognée", "Trois-Ponts", "Trooz", "Tubize", "Turnhout", "Ucimont", "Uikhoven", "Uitbergen", "Uitkerke", "Ukkel", "Ulbeek", "Upigny", "Ursel", "Vaalbeek", "Val-Meer", "Vance", "Varendonk", "Varsenare", "Vaucelles", "Vaulx", "Vaulx-lez-Chimay", "Vaux-Chavanne", "Vaux-et-Borset", "Vaux-lez-Rosières", "Vaux-sous-Chèvremont", "Vaux-sur-Sûre", "Vechmaal", "Vedrin", "Veerle", "Velaine-sur-Sambre", "Velaines", "Veldegem", "Veldwezelt", "Vellereille-le-Sec", "Vellereille-les-Brayeux", "Velm", "Velroux", "Veltem-Beisem", "Velzeke-Ruddershove", "Vencimont", "Vergnies", "Verlaine", "Verlée", "Verrebroek", "Vertrijk", "Verviers", "Vesqueville", "Veulen", "Veurne", "Vezin", "Vezon", "Viane", "Vichte", "Vielsalm", "Viemme", "Viersel", "Vierset-Barse", "Vierves-sur-Viroin", "Viesville", "Vieux-Genappe", "Vieux-Waleffe", "Vieuxville", "Villance", "Ville-Pommeroeul", "Ville-en-Hesbaye", "Ville-sur-Haine", "Villerot", "Villers-Deux-Eglises", "Villers-Notre-Dame", "Villers-Perwin", "Villers-Poterie", "Villers-Saint-Amand", "Villers-Saint-Ghislain", "Villers-Saint-Siméon", "Villers-Sainte-Gertrude", "Villers-aux-Tours", "Villers-devant-Orval", "Villers-en-Fagne", "Villers-l'Evêque", "Villers-la-Bonne-Eau", "Villers-la-Loue", "Villers-la-Tour", "Villers-la-Ville", "Villers-le-Bouillet", "Villers-le-Gambon", "Villers-le-Peuplier", "Villers-le-Temple", "Villers-lez-Heest", "Villers-sur-Lesse", "Villers-sur-Semois", "Vilvoorde", "Vinalmont", "Vinderhoute", "Vinkem", "Vinkt", "Virelles", "Virginal-Samme", "Viroinval", "Virton", "Vissenaken", "Visé", "Vitrival", "Vivegnis", "Vivy", "Vladslo", "Vlamertinge", "Vlekkem", "Vleteren", "Vlezenbeek", "Vliermaal", "Vliermaalroot", "Vlierzele", "Vlijtingen", "Vlimmeren", "Vlissegem", "Vloesberg", "Vodecée", "Vodelée", "Voeren", "Vogenée", "Volkegem", "Vollezele", "Vonêche", "Voorde", "Voormezele", "Voort", "Voroux-Goreux", "Voroux-lez-Liers", "Vorselaar", "Vorsen", "Vorst", "Vosselaar", "Vosselare", "Vossem", "Vottem", "Vrasene", "Vremde", "Vreren", "Vresse-sur-Semois", "Vroenhoven", "Vucht", "Vurste", "Vyle-et-Tharoul", "Waanrode", "Waarbeke", "Waardamme", "Waarloos", "Waarmaarde", "Waarschoot", "Waasmont", "Waasmunster", "Waasten", "Wachtebeke", "Wadelincourt", "Wagnelée", "Waha", "Waillet", "Wakken", "Walcourt", "Walem", "Walhain", "Walhain-Saint-Paul", "Walhorn", "Walsbets", "Walshoutem", "Waltwilder", "Wambeek", "Wancennes", "Wandre", "Wanfercée-Baulet", "Wange", "Wangenies", "Wanlin", "Wanne", "Wannebecq", "Wannegem-Lede", "Wansin", "Wanze", "Wanzele", "Warchin", "Warcoing", "Wardin", "Waregem", "Waremme", "Waret-l'Evêque", "Waret-la-Chaussée", "Warisoulx", "Warnant", "Warnant-Dreye", "Warquignies", "Warsage", "Warzée", "Wasmes", "Wasmes-Audemez-Briffoeil", "Wasmuel", "Wasseiges", "Waterland-Oudeman", "Waterloo", "Watermaal-Bosvoorde", "Watervliet", "Watou", "Wattripont", "Waudrez", "Waulsort", "Wauthier-Braine", "Waver", "Wavreille", "Wayaux", "Ways", "Webbekom", "Wechelderzande", "Weelde", "Weerde", "Weert", "Wegnez", "Weillen", "Weismes", "Welden", "Welkenraedt", "Welle", "Wellen", "Wellin", "Wemmel", "Wenduine", "Werbomont", "Werchter", "Werken", "Werm", "Wervik", "Wespelaar", "Westende", "Westerlo", "Westkapelle", "Westkerke", "Westmalle", "Westmeerbeek", "Westouter", "Westrem", "Westrozebeke", "Westvleteren", "Wetteren", "Wevelgem", "Wez-Velvain", "Wezemaal", "Wezembeek-Oppem", "Wezeren", "Wibrin", "Wichelen", "Widooie", "Wiekevorst", "Wielsbeke", "Wierde", "Wiers", "Wiesme", "Wieze", "Wihogne", "Wihéries", "Wijchmaal", "Wijer", "Wijgmaal", "Wijnegem", "Wijshagen", "Wijtschate", "Wilderen", "Willaupuis", "Willebringen", "Willebroek", "Willemeau", "Willerzie", "Wilrijk", "Wilsele", "Wilskerke", "Wimmertingen", "Winenne", "Wingene", "Winksele", "Wintershoven", "Witry", "Wodecq", "Woesten", "Wolkrange", "Wolvertem", "Wommelgem", "Wommersom", "Wonck", "Wondelgem", "Wontergem", "Wortegem", "Wortegem-Petegem", "Wortel", "Woubrechtegem", "Woumen", "Wulpen", "Wulvergem", "Wulveringem", "Wuustwezel", "Wépion", "Wéris", "Xhendelesse", "Xhendremael", "Xhoris", "Yernée-Fraineux", "Yves-Gomezée", "Yvoir", "Zaffelare", "Zandbergen", "Zande", "Zandhoven", "Zandvliet", "Zandvoorde-Oostende", "Zandvoorde-Zonnebeke", "Zarlardinge", "Zarren", "Zaventem", "Zedelgem", "Zeebrugge", "Zegelsem", "Zele", "Zelem", "Zellik", "Zelzate", "Zemst", "Zepperen", "Zerkegem", "Zevekote", "Zeveneken", "Zeveren", "Zevergem", "Zichem", "Zichen-Zussen-Bolder", "Zillebeke", "Zingem", "Zoerle-Parwijs", "Zoersel", "Zolder", "Zomergem", "Zonhoven", "Zonnebeke", "Zonnegem", "Zottegem", "Zoutenaaie", "Zoutleeuw", "Zuidschote", "Zuienkerke", "Zulte", "Zulzeke", "Zutendaal", "Zwalm", "Zwevegem", "Zwevezele", "Zwijnaarde", "Zwijndrecht", "Zétrud-Lumay", "l'Escaillère", ) provinces = ( "Antwerpen", "Henegouwen", "Limburg", "Luik", "Luxemburg", "Namen", "Oost-Vlaanderen", "Vlaams-Brabant", "Waals-Brabant", "West-Vlaanderen", ) street_name_formats = ("{{first_name}}{{street_suffix}}",) street_address_formats = ("{{street_name}} {{building_number}}",) address_formats = ( "{{street_address}}\n{{postcode}}\n{{city}}", "{{street_address}}\n{{postcode}} {{city}}", ) def administrative_unit(self) -> str: return self.random_element(self.provinces) province = administrative_unit def city(self) -> str: return self.random_element(self.cities)
Provider
python
readthedocs__readthedocs.org
readthedocs/core/settings.py
{ "start": 90, "end": 804 }
class ____: """Class-based settings wrapper.""" @classmethod def load_settings(cls, module_name): """ Export class variables and properties to module namespace. This will export and class variable that is all upper case and doesn't begin with ``_``. These members will be set as attributes on the module ``module_name``. """ self = cls() module = sys.modules[module_name] for member, value in inspect.getmembers(self): if member.isupper() and not member.startswith("_"): if isinstance(value, property): value = value.fget(self) setattr(module, member, value)
Settings
python
pytorch__pytorch
torch/_dynamo/debug_utils.py
{ "start": 22794, "end": 32624 }
class ____: def __init__(self, save_dir: Optional[str], *, stable_hash: bool = False) -> None: self._lines: list[str] = [] # TODO: consider ensuring tensor and storage counters line up? self.storage_counter = itertools.count() self.save_dir = save_dir self.store = ( ContentStoreWriter(save_dir, stable_hash=stable_hash) if save_dir is not None else None ) self.seen_storages: dict[StorageWeakRef, str] = {} def lines(self) -> list[str]: r = [ "def load_args(reader):", ] r.extend(f" {l}" for l in self._lines) # In case we need to change the internal format of load_args # in an FC-breaking way r.append("load_args._version = 0") return r # Storages are untyped, but we need to initialize them with data if # we don't have the real data, so we give a hint saying what kind # of initialization may be appropriate # # If we had a FakeTensor, device_hint tells us what device should be def storage( self, untyped_storage: UntypedStorage, *, device_hint: Optional[torch._prims_common.DeviceLikeType] = None, dtype_hint: Optional[torch.dtype] = None, ) -> str: ws = StorageWeakRef(untyped_storage) v = self.seen_storages.get(ws) if v is not None: return v v = f"buf{next(self.storage_counter)}" maybe_dtype_hint = "" if _dtype_or_default(None) != _dtype_or_default(dtype_hint): maybe_dtype_hint = f", dtype_hint={dtype_hint!r}" # TODO: being optional on device is kind of pointless as the default # is CPU but most repros we care about are CUDA maybe_device = "" device = untyped_storage.device if device.type == "meta": assert device_hint is not None device = device_hint # type: ignore[assignment] if _device_or_default(None) != device: maybe_device = f", device={device!r}" nbytes = untyped_storage.nbytes() storage_hash = None if self.store is not None and untyped_storage.device.type != "meta": storage_hash = self.store.write_storage(untyped_storage) self._lines.append( f"{v} = reader.storage({storage_hash!r}, {nbytes!r}{maybe_device}{maybe_dtype_hint})" ) self.seen_storages[ws] = v return v def tensor(self, name: str, t: torch.Tensor) -> None: from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq storage = self.storage( t.untyped_storage(), dtype_hint=t.dtype, device_hint=t.device ) args = [] # NB: this is positional, must come first if not statically_known_true( sym_eq(_stride_or_default(None, shape=t.shape), t.stride()) ): args.append(str(tuple(t.stride()))) if _dtype_or_default(None) != t.dtype: args.append(f"dtype={t.dtype!r}") if not statically_known_true( _storage_offset_or_default(None) == t.storage_offset() ): args.append(f"storage_offset={t.storage_offset()!r}") tensor_metadata = torch._utils.get_tensor_metadata(t) if tensor_metadata: args.extend(f"{k}={v!r}" for k, v in tensor_metadata.items()) if _requires_grad_or_default(None) != t.requires_grad: args.append(f"requires_grad={t.requires_grad!r}") is_leaf = torch._subclasses.meta_utils.safe_is_leaf(t) if _is_leaf_or_default(None) != is_leaf: args.append(f"is_leaf={is_leaf!r}") self._lines.append( "reader.tensor(" + ", ".join([storage, str(tuple(t.shape)), *args]) + f") # {name}" ) def unsupported(self, name: str, arg: Any) -> None: # NB: Try hard not to /print/ a tensor, that will be very slow self._lines.append(f"# {name} was unsupported type for dumping: {type(arg)}") # Best effort dump as much useful stuff we can lol, in case you want # to repair the repro if isinstance(arg, (list, tuple)): self._lines.append('"""') for i, a in enumerate(arg): name_i = f"{name}[{i}]" if isinstance(a, torch.Tensor): self.tensor(name_i, a) elif isinstance(a, (int, torch.SymInt)): self.symint(name_i, a) else: self.unsupported(name_i, a) self._lines.append('"""') # write out that the arg was filtered out as it is constant def const(self, name: str) -> None: self._lines.append( f"reader.const({name!r}) # {name}, filtered out during compilation" ) # TODO: this doesn't actually symint atm def symint(self, name: str, val: Any) -> None: if isinstance(val, torch.SymInt): val = val.node.hint self._lines.append(f"reader.symint({val!r}) # {name}") def aot_graph_input_parser( func: Callable[[list[Tensor]], list[Tensor]], device: str = "cuda", sym_shapes: Optional[dict[str, int]] = None, default_sym_shape: Optional[int] = None, ) -> dict[str, Any]: """ Takes in a function which has been printed with print_readable() and constructs kwargs to run it. Handles Tensor inputs, Symints, and a graph module which might have tensor constants. Consider a function `forward` defined as follows: def forward(self, primals_1: "f32[1001, 6]", primals_2: "f32[s0]", primals_3: "Sym(s0)",): _tensor_constant0: "i64[4190]" = self._tensor_constant0 # Further implementation kwargs = aot_graph_input_parser(forward) forward(**kwargs) """ from torch.utils._dtype_abbrs import dtype_abbrs dtype_map: dict[str, torch.dtype] = { value: key for key, value in dtype_abbrs.items() } dtype_pattern: str = "|".join(dtype_abbrs.values()) # Extracting the source code from the function source = inspect.getsource(func) # Regular expressions tensor_assignment_regex = rf"(_tensor_constant\d+): \"({dtype_pattern})\[\s*(.*?)\s*\]\" = self\.(_tensor_constant\d+)" tensor_regex = rf"({dtype_pattern})\[\s*(.*?)\s*\]" sym_shape_regex = r"Sym\((s\d+)\)" class TensorContainer: "Container for tensors as attributes" # Dictionary for tensors from annotations kwargs: dict[str, Any] = {} sym_shapes_dict: dict[str, int] = sym_shapes or {} def get_sym_int(symint: str) -> int: torch._check( symint in sym_shapes_dict or default_sym_shape is not None, lambda: f"{symint} not in symbolic_shapes and default sym shape not passed in", ) return sym_shapes_dict.get(symint, default_sym_shape) # type: ignore[return-value] def gen_tensor(shape: torch._prims_common.ShapeType, dtype: torch.dtype) -> Tensor: # Resolve symbolic shapes to concrete values resolved_shape = [] dynamic_dims = [] for i, dim in enumerate(shape): dim = dim.strip() # type: ignore[attr-defined] if "s" in dim: s = get_sym_int(dim) resolved_shape.append(s) dynamic_dims.append(i) else: if dim: resolved_shape.append(int(dim)) constructor = torch.randn if dtype.is_floating_point else torch.zeros out = constructor(resolved_shape, dtype=dtype, device=device) # type: ignore[call-arg] for d in dynamic_dims: torch._dynamo.mark_dynamic(out, d) return out # Parse function annotations for tensor generation annotations = func.__annotations__ for param, annotation in annotations.items(): # Skip 'return' annotation if param == "return": continue match = re.search(tensor_regex, annotation) if match: data_type, shape_str = match.groups() shape = tuple(shape_str.split(",")) dtype = dtype_map[data_type] # pyrefly: ignore [bad-argument-type] kwargs[param] = gen_tensor(shape, dtype) match = re.search(sym_shape_regex, annotation) if match: kwargs[param] = get_sym_int(match.group(1)) if "self" in inspect.signature(func).parameters: container = TensorContainer() kwargs["self"] = container for match in re.finditer(tensor_assignment_regex, source): attr_name, data_type, shape_str, _ = match.groups() shape = tuple(shape_str.split(",")) dtype = dtype_map[data_type] # pyrefly: ignore [bad-argument-type] setattr(container, attr_name, gen_tensor(shape, dtype)) return kwargs def profile_to_file(filename: str) -> Callable[[T], T]: """ Decorator to cProfile a given function and save the result to disk on process exit. Args: filename: filename to save profile to """ prof = cProfile.Profile() filename = os.path.abspath(os.path.expanduser(filename)) def decorator(fn: Any) -> Any: @functools.wraps(fn) def wrapper(*args: Any, **kwargs: Any) -> Any: prof.enable() try: return fn(*args, **kwargs) finally: prof.disable() return wrapper def save_it() -> None: prof.dump_stats(filename) sys.stderr.write( textwrap.dedent( f"""\ Wrote profile to {filename}, view with: snakeviz {filename} """ ) ) atexit.register(save_it) return decorator
InputWriter
python
pennersr__django-allauth
allauth/headless/mfa/views.py
{ "start": 7613, "end": 8240 }
class ____(APIView): input_class = { "POST": LoginWebAuthnInput, } def get(self, request, *args, **kwargs): request_options = webauthn_auth.begin_authentication() return response.WebAuthnRequestOptionsResponse(request, request_options) def post(self, request, *args, **kwargs): authenticator = self.input.cleaned_data["credential"] redirect_url = None login = Login(user=authenticator.user, redirect_url=redirect_url) webauthn_flows.perform_passwordless_login(request, authenticator, login) return AuthenticationResponse(request)
LoginWebAuthnView
python
davidhalter__jedi
jedi/inference/value/dynamic_arrays.py
{ "start": 6991, "end": 7312 }
class ____(_Modification): def py__iter__(self, contextualized_node=None): yield from self._wrapped_value.py__iter__(contextualized_node) yield self._contextualized_key def get_key_values(self): return self._wrapped_value.get_key_values() | self._contextualized_key.infer()
DictModification
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_tm_future_annotations_sync.py
{ "start": 135679, "end": 148092 }
class ____(fixtures.TestBase, testing.AssertsCompiledSQL): __dialect__ = "default" @testing.fixture def dataclass_point_fixture(self, decl_base): @dataclasses.dataclass class Point: x: int y: int class Edge(decl_base): __tablename__ = "edge" id: Mapped[int] = mapped_column(primary_key=True) graph_id: Mapped[int] = mapped_column(ForeignKey("graph.id")) start: Mapped[Point] = composite( Point, mapped_column("x1"), mapped_column("y1") ) end: Mapped[Point] = composite( Point, mapped_column("x2"), mapped_column("y2") ) class Graph(decl_base): __tablename__ = "graph" id: Mapped[int] = mapped_column(primary_key=True) edges: Mapped[List[Edge]] = relationship() decl_base.metadata.create_all(testing.db) return Point, Graph, Edge def test_composite_setup(self, dataclass_point_fixture): Point, Graph, Edge = dataclass_point_fixture with fixture_session() as sess: sess.add( Graph( edges=[ Edge(start=Point(1, 2), end=Point(3, 4)), Edge(start=Point(7, 8), end=Point(5, 6)), ] ) ) sess.commit() self.assert_compile( select(Edge), "SELECT edge.id, edge.graph_id, edge.x1, edge.y1, " "edge.x2, edge.y2 FROM edge", ) with fixture_session() as sess: g1 = sess.scalar(select(Graph)) # round trip! eq_(g1.edges[0].end, Point(3, 4)) def test_named_setup(self, decl_base: Type[DeclarativeBase]): @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped[Address] = composite( Address, mapped_column(), mapped_column(), mapped_column("zip") ) decl_base.metadata.create_all(testing.db) with fixture_session() as sess: sess.add( User( name="user 1", address=Address("123 anywhere street", "NY", "12345"), ) ) sess.commit() with fixture_session() as sess: u1 = sess.scalar(select(User)) # round trip! eq_(u1.address, Address("123 anywhere street", "NY", "12345")) def test_annotated_setup(self, decl_base): global Address @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped["Address"] = composite( mapped_column(), mapped_column(), mapped_column("zip") ) self.assert_compile( select(User), 'SELECT "user".id, "user".name, "user".street, ' '"user".state, "user".zip FROM "user"', dialect="default", ) def test_fwd_ref_plus_no_mapped(self, decl_base): @dataclasses.dataclass class Address: street: str state: str zip_: str with expect_annotation_syntax_error("User.address"): class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: "Address" = composite( # type: ignore mapped_column(), mapped_column(), mapped_column("zip") ) def test_cls_not_composite_compliant(self, decl_base): global Address class Address: def __init__(self, street: int, state: str, zip_: str): pass street: str state: str zip_: str with expect_raises_message( ArgumentError, r"Composite class column arguments must be " r"named unless a dataclass is used", ): class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped[Address] = composite( mapped_column(), mapped_column(), mapped_column("zip") ) def test_fwd_ref_ok_explicit_cls(self, decl_base): global Address @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped["Address"] = composite( Address, mapped_column(), mapped_column(), mapped_column("zip") ) self.assert_compile( select(User), 'SELECT "user".id, "user".name, "user".street, ' '"user".state, "user".zip FROM "user"', ) def test_name_cols_by_str(self, decl_base): @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] street: Mapped[str] state: Mapped[str] # TODO: this needs to be improved, we should be able to say: # zip_: Mapped[str] = mapped_column("zip") # and it should assign to "zip_" for the attribute. not working zip_: Mapped[str] = mapped_column(name="zip", key="zip_") address: Mapped["Address"] = composite( Address, "street", "state", "zip_" ) eq_( User.__mapper__.attrs["address"].props, [ User.__mapper__.attrs["street"], User.__mapper__.attrs["state"], User.__mapper__.attrs["zip_"], ], ) self.assert_compile( select(User), 'SELECT "user".id, "user".name, "user".street, ' '"user".state, "user".zip FROM "user"', ) def test_cls_annotated_setup(self, decl_base): global Address @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped[Address] = composite( mapped_column(), mapped_column(), mapped_column("zip") ) decl_base.metadata.create_all(testing.db) with fixture_session() as sess: sess.add( User( name="user 1", address=Address("123 anywhere street", "NY", "12345"), ) ) sess.commit() with fixture_session() as sess: u1 = sess.scalar(select(User)) # round trip! eq_(u1.address, Address("123 anywhere street", "NY", "12345")) def test_cls_annotated_no_mapped_cols_setup(self, decl_base): global Address @dataclasses.dataclass class Address: street: str state: str zip_: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped[Address] = composite() decl_base.metadata.create_all(testing.db) with fixture_session() as sess: sess.add( User( name="user 1", address=Address("123 anywhere street", "NY", "12345"), ) ) sess.commit() with fixture_session() as sess: u1 = sess.scalar(select(User)) # round trip! eq_(u1.address, Address("123 anywhere street", "NY", "12345")) def test_one_col_setup(self, decl_base): @dataclasses.dataclass class Address: street: str class User(decl_base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column() address: Mapped[Address] = composite(Address, mapped_column()) decl_base.metadata.create_all(testing.db) with fixture_session() as sess: sess.add( User( name="user 1", address=Address("123 anywhere street"), ) ) sess.commit() with fixture_session() as sess: u1 = sess.scalar(select(User)) # round trip! eq_(u1.address, Address("123 anywhere street")) @testing.variation("explicit_col", [True, False]) @testing.variation("use_dataclass", [True, False]) @testing.variation("disable_none_on", [True, False]) def test_optional_composite( self, decl_base, explicit_col, use_dataclass, disable_none_on ): """test #12570""" global Point if use_dataclass: @dataclasses.dataclass class Point: x: Optional[int] y: Optional[int] else: class Point: def __init__(self, x, y): self.x = x self.y = y def __composite_values__(self): return (self.x, self.y) def __eq__(self, other): return ( isinstance(other, Point) and self.x == other.x and self.y == other.y ) class Edge(decl_base): __tablename__ = "edge" id: Mapped[int] = mapped_column(primary_key=True) if disable_none_on: if explicit_col or not use_dataclass: start: Mapped[Optional[Point]] = composite( mapped_column("x1", Integer, nullable=True), mapped_column("y1", Integer, nullable=True), return_none_on=None, ) else: start: Mapped[Optional[Point]] = composite( mapped_column("x1"), mapped_column("y1"), return_none_on=None, ) else: if explicit_col or not use_dataclass: start: Mapped[Optional[Point]] = composite( mapped_column("x1", Integer, nullable=True), mapped_column("y1", Integer, nullable=True), ) else: start: Mapped[Optional[Point]] = composite( mapped_column("x1"), mapped_column("y1") ) eq_(Edge.__table__.c.x1.type._type_affinity, Integer) eq_(Edge.__table__.c.y1.type._type_affinity, Integer) is_true(Edge.__table__.c.x1.nullable) is_true(Edge.__table__.c.y1.nullable) decl_base.metadata.create_all(testing.db) with Session(testing.db) as sess: sess.add(Edge(start=None)) sess.commit() if disable_none_on: eq_( sess.execute(select(Edge.start)).scalar_one(), Point(x=None, y=None), ) else: eq_( sess.execute(select(Edge.start)).scalar_one(), None, )
CompositeTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 27211, "end": 27285 }
class ____(_NoTextCoercion, RoleImpl): __slots__ = ()
ColumnArgumentImpl
python
pypa__warehouse
warehouse/oidc/models/activestate.py
{ "start": 1552, "end": 4949 }
class ____: """ Common functionality for both pending and concrete ActiveState OIDC publishers. """ organization: Mapped[str] = mapped_column(String, nullable=False) activestate_project_name: Mapped[str] = mapped_column(String, nullable=False) actor: Mapped[str] = mapped_column(String, nullable=False) # 'actor' (The ActiveState platform username) is obtained from the user # while configuring the publisher We'll make an api call to ActiveState to # get the 'actor_id' actor_id: Mapped[str] = mapped_column(String, nullable=False) __required_verifiable_claims__: dict[str, CheckClaimCallable[Any]] = { "sub": _check_sub, "organization": oidccore.check_claim_binary(str.__eq__), "project": oidccore.check_claim_binary(str.__eq__), "actor_id": oidccore.check_claim_binary(str.__eq__), # This is the name of the builder in the ActiveState Platform that # publishes things to PyPI. "builder": oidccore.check_claim_invariant("pypi-publisher"), } __unchecked_claims__ = { "actor", "artifact_id", "ingredient", "organization_id", "project_id", "project_path", "project_visibility", } @property def sub(self) -> str: return f"org:{self.organization}:project:{self.activestate_project_name}" @property def builder(self) -> str: return "pypi-publisher" @property def publisher_name(self) -> str: return "ActiveState" @property def project(self) -> str: return self.activestate_project_name @property def publisher_base_url(self) -> str: return urllib.parse.urljoin( _ACTIVESTATE_URL, f"{self.organization}/{self.activestate_project_name}" ) def publisher_url(self, claims: SignedClaims | None = None) -> str: return self.publisher_base_url def stored_claims(self, claims: SignedClaims | None = None) -> dict: return {} def __str__(self) -> str: return self.publisher_url() def exists(self, session: Session) -> bool: return session.query( exists().where( and_( self.__class__.organization == self.organization, self.__class__.activestate_project_name == self.activestate_project_name, self.__class__.actor_id == self.actor_id, ) ) ).scalar() @property def admin_details(self) -> list[tuple[str, str]]: """Returns ActiveState publisher configuration details for admin display.""" return [ ("Organization", self.organization), ("Project", self.activestate_project_name), ("Actor", self.actor), ("Actor ID", self.actor_id), ] @classmethod def lookup_by_claims(cls, session: Session, signed_claims: SignedClaims) -> Self: query: Query = Query(cls).filter_by( organization=signed_claims["organization"], activestate_project_name=signed_claims["project"], actor_id=signed_claims["actor_id"], ) if publisher := query.with_session(session).one_or_none(): return publisher raise InvalidPublisherError("Publisher with matching claims was not found")
ActiveStatePublisherMixin
python
ansible__ansible
lib/ansible/playbook/__init__.py
{ "start": 1206, "end": 4766 }
class ____: def __init__(self, loader): # Entries in the datastructure of a playbook may # be either a play or an include statement self._entries = [] self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict') self._loader = loader self._file_name = None @staticmethod def load(file_name, variable_manager=None, loader=None): pb = Playbook(loader=loader) pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager) return pb def _load_playbook_data(self, file_name, variable_manager, vars=None): if os.path.isabs(file_name): self._basedir = os.path.dirname(file_name) else: self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name))) # set the loaders basedir cur_basedir = self._loader.get_basedir() self._loader.set_basedir(self._basedir) add_all_plugin_dirs(self._basedir) self._file_name = file_name try: ds = self._loader.load_from_file(os.path.basename(file_name), trusted_as_template=True) except UnicodeDecodeError as e: raise AnsibleParserError("Could not read playbook (%s) due to encoding issues: %s" % (file_name, to_native(e))) # check for errors and restore the basedir in case this error is caught and handled if ds is None: self._loader.set_basedir(cur_basedir) raise AnsibleParserError("Empty playbook, nothing to do: %s" % unfrackpath(file_name), obj=ds) elif not isinstance(ds, list): self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must be a list of plays, got a %s instead: %s" % (type(ds), unfrackpath(file_name)), obj=ds) elif not ds: self._loader.set_basedir(cur_basedir) raise AnsibleParserError("A playbook must contain at least one play: %s" % unfrackpath(file_name)) # Parse the playbook entries. For plays, we simply parse them # using the Play() object, and includes are parsed using the # PlaybookInclude() object for entry in ds: if not isinstance(entry, dict): # restore the basedir in case this error is caught and handled self._loader.set_basedir(cur_basedir) raise AnsibleParserError("playbook entries must be either valid plays or 'import_playbook' statements", obj=entry) if any(action in entry for action in C._ACTION_IMPORT_PLAYBOOK): pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader) if pb is not None: self._entries.extend(pb._entries) else: which = entry for k in C._ACTION_IMPORT_PLAYBOOK: if k in entry: which = entry[k] break display.display("skipping playbook '%s' due to conditional test failure" % which, color=C.COLOR_SKIP) else: entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader, vars=vars) self._entries.append(entry_obj) # we're done, so restore the old basedir in the loader self._loader.set_basedir(cur_basedir) def get_loader(self): return self._loader def get_plays(self): return self._entries[:]
Playbook
python
aimacode__aima-python
probability.py
{ "start": 7649, "end": 9988 }
class ____(Agent): """ [Figure 16.9] A simple information gathering agent. The agent works by repeatedly selecting the observation with the highest information value, until the cost of the next observation is greater than its expected benefit.""" def __init__(self, decnet, infer, initial_evidence=None): """decnet: a decision network infer: the preferred method to carry out inference on the given decision network initial_evidence: initial evidence""" self.decnet = decnet self.infer = infer self.observation = initial_evidence or [] self.variables = self.decnet.nodes def integrate_percept(self, percept): """Integrate the given percept into the decision network""" raise NotImplementedError def execute(self, percept): """Execute the information gathering algorithm""" self.observation = self.integrate_percept(percept) vpis = self.vpi_cost_ratio(self.variables) j = max(vpis) variable = self.variables[j] if self.vpi(variable) > self.cost(variable): return self.request(variable) return self.decnet.best_action() def request(self, variable): """Return the value of the given random variable as the next percept""" raise NotImplementedError def cost(self, var): """Return the cost of obtaining evidence through tests, consultants or questions""" raise NotImplementedError def vpi_cost_ratio(self, variables): """Return the VPI to cost ratio for the given variables""" v_by_c = [] for var in variables: v_by_c.append(self.vpi(var) / self.cost(var)) return v_by_c def vpi(self, variable): """Return VPI for a given variable""" vpi = 0.0 prob_dist = self.infer(variable, self.observation, self.decnet).prob for item, _ in prob_dist.items(): post_prob = prob_dist[item] new_observation = list(self.observation) new_observation.append(item) expected_utility = self.decnet.get_expected_utility(variable, new_observation) vpi += post_prob * expected_utility vpi -= self.decnet.get_expected_utility(variable, self.observation) return vpi
InformationGatheringAgent
python
jmcnamara__XlsxWriter
xlsxwriter/exceptions.py
{ "start": 525, "end": 622 }
class ____(XlsxInputError): """Chart must contain at least one data series."""
EmptyChartSeries
python
pytorch__pytorch
test/mobile/test_upgraders.py
{ "start": 329, "end": 2613 }
class ____(TestCase): def _save_load_mobile_module(self, script_module: torch.jit.ScriptModule): buffer = io.BytesIO( script_module._save_to_buffer_for_lite_interpreter( _save_mobile_debug_info=True ) ) buffer.seek(0) mobile_module = _load_for_lite_interpreter(buffer) return mobile_module def _try_fn(self, fn, *args, **kwargs): try: return fn(*args, **kwargs) except Exception as e: return e def test_versioned_div_tensor(self): # noqa: F841 def div_tensor_0_3(self, other): # noqa: F841 if self.is_floating_point() or other.is_floating_point(): return self.true_divide(other) return self.divide(other, rounding_mode="trunc") model_path = ( pytorch_test_dir / "cpp" / "jit" / "upgrader_models" / "test_versioned_div_tensor_v2.ptl" ) _load_for_lite_interpreter(str(model_path)) jit_module_v2 = torch.jit.load(str(model_path)) self._save_load_mobile_module(jit_module_v2) vals = (2.0, 3.0, 2, 3) for val_a, val_b in product(vals, vals): a = torch.tensor((val_a,)) b = torch.tensor((val_b,)) def _helper(m, fn): m_results = self._try_fn(m, a, b) fn_result = self._try_fn(fn, a, b) if isinstance(m_results, Exception): self.assertTrue(isinstance(fn_result, Exception)) else: for result in m_results: print("result: ", result) print("fn_result: ", fn_result) print(result == fn_result) self.assertTrue(result.eq(fn_result)) # self.assertEqual(result, fn_result) # old operator should produce the same result as applying upgrader of torch.div op # _helper(mobile_module_v2, div_tensor_0_3) # latest operator should produce the same result as applying torch.div op # _helper(current_mobile_module, torch.div) if __name__ == "__main__": run_tests()
TestLiteScriptModule
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 2378, "end": 2493 }
class ____(HashAlgorithm): # noqa: N801 name = "sha512-256" digest_size = 32 block_size = 128
SHA512_256
python
scikit-learn__scikit-learn
sklearn/random_projection.py
{ "start": 16104, "end": 20841 }
class ____(BaseRandomProjection): """Reduce dimensionality through Gaussian random projection. The components of the random matrix are drawn from N(0, 1 / n_components). Read more in the :ref:`User Guide <gaussian_random_matrix>`. .. versionadded:: 0.13 Parameters ---------- n_components : int or 'auto', default='auto' Dimensionality of the target projection space. n_components can be automatically adjusted according to the number of samples in the dataset and the bound given by the Johnson-Lindenstrauss lemma. In that case the quality of the embedding is controlled by the ``eps`` parameter. It should be noted that Johnson-Lindenstrauss lemma can yield very conservative estimated of the required number of components as it makes no assumption on the structure of the dataset. eps : float, default=0.1 Parameter to control the quality of the embedding according to the Johnson-Lindenstrauss lemma when `n_components` is set to 'auto'. The value should be strictly positive. Smaller values lead to better embedding and higher number of dimensions (n_components) in the target projection space. compute_inverse_components : bool, default=False Learn the inverse transform by computing the pseudo-inverse of the components during fit. Note that computing the pseudo-inverse does not scale well to large matrices. random_state : int, RandomState instance or None, default=None Controls the pseudo random number generator used to generate the projection matrix at fit time. Pass an int for reproducible output across multiple function calls. See :term:`Glossary <random_state>`. Attributes ---------- n_components_ : int Concrete number of components computed when n_components="auto". components_ : ndarray of shape (n_components, n_features) Random matrix used for the projection. inverse_components_ : ndarray of shape (n_features, n_components) Pseudo-inverse of the components, only computed if `compute_inverse_components` is True. .. versionadded:: 1.1 n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- SparseRandomProjection : Reduce dimensionality through sparse random projection. Examples -------- >>> import numpy as np >>> from sklearn.random_projection import GaussianRandomProjection >>> rng = np.random.RandomState(42) >>> X = rng.rand(25, 3000) >>> transformer = GaussianRandomProjection(random_state=rng) >>> X_new = transformer.fit_transform(X) >>> X_new.shape (25, 2759) """ def __init__( self, n_components="auto", *, eps=0.1, compute_inverse_components=False, random_state=None, ): super().__init__( n_components=n_components, eps=eps, compute_inverse_components=compute_inverse_components, random_state=random_state, ) def _make_random_matrix(self, n_components, n_features): """Generate the random projection matrix. Parameters ---------- n_components : int, Dimensionality of the target projection space. n_features : int, Dimensionality of the original source space. Returns ------- components : ndarray of shape (n_components, n_features) The generated random matrix. """ random_state = check_random_state(self.random_state) return _gaussian_random_matrix( n_components, n_features, random_state=random_state ) def transform(self, X): """Project the data by using matrix product with the random matrix. Parameters ---------- X : {ndarray, sparse matrix} of shape (n_samples, n_features) The input data to project into a smaller dimensional space. Returns ------- X_new : ndarray of shape (n_samples, n_components) Projected array. """ check_is_fitted(self) X = validate_data( self, X, accept_sparse=["csr", "csc"], reset=False, dtype=[np.float64, np.float32], ) return X @ self.components_.T
GaussianRandomProjection
python
pypa__hatch
tests/cli/status/test_status.py
{ "start": 147, "end": 1056 }
class ____: def test_no_project(self, hatch, isolation, config_file, helpers): result = hatch("status") assert result.exit_code == 0, result.output assert result.output == helpers.dedent( f""" [Project] - <no project detected> [Location] - {isolation} [Config] - {config_file.path} """ ) def test_found_project(self, hatch, temp_dir, config_file, helpers): project_file = temp_dir / "pyproject.toml" project_file.touch() with temp_dir.as_cwd(): result = hatch("status") assert result.exit_code == 0, result.output assert result.output == helpers.dedent( f""" [Project] - {temp_dir.name} (current directory) [Location] - {temp_dir} [Config] - {config_file.path} """ )
TestModeLocalDefault
python
huggingface__transformers
src/transformers/models/mimi/modeling_mimi.py
{ "start": 21253, "end": 26115 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: MimiConfig, 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 @staticmethod def compute_default_rope_parameters( config: Optional[MimiConfig] = 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): inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device) position_ids_expanded = position_ids[:, None, :].float() 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(1, 2) 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) # Copied from transformers.models.llama.modeling_llama.rotate_half def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`, *optional*): Deprecated and unused. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed
MimiRotaryEmbedding
python
neetcode-gh__leetcode
python/0200-number-of-islands.py
{ "start": 0, "end": 860 }
class ____: def numIslands(self, grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 islands = 0 visit = set() rows, cols = len(grid), len(grid[0]) def dfs(r, c): if ( r not in range(rows) or c not in range(cols) or grid[r][c] == "0" or (r, c) in visit ): return visit.add((r, c)) directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] for dr, dc in directions: dfs(r + dr, c + dc) for r in range(rows): for c in range(cols): if grid[r][c] == "1" and (r, c) not in visit: islands += 1 dfs(r, c) return islands # DFS O(1) Space and much less code
Solution
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/emr.py
{ "start": 6796, "end": 9125 }
class ____(AwsBaseSensor[EmrServerlessHook]): """ Poll the state of the application until it reaches a terminal state; fails if the application fails. .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/sensor:EmrServerlessApplicationSensor` :param application_id: application_id to check the state of :param target_states: a set of states to wait for, defaults to {'CREATED', 'STARTED'} :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.h """ aws_hook_class = EmrServerlessHook template_fields: Sequence[str] = aws_template_fields( "application_id", ) def __init__( self, *, application_id: str, target_states: set | frozenset = frozenset(EmrServerlessHook.APPLICATION_SUCCESS_STATES), **kwargs: Any, ) -> None: self.target_states = target_states self.application_id = application_id super().__init__(**kwargs) def poke(self, context: Context) -> bool: response = self.hook.conn.get_application(applicationId=self.application_id) state = response["application"]["state"] if state in EmrServerlessHook.APPLICATION_FAILURE_STATES: raise AirflowException( f"EMR Serverless application failed: {self.failure_message_from_response(response)}" ) return state in self.target_states @staticmethod def failure_message_from_response(response: dict[str, Any]) -> str | None: """ Get failure message from response dictionary. :param response: response from AWS API :return: failure message """ return response["application"]["stateDetails"]
EmrServerlessApplicationSensor
python
python-attrs__attrs
src/attr/exceptions.py
{ "start": 98, "end": 456 }
class ____(AttributeError): """ A frozen/immutable instance or attribute have been attempted to be modified. It mirrors the behavior of ``namedtuples`` by using the same error message and subclassing `AttributeError`. .. versionadded:: 20.1.0 """ msg = "can't set attribute" args: ClassVar[tuple[str]] = [msg]
FrozenError
python
euske__pdfminer
pdfminer/layout.py
{ "start": 3977, "end": 4127 }
class ____(LTCurve): def __init__(self, linewidth, p0, p1): LTCurve.__init__(self, linewidth, [p0, p1]) return ## LTRect ##
LTLine
python
django__django
tests/model_options/models/tablespaces.py
{ "start": 1059, "end": 1881 }
class ____(models.Model): title = models.CharField(max_length=50, unique=True) code = models.CharField(max_length=50, unique=True, db_tablespace="idx_tbsp") authors = models.ManyToManyField(Scientist, related_name="articles_written_set") reviewers = models.ManyToManyField( Scientist, related_name="articles_reviewed_set", db_tablespace="idx_tbsp" ) class Meta: db_table = "model_options_articleref" db_tablespace = "tbl_tbsp" managed = False # Also set the tables for automatically created models Authors = Article._meta.get_field("authors").remote_field.through Authors._meta.db_table = "model_options_articleref_authors" Reviewers = Article._meta.get_field("reviewers").remote_field.through Reviewers._meta.db_table = "model_options_articleref_reviewers"
Article
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 15240, "end": 15355 }
class ____(PydanticValueError): msg_template = 'value is not a valid IPv4 or IPv6 interface'
IPvAnyInterfaceError
python
automl__auto-sklearn
test/test_util/test_backend.py
{ "start": 150, "end": 2625 }
class ____(unittest.TestCase): class BackendStub(Backend): def __init__(self): self.__class__ = Backend def setUp(self): self.backend = self.BackendStub() self.backend.internals_directory = "/" @unittest.mock.patch("pickle.load") @unittest.mock.patch("os.path.exists") def test_load_model_by_seed_and_id(self, exists_mock, pickleLoadMock): exists_mock.return_value = False open_mock = unittest.mock.mock_open(read_data="Data") with unittest.mock.patch( "autosklearn.automl_common.common.utils.backend.open", open_mock, create=True, ): seed = 13 idx = 17 budget = 50.0 expected_model = self._setup_load_model_mocks( open_mock, pickleLoadMock, seed, idx, budget ) actual_model = self.backend.load_model_by_seed_and_id_and_budget( seed, idx, budget ) self.assertEqual(expected_model, actual_model) @unittest.mock.patch("pickle.load") @unittest.mock.patch.object(builtins, "open") @unittest.mock.patch("os.path.exists") def test_loads_models_by_identifiers(self, exists_mock, openMock, pickleLoadMock): exists_mock.return_value = True seed = 13 idx = 17 budget = 50.0 expected_model = self._setup_load_model_mocks( openMock, pickleLoadMock, seed, idx, budget ) expected_dict = {(seed, idx, budget): expected_model} actual_dict = self.backend.load_models_by_identifiers([(seed, idx, budget)]) self.assertIsInstance(actual_dict, dict) self.assertDictEqual(expected_dict, actual_dict) def _setup_load_model_mocks(self, openMock, pickleLoadMock, seed, idx, budget): model_path = "/runs/%s_%s_%s/%s.%s.%s.model" % ( seed, idx, budget, seed, idx, budget, ) file_handler = "file_handler" expected_model = "model" fileMock = unittest.mock.MagicMock() fileMock.__enter__.return_value = file_handler openMock.side_effect = ( lambda path, flag: fileMock if path == model_path and flag == "rb" else None ) pickleLoadMock.side_effect = ( lambda fh: expected_model if fh == file_handler else None ) return expected_model
BackendModelsTest
python
pytorch__pytorch
test/distributed/test_store.py
{ "start": 30570, "end": 31104 }
class ____(dist.Store): def __init__(self) -> None: self.appends = [] self.multi_sets = [] self.multi_gets = [] self.multi_get_res = [] super().__init__() def append(self, key, value): self.appends.append((key, value)) def multi_get(self, keys): self.multi_gets.append(keys) return self.multi_get_res.pop(0) def multi_set(self, keys, values): self.multi_sets.append((keys, values)) def has_extended_api(self): return True
DummyStore
python
pytorch__pytorch
torch/utils/data/datapipes/dataframe/dataframe_wrapper.py
{ "start": 540, "end": 3288 }
class ____: @classmethod def create_dataframe(cls, data, columns): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") return _pandas.DataFrame(data, columns=columns) # type: ignore[union-attr] @classmethod def is_dataframe(cls, data): if not _with_pandas(): return False return isinstance(data, _pandas.core.frame.DataFrame) # type: ignore[union-attr] @classmethod def is_column(cls, data): if not _with_pandas(): return False return isinstance(data, _pandas.core.series.Series) # type: ignore[union-attr] @classmethod def iterate(cls, data): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") yield from data.itertuples(index=False) @classmethod def concat(cls, buffer): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") return _pandas.concat(buffer) # type: ignore[union-attr] @classmethod def get_item(cls, data, idx): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") return data[idx : idx + 1] @classmethod def get_len(cls, df): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") return len(df.index) @classmethod def get_columns(cls, df): if not _with_pandas(): raise RuntimeError("DataFrames prototype requires pandas to function") return list(df.columns.values.tolist()) # When you build own implementation just override it with dataframe_wrapper.set_df_wrapper(new_wrapper_class) default_wrapper = PandasWrapper def get_df_wrapper(): return default_wrapper def set_df_wrapper(wrapper) -> None: global default_wrapper default_wrapper = wrapper def create_dataframe(data, columns=None): wrapper = get_df_wrapper() return wrapper.create_dataframe(data, columns) def is_dataframe(data): wrapper = get_df_wrapper() return wrapper.is_dataframe(data) def get_columns(data): wrapper = get_df_wrapper() return wrapper.get_columns(data) def is_column(data): wrapper = get_df_wrapper() return wrapper.is_column(data) def concat(buffer): wrapper = get_df_wrapper() return wrapper.concat(buffer) def iterate(data): wrapper = get_df_wrapper() return wrapper.iterate(data) def get_item(data, idx): wrapper = get_df_wrapper() return wrapper.get_item(data, idx) def get_len(df): wrapper = get_df_wrapper() return wrapper.get_len(df)
PandasWrapper
python
huggingface__transformers
src/transformers/models/timesfm/modular_timesfm.py
{ "start": 3972, "end": 5938 }
class ____(nn.Module): """Generates position embedding for a given 1-d sequence.""" def __init__(self, config: TimesFmConfig): super().__init__() min_timescale = config.min_timescale max_timescale = config.max_timescale self.embedding_dims = config.hidden_size num_timescales = self.embedding_dims // 2 log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) / max(num_timescales - 1, 1) self.register_buffer( "inv_timescales", min_timescale * torch.exp(torch.arange(num_timescales, dtype=torch.float32) * -log_timescale_increment), ) def forward(self, seq_length=None, position=None): """Generates a Tensor of sinusoids with different frequencies. Args: seq_length: an optional Python int defining the output sequence length. if the `position` argument is specified. position: [B, seq_length], optional position for each token in the sequence, only required when the sequence is packed. Returns: [B, seqlen, D] if `position` is specified, else [1, seqlen, D] """ if position is None and seq_length is None: raise ValueError("Either position or seq_length must be provided") if position is None: # [1, seqlen] position = torch.arange(seq_length, dtype=torch.float32, device=self.inv_timescales.device).unsqueeze(0) elif position.ndim != 2: raise ValueError(f"position must be 2-dimensional, got shape {position.shape}") scaled_time = position.view(*position.shape, 1) * self.inv_timescales.view(1, 1, -1) signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2) # Padding to ensure correct embedding dimension signal = F.pad(signal, (0, 0, 0, self.embedding_dims % 2)) return signal
TimesFmPositionalEmbedding
python
kamyu104__LeetCode-Solutions
Python/equalize-strings-by-adding-or-removing-characters-at-ends.py
{ "start": 2056, "end": 2611 }
class ____(object): def minOperations(self, initial, target): """ :type initial: str :type target: str :rtype: int """ if len(initial) < len(target): initial, target = target, initial result = 0 dp = [0]*(len(target)+1) for i in xrange(len(initial)): for j in reversed(xrange(len(target))): dp[j+1] = dp[j]+1 if initial[i] == target[j] else 0 result = max(result, max(dp)) return len(initial)+len(target)-2*result
Solution3
python
huggingface__transformers
src/transformers/models/reformer/configuration_reformer.py
{ "start": 849, "end": 13196 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`ReformerModel`]. It is used to instantiate a Reformer model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the ReFormer [google/reformer-crime-and-punishment](https://huggingface.co/google/reformer-crime-and-punishment) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: attention_head_size (`int`, *optional*, defaults to 64): Dimensionality of the projected key, query and value vectors attn_layers (`list[str]`, *optional*, defaults to `["local", "lsh", "local", "lsh", "local", "lsh"]`): List of attention layer types in ascending order. It can be chosen between a LSHSelfAttention layer (`"lsh"`) and a LocalSelfAttention layer (`"local"`). For more information on LSHSelfAttention layer, see [LSH Self Attention](reformer#lsh-self-attention). For more information on LocalSelfAttention layer, see [Local Self Attention](reformer#local-self-attention). axial_pos_embds (`bool`, *optional*, defaults to `True`): Whether or not to use axial position embeddings. For more information on how axial position embeddings work, see [Axial Position Encodings](reformer#axial-positional-encodings). axial_norm_std (`float`, *optional*, defaults to 1.0): The standard deviation of the normal_initializer for initializing the weight matrices of the axial positional encodings. axial_pos_shape (`list[int]`, *optional*, defaults to `[64, 64]`): The position dims of the axial position encodings. During training, the product of the position dims has to be equal to the sequence length. For more information on how axial position embeddings work, see [Axial Position Encodings](reformer#axial-positional-encodings). axial_pos_embds_dim (`list[int]`, *optional*, defaults to `[64, 192]`): The embedding dims of the axial position encodings. The sum of the embedding dims has to be equal to the hidden size. For more information on how axial position embeddings work, see [Axial Position Encodings](reformer#axial-positional-encodings). chunk_size_lm_head (`int`, *optional*, defaults to 0): The chunk size of the final language model feed forward head layer. A chunk size of 0 means that the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes n < sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed Forward Chunking work?](../glossary#feed-forward-chunking). eos_token_id (`int`, *optional*, defaults to 2): The token id for the end-of-sentence token. feed_forward_size (`int`, *optional*, defaults to 512): Dimensionality of the feed_forward layer in the residual attention block. hash_seed (`int`, *optional*): Seed that can be used to make local sensitive hashing in `LSHSelfAttention` deterministic. This should only be set for testing purposed. For evaluation and training purposes `hash_seed` should be left as `None` to ensure fully random rotations in local sensitive hashing scheme. hidden_act (`str` or `Callable`, *optional*, defaults to `"relu"`): The non-linear activation function (function or string) in the feed forward layer in the residual attention block. If string, `"gelu"`, `"relu"`, `"silu"` and `"gelu_new"` are supported. hidden_dropout_prob (`float`, *optional*, defaults to 0.05): The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. hidden_size (`int`, *optional*, defaults to 256): Dimensionality of the output hidden states of the residual attention blocks. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. is_decoder (`bool`, *optional*, defaults to `False`): Whether or not to use a causal mask in addition to the `attention_mask` passed to [`ReformerModel`]. When using the Reformer for causal language modeling, this argument should be set to `True`. layer_norm_eps (`float`, *optional*, defaults to 1e-12): The epsilon used by the layer normalization layers. local_chunk_length (`int`, *optional*, defaults to 64): Length of chunk which attends to itself in `LocalSelfAttention`. Chunking reduces memory complexity from sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk length (chunked self attention). local_num_chunks_before (`int`, *optional*, defaults to 1): Number of previous neighbouring chunks to attend to in `LocalSelfAttention` layer to itself. local_num_chunks_after (`int`, *optional*, defaults to 0): Number of following neighbouring chunks to attend to in `LocalSelfAttention` layer in addition to itself. local_attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities in `LocalSelfAttention`. lsh_attn_chunk_length (`int`, *optional*, defaults to 64): Length of chunk which attends to itself in `LSHSelfAttention`. Chunking reduces memory complexity from sequence length x sequence length (self attention) to chunk length x chunk length x sequence length / chunk length (chunked self attention). lsh_num_chunks_before (`int`, *optional*, defaults to 1): Number of previous neighbouring chunks to attend to in `LSHSelfAttention` layer to itself. lsh_num_chunks_after (`int`, *optional*, defaults to 0): Number of following neighbouring chunks to attend to in `LSHSelfAttention` layer to itself. lsh_attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1): The dropout ratio for the attention probabilities in `LSHSelfAttention`. max_position_embeddings (`int`, *optional*, defaults to 4096): The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). num_attention_heads (`int`, *optional*, defaults to 12): Number of attention heads for each attention layer in the Transformer encoder. num_buckets (`int` or `list[int]`, *optional*): Number of buckets, the key query vectors can be "hashed into" using the locality sensitive hashing scheme. Each query key vector is hashed into a hash in `1, ..., num_buckets`. The number of buckets can also be factorized into a list for improved memory complexity. In this case, each query key vector is hashed into a hash in `1-1, 1-2, ..., num_buckets[0]-1, ..., num_buckets[0]-num_buckets[1]` if `num_buckets` is factorized into two factors. The number of buckets (or the product the factors) should approximately equal sequence length / lsh_chunk_length. If `num_buckets` not set, a good value is calculated on the fly. num_hashes (`int`, *optional*, defaults to 1): Number of hashing rounds (e.g., number of random rotations) in Local Sensitive Hashing scheme. The higher `num_hashes`, the more accurate the `LSHSelfAttention` becomes, but also the more memory and time intensive the hashing becomes. pad_token_id (`int`, *optional*, defaults to 0): The token id for the padding token. vocab_size (`int`, *optional*, defaults to 320):\ Vocabulary size of the Reformer model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`ReformerModel`]. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie input and output embeddings. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). classifier_dropout (`float`, *optional*): The dropout ratio for the classification head. Examples: ```python >>> from transformers import ReformerConfig, ReformerModel >>> # Initializing a Reformer configuration >>> configuration = ReformerConfig() >>> # Initializing a Reformer model (with random weights) >>> model = ReformerModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ``` """ model_type = "reformer" keys_to_ignore_at_inference = ["past_buckets_states"] attribute_map = {} def __init__( self, attention_head_size=64, attn_layers=["local", "lsh", "local", "lsh", "local", "lsh"], axial_norm_std=1.0, axial_pos_embds=True, axial_pos_shape=[64, 64], axial_pos_embds_dim=[64, 192], chunk_size_lm_head=0, eos_token_id=2, feed_forward_size=512, hash_seed=None, hidden_act="relu", hidden_dropout_prob=0.05, hidden_size=256, initializer_range=0.02, is_decoder=False, layer_norm_eps=1e-12, local_num_chunks_before=1, local_num_chunks_after=0, local_attention_probs_dropout_prob=0.05, local_attn_chunk_length=64, lsh_attn_chunk_length=64, lsh_attention_probs_dropout_prob=0.0, lsh_num_chunks_before=1, lsh_num_chunks_after=0, max_position_embeddings=4096, num_attention_heads=12, num_buckets=None, num_hashes=1, pad_token_id=0, vocab_size=320, tie_word_embeddings=False, use_cache=True, classifier_dropout=None, **kwargs, ): self.hash_seed = hash_seed self.vocab_size = vocab_size self.attention_head_size = attention_head_size self.hidden_size = hidden_size self.num_attention_heads = num_attention_heads self.num_hashes = num_hashes self.num_hidden_layers = len(attn_layers) self.num_buckets = tuple(num_buckets) if isinstance(num_buckets, list) else num_buckets self.lsh_attn_chunk_length = lsh_attn_chunk_length self.local_attn_chunk_length = local_attn_chunk_length self.lsh_num_chunks_after = lsh_num_chunks_after self.lsh_num_chunks_before = lsh_num_chunks_before self.local_num_chunks_after = local_num_chunks_after self.local_num_chunks_before = local_num_chunks_before self.hidden_act = hidden_act self.feed_forward_size = feed_forward_size self.hidden_dropout_prob = hidden_dropout_prob self.lsh_attention_probs_dropout_prob = lsh_attention_probs_dropout_prob self.local_attention_probs_dropout_prob = local_attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.layer_norm_eps = layer_norm_eps self.axial_pos_embds = axial_pos_embds self.axial_pos_shape = tuple(axial_pos_shape) self.axial_pos_embds_dim = tuple(axial_pos_embds_dim) self.axial_norm_std = axial_norm_std self.chunk_size_lm_head = chunk_size_lm_head self.attn_layers = attn_layers self.use_cache = use_cache self.classifier_dropout = classifier_dropout super().__init__( pad_token_id=pad_token_id, eos_token_id=eos_token_id, is_decoder=is_decoder, tie_word_embeddings=tie_word_embeddings, **kwargs, ) __all__ = ["ReformerConfig"]
ReformerConfig
python
catalyst-team__catalyst
catalyst/contrib/losses/recsys.py
{ "start": 5748, "end": 7269 }
class ____(PairwiseLoss): """Adaptive hinge loss function. Takes a set of predictions for implicitly negative items, and selects those that are highest, thus sampling those negatives that are closes to violating the ranking implicit in the pattern of user interactions. Example: .. code-block:: python import torch from catalyst.contrib.losses import recsys pos_score = torch.randn(3, requires_grad=True) neg_scores = torch.randn(5, 3, requires_grad=True) output = recsys.AdaptiveHingeLoss()(pos_score, neg_scores) output.backward() """ def __init__(self) -> None: super().__init__() self._hingeloss = HingeLoss() def forward( self, positive_score: torch.Tensor, negative_scores: torch.Tensor ) -> torch.Tensor: """Forward propagation method for the adaptive hinge loss. Args: positive_score: Tensor containing predictions for known positive items. negative_scores: Iterable of tensors containing predictions for sampled negative items. More tensors increase the likelihood of finding ranking-violating pairs, but risk overfitting. Returns: computed loss """ self._assert_equal_size(positive_score, negative_scores[0]) highest_negative_score, _ = torch.max(negative_scores, 0) return self._hingeloss.forward(positive_score, highest_negative_score.squeeze())
AdaptiveHingeLoss
python
etianen__django-reversion
reversion/errors.py
{ "start": 0, "end": 110 }
class ____(Exception): """Exception thrown when something goes wrong with reverting a model."""
RevertError
python
tensorflow__tensorflow
tensorflow/python/framework/convert_to_constants.py
{ "start": 24699, "end": 27144 }
class ____(_Convertible): """A convertible GraphDef.""" def __init__(self, graph_def): super(_GraphDef, self).__init__(enclosing_graph=None) self._graph_def = graph_def self._nodes = { n.name: _Node.new(node=n, function=None, enclosing_graph=self) for n in graph_def.node } self._functions = { f.signature.name: _Function(f, enclosing_graph=self) for f in graph_def.library.function } self.create_edges() self._converted_function_names = None @property def graph_def(self): return self._graph_def @property def nodes(self): return self._nodes @property def functions(self): return self._functions @property def converted_function_names(self): """Map from original to new function names. In order to avoid conflicts (two functions with the same name, one converted and one not), we need to change the name of every converted function to something that is hopefully unique. Returns: Map from original to new suggested function names. """ if self._converted_function_names is None: parsed_names = [] # List of (id, base_name, original_name) for name in self.functions: elements = name.rsplit("_", 1) if len(elements) == 2 and elements[1].isnumeric(): parsed_names.append((int(elements[1]), elements[0], name)) else: parsed_names.append((-1, name, name)) self._converted_function_names = { name: "{}_frozen_{}".format(base_name, ops.uid()) for (_, base_name, name) in sorted(parsed_names) } return self._converted_function_names def rename_function(self, old_name, new_name): func = self.functions.pop(old_name) func.function.signature.name = new_name self.functions[new_name] = func def is_converted_function(self, function_name): # Only converted functions will be renamed. return (function_name not in self.converted_self().functions) and ( function_name in self.converted_function_names) def converted_self(self): if self._converted_self is None: copied_graph = graph_pb2.GraphDef() copied_graph.CopyFrom(self._graph_def) self._converted_self = _GraphDef(copied_graph) return self._converted_self def create_edges(self): for n in self._nodes.values(): n.create_edges() for f in self._functions.values(): f.create_edges()
_GraphDef
python
getsentry__sentry
tests/sentry/sentry_apps/api/endpoints/test_sentry_app_rotate_secret.py
{ "start": 268, "end": 4659 }
class ____(APITestCase): def setUp(self) -> None: self.application = ApiApplication.objects.create(owner=self.user) self.sentry_app = SentryApp.objects.create( application=self.application, owner_id=self.organization.id, name="a", slug="a" ) self.url = reverse("sentry-api-0-sentry-app-rotate-secret", args=[self.sentry_app.slug]) def test_unauthenticated_call(self) -> None: response = self.client.post(self.url) assert response.status_code == 401 def test_member_call(self) -> None: """ Tests that a low privileged user from the same org cannot rotate a secret. """ other_user = self.create_user() other_member = self.create_member( user=other_user, organization=self.organization, role="member" ) self.login_as(other_member) response = self.client.post(self.url) assert response.status_code == 403 def test_manager_cannot_rotate_privileged_secret(self) -> None: """ Tests that a Manager cannot rotate a secret with a high privileged scope (such as org:admin) """ other_application = ApiApplication.objects.create(owner=self.user) other_app = SentryApp.objects.create( application=other_application, owner_id=self.organization.id, name="b", slug="b", scope_list=("org:admin",), ) self.url = reverse("sentry-api-0-sentry-app-rotate-secret", args=[other_app.slug]) other_user = self.create_user() other_manager = self.create_member( user=other_user, organization=self.organization, role="manager" ) self.login_as(other_manager) response = self.client.post(self.url) assert response.status_code == 403 assert ( "Requested permission of org:admin exceeds requester's permission. Please contact an owner to make the requested change." in response.data["detail"] ) def test_non_owner_call(self) -> None: """ Tests that an authenticated user cannot rotate the secret for an app from other org. """ self.login_as(self.user) other_user = self.create_user() other_org = self.create_organization(owner=other_user) other_app = ApiApplication.objects.create(owner=other_user, name="b") other_sentry_app = SentryApp.objects.create( application=other_app, owner_id=other_org.id, name="b", slug="b" ) response = self.client.post( reverse("sentry-api-0-sentry-app-rotate-secret", args=[other_sentry_app.slug]) ) assert response.status_code == 404 def test_invalid_app_id(self) -> None: self.login_as(self.user) path_with_invalid_id = reverse("sentry-api-0-sentry-app-rotate-secret", args=["invalid"]) response = self.client.post(path_with_invalid_id) assert response.status_code == 404 def test_valid_call(self) -> None: self.login_as(self.user) assert self.sentry_app.application is not None old_secret = self.sentry_app.application.client_secret response = self.client.post(self.url) new_secret = response.data["clientSecret"] assert len(new_secret) == len(old_secret) assert new_secret != old_secret def test_superuser_has_access(self) -> None: superuser = self.create_user(is_superuser=True) self.login_as(user=superuser, superuser=True) assert self.sentry_app.application is not None old_secret = self.sentry_app.application.client_secret response = self.client.post(self.url) new_secret = response.data["clientSecret"] assert len(new_secret) == len(old_secret) assert new_secret != old_secret def test_no_corresponding_application_found(self) -> None: self.login_as(self.user) other_sentry_app = SentryApp.objects.create( application=None, owner_id=self.organization.id, name="c", slug="c" ) response = self.client.post( reverse("sentry-api-0-sentry-app-rotate-secret", args=[other_sentry_app.slug]) ) assert response.status_code == 404 assert "Corresponding application was not found." in response.data["detail"]
SentryAppRotateSecretTest
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-pgvector/destination_pgvector/pgvector_processor.py
{ "start": 2034, "end": 9426 }
class ____(SqlProcessorBase): """A PGVector implementation of the SQL Processor.""" supports_merge_insert = False """We use the emulated merge code path because each primary key has multiple rows (chunks).""" sql_config: PostgresConfig """The configuration for the PGVector processor, including the vector length.""" splitter_config: DocumentSplitterConfig """The configuration for the document splitter.""" file_writer_class = JsonlWriter # No need to override `type_converter_class`. def __init__( self, sql_config: PostgresConfig, splitter_config: DocumentSplitterConfig, embedder_config: EmbeddingConfig, catalog_provider: CatalogProvider, temp_dir: Path, temp_file_cleanup: bool = True, ) -> None: """Initialize the PGVector processor.""" self.splitter_config = splitter_config self.embedder_config = embedder_config super().__init__( sql_config=sql_config, catalog_provider=catalog_provider, temp_dir=temp_dir, temp_file_cleanup=temp_file_cleanup, ) def _get_sql_column_definitions( self, stream_name: str, ) -> dict[str, sqlalchemy.types.TypeEngine]: """Return the column definitions for the given stream. Return the static column definitions for vector index tables. """ _ = stream_name # unused return { DOCUMENT_ID_COLUMN: self.type_converter_class.get_string_type(), CHUNK_ID_COLUMN: self.type_converter_class.get_string_type(), METADATA_COLUMN: self.type_converter_class.get_json_type(), DOCUMENT_CONTENT_COLUMN: self.type_converter_class.get_string_type(), EMBEDDING_COLUMN: Vector(self.embedding_dimensions), } def _emulated_merge_temp_table_to_final_table( self, stream_name: str, temp_table_name: str, final_table_name: str, ) -> None: """Emulate the merge operation using a series of SQL commands. This method varies from the default SqlProcessor implementation in that multiple rows will exist for each primary key. And we need to remove all rows (chunks) for a given primary key before inserting new ones. So instead of using UPDATE and then INSERT, we will DELETE all rows for included primary keys and then call the append implementation to insert new rows. """ columns_list: list[str] = list( self._get_sql_column_definitions(stream_name=stream_name).keys() ) delete_statement = dedent( f""" DELETE FROM {final_table_name} WHERE {DOCUMENT_ID_COLUMN} IN ( SELECT {DOCUMENT_ID_COLUMN} FROM {temp_table_name} ); """ ) append_statement = dedent( f""" INSERT INTO {final_table_name} ({", ".join(columns_list)}) SELECT {", ".join(columns_list)} FROM {temp_table_name}; """ ) with self.get_sql_connection() as conn: # This is a transactional operation to avoid "outages", in case # a user queries the data during the operation. conn.execute(delete_statement) conn.execute(append_statement) def process_record_message( self, record_msg: AirbyteRecordMessage, stream_schema: dict, ) -> None: """Write a record to the cache. We override the SQLProcessor implementation in order to handle chunking, embedding, etc. This method is called for each record message, before the record is written to local file. """ document_chunks, id_to_delete = self.splitter.process(record_msg) _ = id_to_delete # unused embeddings = self.embedder.embed_documents( documents=document_chunks, ) for i, chunk in enumerate(document_chunks, start=0): new_data: dict[str, Any] = { DOCUMENT_ID_COLUMN: self._create_document_id(record_msg), CHUNK_ID_COLUMN: str(uuid.uuid4().int), METADATA_COLUMN: chunk.metadata, DOCUMENT_CONTENT_COLUMN: chunk.page_content, EMBEDDING_COLUMN: embeddings[i], } self.file_writer.process_record_message( record_msg=AirbyteRecordMessage( namespace=record_msg.namespace, stream=record_msg.stream, data=new_data, emitted_at=record_msg.emitted_at, ), stream_schema={ "type": "object", "properties": { DOCUMENT_ID_COLUMN: {"type": "string"}, CHUNK_ID_COLUMN: {"type": "string"}, METADATA_COLUMN: {"type": "object"}, DOCUMENT_CONTENT_COLUMN: {"type": "string"}, EMBEDDING_COLUMN: { "type": "array", "items": {"type": "float"}, }, }, }, ) def _add_missing_columns_to_table( self, stream_name: str, table_name: str, ) -> None: """Add missing columns to the table. This is a no-op because metadata scans do not work with the `VECTOR` data type. """ pass @property def embedder(self) -> embedder.Embedder: return embedder.create_from_config( embedding_config=self.embedder_config, # type: ignore [arg-type] # No common base class processing_config=self.splitter_config, ) @property def embedding_dimensions(self) -> int: """Return the number of dimensions for the embeddings.""" return self.embedder.embedding_dimensions @property def splitter(self) -> DocumentSplitter: return DocumentSplitter( config=self.splitter_config, catalog=self.catalog_provider.configured_catalog, ) def _create_document_id(self, record_msg: AirbyteRecordMessage) -> str: """Create document id based on the primary key values. Returns a random uuid if no primary key is found""" stream_name = record_msg.stream primary_key = self._get_record_primary_key(record_msg=record_msg) if primary_key is not None: return f"Stream_{stream_name}_Key_{primary_key}" return str(uuid.uuid4().int) def _get_record_primary_key(self, record_msg: AirbyteRecordMessage) -> str | None: """Create primary key for the record by appending the primary keys.""" stream_name = record_msg.stream primary_keys = self._get_primary_keys(stream_name) if not primary_keys: return None primary_key = [] for key in primary_keys: try: primary_key.append(str(dpath.get(record_msg.data, key))) except KeyError: primary_key.append("__not_found__") # return a stringified version of all primary keys stringified_primary_key = "_".join(primary_key) return stringified_primary_key
PGVectorProcessor
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 3693, "end": 3901 }
class ____(_VectorIndexConfigCreate): vectorCacheMaxObjects: Optional[int] @staticmethod def vector_index_type() -> VectorIndexType: return VectorIndexType.FLAT
_VectorIndexConfigFlatCreate
python
xlwings__xlwings
xlwings/constants.py
{ "start": 125955, "end": 126219 }
class ____: xlVAlignBottom = -4107 # from enum XlVAlign xlVAlignCenter = -4108 # from enum XlVAlign xlVAlignDistributed = -4117 # from enum XlVAlign xlVAlignJustify = -4130 # from enum XlVAlign xlVAlignTop = -4160 # from enum XlVAlign
VAlign
python
huggingface__transformers
tests/models/gemma3/test_processing_gemma3.py
{ "start": 880, "end": 7801 }
class ____(ProcessorTesterMixin, unittest.TestCase): processor_class = Gemma3Processor @classmethod def _setup_test_attributes(cls, processor): cls.image_token = processor.boi_token @classmethod def _setup_image_processor(cls): image_processor_class = cls._get_component_class_from_processor("image_processor") gemma3_image_processor_kwargs = { "do_pan_and_scan": True, "pan_and_scan_min_crop_size": 256, "pan_and_scan_max_num_crops": 4, "pan_and_scan_min_ratio_to_activate": 1.2, } return image_processor_class(**gemma3_image_processor_kwargs) @classmethod def _setup_tokenizer(cls): tokenizer_class = cls._get_component_class_from_processor("tokenizer") extra_special_tokens = { "image_token": "<image_soft_token>", "boi_token": "<start_of_image>", "eoi_token": "<end_of_image>", } tokenizer = tokenizer_class(SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens) return tokenizer def test_get_num_vision_tokens(self): "Tests general functionality of the helper used internally in vLLM" processor = self.get_processor() output = processor._get_num_multimodal_tokens(image_sizes=[(100, 100), (300, 100), (500, 30)]) self.assertTrue("num_image_tokens" in output) self.assertEqual(len(output["num_image_tokens"]), 3) self.assertTrue("num_image_patches" in output) self.assertEqual(len(output["num_image_patches"]), 3) @staticmethod def prepare_processor_dict(): return { "chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n", "image_seq_length": 3, } # fmt: skip # Override as Gemma3 needs images to be an explicitly nested batch def prepare_image_inputs(self, batch_size: int | None = None): """This function prepares a list of PIL images for testing""" images = super().prepare_image_inputs(batch_size) if isinstance(images, (list, tuple)): images = [[image] for image in images] return images def test_text_with_image_tokens(self): image_processor = self.get_component("image_processor") tokenizer = self.get_component("tokenizer") processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor) text_multi_images = f"{processor.boi_token}{processor.boi_token}Dummy text!" text_single_image = f"{processor.boi_token}Dummy text!" text_no_image = "Dummy text!" image = self.prepare_image_inputs() # If text has no image tokens, image should be `None` with self.assertRaises(ValueError): _ = processor(text=text_no_image, images=image, return_tensors="pt") # We can't be sure what is users intention: if user wants one image per text OR two images for first text and no image for second text with self.assertRaises(ValueError): _ = processor(text=[text_single_image, text_single_image], images=[image, image], return_tensors="pt") # The users is expected to be explicit about which image belong to which text by nesting the images list out_multiimages = processor(text=text_multi_images, images=[image, image], return_tensors="pt") out_batch_oneimage = processor( text=[text_single_image, text_single_image], images=[[image], [image]], return_tensors="pt" ) self.assertListEqual( out_batch_oneimage[self.images_input_name].tolist(), out_multiimages[self.images_input_name].tolist() ) def test_pan_and_scan(self): processor_components = self.prepare_components() processor_kwargs = self.prepare_processor_dict() processor = self.processor_class(**processor_components, **processor_kwargs) input_str = self.prepare_text_inputs(modalities="image") image_input = self.prepare_image_inputs() inputs = processor( text=input_str, images=image_input, return_tensors="pt", do_pan_and_scan=True, image_seq_length=2, pan_and_scan_min_crop_size=10, ) # base image + 4 crops self.assertEqual(len(inputs[self.images_input_name]), 5) baseline = processor( text=input_str, images=image_input, return_tensors="pt", do_pan_and_scan=False, image_seq_length=2, pan_and_scan_min_crop_size=10, ) self.assertGreater(len(inputs[self.text_input_name][0]), len(baseline[self.text_input_name][0])) def test_special_mm_token_truncation(self): """Tests that special vision tokens do not get truncated when `truncation=True` is set.""" processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modalities="image") image_input = self.prepare_image_inputs(batch_size=2) _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=None, padding=True, ) with self.assertRaises(ValueError): _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=True, padding=True, max_length=5, )
Gemma3ProcessorTest
python
vyperlang__vyper
vyper/semantics/types/base.py
{ "start": 621, "end": 1411 }
class ____: def __repr__(self): return f"GenericTypeAcceptor({self.type_})" def __init__(self, type_): self.type_ = type_ def compare_type(self, other): if isinstance(other, self.type_): return True # compare two GenericTypeAcceptors -- they are the same if the base # type is the same return isinstance(other, self.__class__) and other.type_ == self.type_ def to_dict(self): # this shouldn't really appear in the AST type annotations, but it's # there for certain string literals which don't have a known type. this # should be fixed soon by improving type inference. for now just put # *something* in the AST. return {"generic": self.type_.typeclass}
_GenericTypeAcceptor
python
kamyu104__LeetCode-Solutions
Python/two-sum-iv-input-is-a-bst.py
{ "start": 29, "end": 1392 }
class ____(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ class BSTIterator(object): def __init__(self, root, forward): self.__node = root self.__forward = forward self.__s = [] self.__cur = None self.next() def val(self): return self.__cur def next(self): while self.__node or self.__s: if self.__node: self.__s.append(self.__node) self.__node = self.__node.left if self.__forward else self.__node.right else: self.__node = self.__s.pop() self.__cur = self.__node.val self.__node = self.__node.right if self.__forward else self.__node.left break if not root: return False left, right = BSTIterator(root, True), BSTIterator(root, False) while left.val() < right.val(): if left.val() + right.val() == k: return True elif left.val() + right.val() < k: left.next() else: right.next() return False
Solution
python
keras-team__keras
keras/src/saving/saving_api_test.py
{ "start": 417, "end": 4262 }
class ____(test_case.TestCase): def get_model(self): return Sequential( [ layers.Dense(5, input_shape=(3,)), layers.Softmax(), ] ) def test_basic_saving(self): """Test basic model saving and loading.""" model = self.get_model() filepath = os.path.join(self.get_temp_dir(), "test_model.keras") saving_api.save_model(model, filepath) loaded_model = saving_api.load_model(filepath) x = np.random.uniform(size=(10, 3)) self.assertTrue(np.allclose(model.predict(x), loaded_model.predict(x))) def test_invalid_save_format(self): """Test deprecated save_format argument.""" model = self.get_model() with self.assertRaisesRegex( ValueError, "The `save_format` argument is deprecated" ): saving_api.save_model(model, "model.txt", save_format=True) def test_unsupported_arguments(self): """Test unsupported argument during model save.""" model = self.get_model() filepath = os.path.join(self.get_temp_dir(), "test_model.keras") with self.assertRaisesRegex( ValueError, r"The following argument\(s\) are not supported" ): saving_api.save_model(model, filepath, random_arg=True) def test_save_h5_format(self): """Test saving model in h5 format.""" model = self.get_model() filepath_h5 = os.path.join(self.get_temp_dir(), "test_model.h5") # Verify the warning. with mock.patch.object(logging, "warning") as mock_warn: saving_api.save_model(model, filepath_h5) mock_warn.assert_called_once_with( "You are saving your model as an HDF5 file via " "`model.save()` or `keras.saving.save_model(model)`. " "This file format is considered legacy. " "We recommend using instead the native Keras format, " "e.g. `model.save('my_model.keras')` or " "`keras.saving.save_model(model, 'my_model.keras')`. " ) self.assertTrue(os.path.exists(filepath_h5)) os.remove(filepath_h5) def test_save_unsupported_extension(self): """Test saving model with unsupported extension.""" model = self.get_model() with self.assertRaisesRegex( ValueError, "Invalid filepath extension for saving" ): saving_api.save_model(model, "model.png") def test_objects_to_skip(self): model = Sequential( [ layers.Input((3,)), layers.Dense(5), layers.Dense(5), ] ) skip = model.layers[0] filepath = os.path.join(self.get_temp_dir(), "test_model.weights.h5") saving_api.save_weights(model, filepath, objects_to_skip=[skip]) new_model = Sequential( [ layers.Input((3,)), layers.Dense(5), layers.Dense(5), ] ) new_model.load_weights(filepath, objects_to_skip=[new_model.layers[0]]) self.assertNotAllClose( new_model.layers[0].get_weights()[0], model.layers[0].get_weights()[0], ) self.assertAllClose( new_model.layers[0].get_weights()[1], model.layers[0].get_weights()[1], ) saving_api.save_weights(model, filepath) new_model.load_weights(filepath, objects_to_skip=[new_model.layers[0]]) self.assertNotAllClose( new_model.layers[0].get_weights()[0], model.layers[0].get_weights()[0], ) self.assertAllClose( new_model.layers[0].get_weights()[1], model.layers[0].get_weights()[1], )
SaveModelTests
python
django__django
django/http/response.py
{ "start": 23650, "end": 24069 }
class ____(HttpResponse): status_code = 304 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self["content-type"] @HttpResponse.content.setter def content(self, value): if value: raise AttributeError( "You cannot set content to a 304 (Not Modified) response" ) self._container = []
HttpResponseNotModified
python
allegroai__clearml
clearml/backend_interface/session.py
{ "start": 406, "end": 816 }
class ____(object): """Session wrapper interface providing a session property and a send convenience method""" @property @abstractmethod def session(self) -> Any: pass @abstractmethod def send( self, req: Any, ignore_errors: bool = False, raise_on_errors: bool = True, async_enable: bool = False, ) -> Any: pass
SessionInterface
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 109382, "end": 109571 }
class ____(spack.error.SpackError): """ Raised if directory layout is different from buildcache. """ def __init__(self, msg): super().__init__(msg)
NewLayoutException
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/logging_/test_distributed_logging.py
{ "start": 905, "end": 1515 }
class ____(Logger): """Logger to test all-rank logging (i.e. not just rank 0). Logs are saved to local variable `logs`. """ def __init__(self): super().__init__() self.logs = {} self.exp = object() def experiment(self) -> Any: return self.exp def log_metrics(self, metrics: dict[str, float], step: Optional[int] = None): self.logs.update(metrics) def version(self) -> Union[int, str]: return 1 def name(self) -> str: return "AllRank" def log_hyperparams(self, *args, **kwargs) -> None: pass
AllRankLogger
python
automl__auto-sklearn
test/test_pipeline/components/classification/test_adaboost.py
{ "start": 170, "end": 777 }
class ____(BaseClassificationComponentTest): __test__ = True res = dict() res["default_iris"] = 0.93999999999999995 res["default_iris_iterative"] = -1 res["default_iris_proba"] = 0.22452300738472031 res["default_iris_sparse"] = 0.85999999999999999 res["default_digits"] = 0.6879174256223437 res["default_digits_iterative"] = -1 res["default_digits_binary"] = 0.98299939283545845 res["default_digits_multilabel"] = -1 res["default_digits_multilabel_proba"] = -1 sk_mod = sklearn.ensemble.AdaBoostClassifier module = AdaboostClassifier
AdaBoostComponentTest
python
pytorch__pytorch
torch/_dynamo/variables/ctx_manager.py
{ "start": 37136, "end": 38455 }
class ____(ContextWrappingVariable): """ This class represents a set of torch profiler context objects, where Dynamo ignores all the side-effects in the __init__, __enter__ and __exit__ methods by treating the object mostly as a `contextlib.nullcontext`, except for edge cases like the `__enter__` method which returns the object itself rather than `None`, per implementation of the torch objects. """ def __init__(self, **kwargs: Any) -> None: super().__init__(target_values=None, **kwargs) def enter(self, tx: "InstructionTranslator") -> VariableTracker: return self def exit( self, tx: "InstructionTranslator", *args: VariableTracker ) -> VariableTracker: return variables.ConstantVariable.create(None) def module_name(self) -> str: return "contextlib" def fn_name(self) -> str: return "nullcontext" def reconstruct(self, cg: "PyCodegen") -> None: unimplemented( gb_type="torch.profiler object escaped from compiled region", context=str(self), explanation="Dynamo doesn't support compiling a region that returns a torch.profiler context manager.", hints=[ *graph_break_hints.SUPPORTABLE, ], )
ProfilerContextVariable
python
keras-team__keras
keras/src/backend/common/variables_test.py
{ "start": 46492, "end": 47067 }
class ____(test_case.TestCase): def test_standardize_shape_with_torch_size(self): import torch tensor = torch.randn(3, 4, 5) shape = tensor.size() standardized_shape = standardize_shape(shape) self.assertEqual(standardized_shape, (3, 4, 5)) self.assertIs(type(standardized_shape), tuple) for d in standardized_shape: self.assertIsInstance(d, int) @pytest.mark.skipif( backend.backend() != "tensorflow", reason="Tests for standardize_shape with TensorFlow backend", )
TestStandardizeShapeWithTorch
python
ray-project__ray
rllib/offline/estimators/fqe_torch_model.py
{ "start": 631, "end": 11812 }
class ____: """Pytorch implementation of the Fitted Q-Evaluation (FQE) model from https://arxiv.org/abs/1911.06854 """ def __init__( self, policy: Policy, gamma: float, model_config: ModelConfigDict = None, n_iters: int = 1, lr: float = 1e-3, min_loss_threshold: float = 1e-4, clip_grad_norm: float = 100.0, minibatch_size: int = None, polyak_coef: float = 1.0, ) -> None: """ Args: policy: Policy to evaluate. gamma: Discount factor of the environment. model_config: The ModelConfigDict for self.q_model, defaults to: { "fcnet_hiddens": [8, 8], "fcnet_activation": "relu", "vf_share_layers": True, }, n_iters: Number of gradient steps to run on batch, defaults to 1 lr: Learning rate for Adam optimizer min_loss_threshold: Early stopping if mean loss < min_loss_threshold clip_grad_norm: Clip loss gradients to this maximum value minibatch_size: Minibatch size for training Q-function; if None, train on the whole batch polyak_coef: Polyak averaging factor for target Q-function """ self.policy = policy assert isinstance( policy.action_space, Discrete ), f"{self.__class__.__name__} only supports discrete action spaces!" self.gamma = gamma self.observation_space = policy.observation_space self.action_space = policy.action_space if model_config is None: model_config = { "fcnet_hiddens": [32, 32, 32], "fcnet_activation": "relu", "vf_share_layers": True, } self.model_config = model_config self.device = self.policy.device self.q_model: TorchModelV2 = ModelCatalog.get_model_v2( self.observation_space, self.action_space, self.action_space.n, model_config, framework="torch", name="TorchQModel", ).to(self.device) self.target_q_model: TorchModelV2 = ModelCatalog.get_model_v2( self.observation_space, self.action_space, self.action_space.n, model_config, framework="torch", name="TargetTorchQModel", ).to(self.device) self.n_iters = n_iters self.lr = lr self.min_loss_threshold = min_loss_threshold self.clip_grad_norm = clip_grad_norm self.minibatch_size = minibatch_size self.polyak_coef = polyak_coef self.optimizer = torch.optim.Adam(self.q_model.variables(), self.lr) initializer = get_initializer("xavier_uniform", framework="torch") # Hard update target self.update_target(polyak_coef=1.0) def f(m): if isinstance(m, nn.Linear): initializer(m.weight) self.initializer = f def train(self, batch: SampleBatch) -> TensorType: """Trains self.q_model using FQE loss on given batch. Args: batch: A SampleBatch of episodes to train on Returns: A list of losses for each training iteration """ losses = [] minibatch_size = self.minibatch_size or batch.count # Copy batch for shuffling batch = batch.copy(shallow=True) for _ in range(self.n_iters): minibatch_losses = [] batch.shuffle() for idx in range(0, batch.count, minibatch_size): minibatch = batch[idx : idx + minibatch_size] obs = torch.tensor(minibatch[SampleBatch.OBS], device=self.device) actions = torch.tensor( minibatch[SampleBatch.ACTIONS], device=self.device, dtype=int, ) rewards = torch.tensor( minibatch[SampleBatch.REWARDS], device=self.device ) next_obs = torch.tensor( minibatch[SampleBatch.NEXT_OBS], device=self.device ) dones = torch.tensor( minibatch[SampleBatch.TERMINATEDS], device=self.device, dtype=float ) # Compute Q-values for current obs q_values, _ = self.q_model({"obs": obs}, [], None) q_acts = torch.gather(q_values, -1, actions.unsqueeze(-1)).squeeze(-1) next_action_probs = self._compute_action_probs(next_obs) # Compute Q-values for next obs with torch.no_grad(): next_q_values, _ = self.target_q_model({"obs": next_obs}, [], None) # Compute estimated state value next_v = E_{a ~ pi(s)} [Q(next_obs,a)] next_v = torch.sum(next_q_values * next_action_probs, axis=-1) targets = rewards + (1 - dones) * self.gamma * next_v loss = (targets - q_acts) ** 2 loss = torch.mean(loss) self.optimizer.zero_grad() loss.backward() nn.utils.clip_grad.clip_grad_norm_( self.q_model.variables(), self.clip_grad_norm ) self.optimizer.step() minibatch_losses.append(loss.item()) iter_loss = sum(minibatch_losses) / len(minibatch_losses) losses.append(iter_loss) if iter_loss < self.min_loss_threshold: break self.update_target() return losses def estimate_q(self, batch: SampleBatch) -> TensorType: obs = torch.tensor(batch[SampleBatch.OBS], device=self.device) with torch.no_grad(): q_values, _ = self.q_model({"obs": obs}, [], None) actions = torch.tensor( batch[SampleBatch.ACTIONS], device=self.device, dtype=int ) q_values = torch.gather(q_values, -1, actions.unsqueeze(-1)).squeeze(-1) return q_values def estimate_v(self, batch: SampleBatch) -> TensorType: obs = torch.tensor(batch[SampleBatch.OBS], device=self.device) with torch.no_grad(): q_values, _ = self.q_model({"obs": obs}, [], None) # Compute pi(a | s) for each action a in policy.action_space action_probs = self._compute_action_probs(obs) v_values = torch.sum(q_values * action_probs, axis=-1) return v_values def update_target(self, polyak_coef=None): # Update_target will be called periodically to copy Q network to # target Q network, using (soft) polyak_coef-synching. polyak_coef = polyak_coef or self.polyak_coef model_state_dict = self.q_model.state_dict() # Support partial (soft) synching. # If polyak_coef == 1.0: Full sync from Q-model to target Q-model. target_state_dict = self.target_q_model.state_dict() model_state_dict = { k: polyak_coef * model_state_dict[k] + (1 - polyak_coef) * v for k, v in target_state_dict.items() } self.target_q_model.load_state_dict(model_state_dict) def _compute_action_probs(self, obs: TensorType) -> TensorType: """Compute action distribution over the action space. Args: obs: A tensor of observations of shape (batch_size * obs_dim) Returns: action_probs: A tensor of action probabilities of shape (batch_size * action_dim) """ input_dict = {SampleBatch.OBS: obs} seq_lens = torch.ones(len(obs), device=self.device, dtype=int) state_batches = [] if is_overridden(self.policy.action_distribution_fn): try: # TorchPolicyV2 function signature dist_inputs, dist_class, _ = self.policy.action_distribution_fn( self.policy.model, obs_batch=input_dict, state_batches=state_batches, seq_lens=seq_lens, explore=False, is_training=False, ) except TypeError: # TorchPolicyV1 function signature for compatibility with DQN # TODO: Remove this once DQNTorchPolicy is migrated to PolicyV2 dist_inputs, dist_class, _ = self.policy.action_distribution_fn( self.policy, self.policy.model, input_dict=input_dict, state_batches=state_batches, seq_lens=seq_lens, explore=False, is_training=False, ) else: dist_class = self.policy.dist_class dist_inputs, _ = self.policy.model(input_dict, state_batches, seq_lens) action_dist = dist_class(dist_inputs, self.policy.model) assert isinstance( action_dist.dist, torch.distributions.categorical.Categorical ), "FQE only supports Categorical or MultiCategorical distributions!" action_probs = action_dist.dist.probs return action_probs def get_state(self) -> Dict[str, Any]: """Returns the current state of the FQE Model.""" return { "policy_state": self.policy.get_state(), "model_config": self.model_config, "n_iters": self.n_iters, "lr": self.lr, "min_loss_threshold": self.min_loss_threshold, "clip_grad_norm": self.clip_grad_norm, "minibatch_size": self.minibatch_size, "polyak_coef": self.polyak_coef, "gamma": self.gamma, "q_model_state": self.q_model.state_dict(), "target_q_model_state": self.target_q_model.state_dict(), } def set_state(self, state: Dict[str, Any]) -> None: """Sets the current state of the FQE Model. Args: state: A state dict returned by `get_state()`. """ self.n_iters = state["n_iters"] self.lr = state["lr"] self.min_loss_threshold = state["min_loss_threshold"] self.clip_grad_norm = state["clip_grad_norm"] self.minibatch_size = state["minibatch_size"] self.polyak_coef = state["polyak_coef"] self.gamma = state["gamma"] self.policy.set_state(state["policy_state"]) self.q_model.load_state_dict(state["q_model_state"]) self.target_q_model.load_state_dict(state["target_q_model_state"]) @classmethod def from_state(cls, state: Dict[str, Any]) -> "FQETorchModel": """Creates a FQE Model from a state dict. Args: state: A state dict returned by `get_state`. Returns: An instance of the FQETorchModel. """ policy = Policy.from_state(state["policy_state"]) model = cls( policy=policy, gamma=state["gamma"], model_config=state["model_config"] ) model.set_state(state) return model
FQETorchModel
python
getsentry__sentry
src/sentry/api/bases/organization.py
{ "start": 8638, "end": 8899 }
class ____(OrganizationPermission): scope_map = { "GET": ["org:read", "org:write", "org:admin"], "POST": ["org:read", "org:write", "org:admin"], "DELETE": ["org:write", "org:admin"], }
OrganizationFlagWebHookSigningSecretPermission
python
uqfoundation__dill
dill/tests/test_recursive.py
{ "start": 1636, "end": 1825 }
class ____(object): def __init__(self): self.child = Model() self.trigger = partial(get_trigger, self) self.child.trigger = partial(get_trigger, self.child)
Machine
python
tensorflow__tensorflow
tensorflow/python/distribute/checkpointing_test.py
{ "start": 1076, "end": 2949 }
class ____(test.TestCase, parameterized.TestCase): @combinations.generate( combinations.combine( distribution=[ strategy_combinations.mirrored_strategy_with_one_cpu, strategy_combinations.mirrored_strategy_with_gpu_and_cpu, strategy_combinations.tpu_strategy, strategy_combinations.tpu_strategy_packed_var, strategy_combinations.central_storage_strategy_with_two_gpus, ], mode=["eager"])) def testInitializeFromCheckpoint(self, distribution): variable_shape = [5] save_checkpoint = trackable_utils.Checkpoint(v=variables_lib.Variable( array_ops.ones(variable_shape))) save_path = save_checkpoint.save( os.path.join(self.get_temp_dir(), "checkpoint")) with distribution.scope(): restore_checkpoint = trackable_utils.Checkpoint() restore_checkpoint.restore(save_path) initial_value = restore_checkpoint._preload_simple_restoration( "v") v = variables_lib.Variable(initial_value) # Check that the variable is now tagged as restored. `Checkpoint` then # knows it doesn't have to restore `v`'s value when it's assigned to an # object. self.assertGreater(v._update_uid, 0) self.assertAllClose(array_ops.ones(variable_shape), v) v.assign(array_ops.zeros(variable_shape)) # Assignment to an object should not trigger restoration, since we already # restored the object through an initializer. This wouldn't be a # correctness issue, but it would mean that models would use twice as much # memory when loading (the buffer already assigned to the variable, and # the new restoration). restore_checkpoint.v = v self.assertAllClose(array_ops.zeros(variable_shape), v) if __name__ == "__main__": test.main()
TrainingCheckpointTests
python
tensorflow__tensorflow
tensorflow/compiler/tests/function_test.py
{ "start": 1044, "end": 4818 }
class ____(xla_test.XLATestCase): def testFunction(self): """Executes a simple TensorFlow function.""" def APlus2B(a, b): return a + b * 2 aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) bval = np.array([5, 6, 7, 8]).reshape([2, 2]).astype(np.float32) expected = APlus2B(aval, bval) with self.session(): @function.Defun(dtypes.float32, dtypes.float32) def Foo(a, b): return APlus2B(a, b) a = constant_op.constant(aval, name="a") b = constant_op.constant(bval, name="b") with self.test_scope(): call_f = Foo(a, b) result = self.evaluate(call_f) self.assertAllClose(result, expected, rtol=1e-3) def testNestedFunctions(self): """Executes two nested TensorFlow functions.""" def TimesTwo(x): return x * 2 def APlus2B(a, b): return a + TimesTwo(b) aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) bval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) expected = APlus2B(aval, bval) with self.session(): @function.Defun(dtypes.float32, dtypes.float32) def Foo(a, b): return APlus2B(a, b) a = constant_op.constant(aval, name="a") b = constant_op.constant(bval, name="b") with self.test_scope(): call_g = Foo(a, b) result = self.evaluate(call_g) self.assertAllClose(result, expected, rtol=1e-3) def testFunctionMultipleRetvals(self): """Executes a function with multiple return values.""" # This function will run on the XLA device def Func(a, b): return a + b, a - b aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) bval = np.array([5, 6, 7, 8]).reshape([2, 2]).astype(np.float32) expected = Func(aval, bval) with self.session(): @function.Defun(dtypes.float32, dtypes.float32) def Foo(a, b): return Func(a, b) a = constant_op.constant(aval, name="a") b = constant_op.constant(bval, name="b") with self.test_scope(): call_f = Foo(a, b) result = self.evaluate(call_f) self.assertAllClose(result, expected, rtol=1e-3) def testCompileTimeConstantsInDefun(self): """Tests that XLA handles compile-time constants in defuns.""" with self.session() as sess: @function.Defun(dtypes.float32, dtypes.int32, dtypes.int32) def Foo(a, c, d): # c and d must be known at compile time x = array_ops.slice(a, c, d) return x a = array_ops.placeholder(dtypes.float32) c = array_ops.placeholder(dtypes.int32, shape=[4]) d = array_ops.placeholder(dtypes.int32, shape=[4]) with self.test_scope(): call_f = Foo(a, c, d) result = sess.run(call_f, feed_dict={ a: np.ones([1, 4, 4, 1]), c: [0, 0, 0, 0], d: [1, 2, 2, 1]}) self.assertAllEqual(np.ones([1, 2, 2, 1]), result) # TODO(b/36139787): Re-enable this test when noinline works again. def DISABLED_testFunctionsNoInline(self): @function.Defun(dtypes.float32, noinline=True) def TimesTwo(x): return x * 2 @function.Defun(dtypes.float32, dtypes.float32) def APlus2B(a, b): return a + TimesTwo(b) aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) bval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) expected = aval + bval * 2 with self.session() as sess: with self.test_scope(): a = array_ops.placeholder(dtypes.float32, name="a") b = array_ops.placeholder(dtypes.float32, name="b") call = APlus2B(a, b) result = sess.run(call, {a: aval, b: bval}) self.assertAllClose(result, expected, rtol=1e-3) if __name__ == "__main__": googletest.main()
FunctionTest
python
spyder-ide__spyder
spyder/plugins/profiler/widgets/profiler_data_tree.py
{ "start": 7675, "end": 14796 }
class ____(QTreeWidgetItem): """Item to show in the tree. It represent a function call.""" def __init__(self, parent, item_key, profile_data, compare_data, icon_list, index_dict): QTreeWidgetItem.__init__(self, parent) self.item_key = item_key self.index_dict = index_dict # Order is from profile data self.total_calls, self.local_time, self.total_time = profile_data[1:4] ( filename, line_number, function_name, file_and_line, node_type, ) = self.function_info(item_key) self.function_name = function_name self.filename = filename self.line_number = line_number self.set_item_data(filename, line_number) self.setIcon(self.index_dict["function_name"], icon_list[node_type]) self.set_tooltips() data = { "function_name": function_name, "total_time": self.format_measure(self.total_time), "local_time": self.format_measure(self.local_time), "number_calls": self.format_measure(self.total_calls), "file:line": file_and_line } self.set_data(data) alignment = { "total_time": Qt.AlignRight, "local_time": Qt.AlignRight, "number_calls": Qt.AlignRight, } self.set_alignment(alignment) if self.is_recursive(): self.setData( self.index_dict["file:line"], Qt.DisplayRole, "(%s)" % _("recursion"), ) self.setDisabled(True) if compare_data is None: return diff_data = {} diff_colors = {} # Keep same order as profile data compare_keys = [ "unused", "number_calls_diff", "local_time_diff", "total_time_diff" ] for i in range(1, 4): diff_str, color = self.color_diff( profile_data[i] - compare_data[i] ) diff_data[compare_keys[i]] = diff_str diff_colors[compare_keys[i]] = color self.set_data(diff_data) self.set_color(diff_colors) diff_alignment = { "total_time_diff": Qt.AlignLeft, "local_time_diff": Qt.AlignLeft, "number_calls_diff": Qt.AlignLeft } self.set_alignment(diff_alignment) def set_data(self, data): """Set data in columns.""" for k, v in data.items(): self.setData(self.index_dict[k], Qt.DisplayRole, v) def set_color(self, colors): """Set colors""" for k, v in colors.items(): self.setForeground(self.index_dict[k], QColor(v)) def set_alignment(self, alignment): """Set alignment.""" for k, v in alignment.items(): self.setTextAlignment(self.index_dict[k], v) @staticmethod def color_diff(difference): """Color difference.""" diff_str = "" color = "black" if difference: color, sign = ( (SpyderPalette.COLOR_SUCCESS_1, '-') if difference < 0 else (SpyderPalette.COLOR_ERROR_1, '+') ) diff_str = '{}{}'.format( sign, TreeWidgetItem.format_measure(difference) ) return diff_str, color @staticmethod def format_measure(measure): """Get format and units for data coming from profiler task.""" # Convert to a positive value. measure = abs(measure) # For number of calls if isinstance(measure, int): return str(measure) # For time measurements if 1.e-9 < measure <= 1.e-6: measure = u"{0:.2f} ns".format(measure / 1.e-9) elif 1.e-6 < measure <= 1.e-3: measure = u"{0:.2f} \u03BCs".format(measure / 1.e-6) elif 1.e-3 < measure <= 1: measure = u"{0:.2f} ms".format(measure / 1.e-3) elif 1 < measure <= 60: measure = u"{0:.2f} s".format(measure) elif 60 < measure <= 3600: m, s = divmod(measure, 3600) if s > 60: m, s = divmod(measure, 60) s = str(s).split(".")[-1] measure = u"{0:.0f}.{1:.2s} min".format(m, s) else: h, m = divmod(measure, 3600) if m > 60: m /= 60 measure = u"{0:.0f}h:{1:.0f}min".format(h, m) return measure def __lt__(self, otherItem): column = self.treeWidget().sortColumn() try: if column == self.index_dict["total_time"]: return self.total_time > otherItem.total_time if column == self.index_dict["local_time"]: return self.local_time > otherItem.local_time return float(self.text(column)) > float(otherItem.text(column)) except ValueError: return self.text(column) > otherItem.text(column) def set_item_data(self, filename, line_number): """Set tree item user data: filename (string) and line_number (int)""" # separator between filename and linenumber SEP = r"<[=]>" # (must be improbable as a filename) set_item_user_text(self, '%s%s%d' % (filename, SEP, line_number)) def function_info(self, functionKey): """Returns processed information about the function's name and file.""" node_type = 'function' filename, line_number, function_name = functionKey if function_name == '<module>': module_path, module_name = osp.split(filename) node_type = 'module' if module_name == '__init__.py': module_path, module_name = osp.split(module_path) function_name = '<' + module_name + '>' if not filename or filename == '~': file_and_line = '(built-in)' node_type = 'builtin' else: if function_name == '__init__': node_type = 'constructor' file_and_line = '%s : %d' % (filename, line_number) return filename, line_number, function_name, file_and_line, node_type def is_recursive(self): """Returns True is a function is a descendant of itself.""" ancestor = self.parent() while ancestor: if ( self.function_name == ancestor.function_name and self.filename == ancestor.filename and self.line_number == ancestor.line_number ): return True else: ancestor = ancestor.parent() return False def set_tooltips(self): """Set item tooltips.""" self.setToolTip(self.index_dict["function_name"], self.function_name) if not self.filename or self.filename == '~': fname_tip = "(built-in)" else: fname_tip = f"{self.filename}:{self.line_number}" self.setToolTip(self.index_dict["file:line"], fname_tip)
TreeWidgetItem
python
getsentry__sentry
src/sentry/testutils/helpers/notifications.py
{ "start": 2214, "end": 11566 }
class ____(DummyNotification): group: Group def get_notification_title( self, provider: ExternalProviders, context: Mapping[str, Any] | None = None ) -> str: assert context is not None some_value = context["some_field"] return f"Notification Title with {some_value}" def build_notification_footer(self, *args) -> str: return "Notification Footer" def get_message_description(self, recipient: Actor, provider: ExternalProviders) -> str: return "Message Description" def get_title_link(self, *args): from sentry.integrations.messaging.message_builder import get_title_link return get_title_link(self.group, None, False, True, self, ExternalProviders.SLACK) TEST_ISSUE_OCCURRENCE = IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["some-fingerprint"], "something bad happened", "it was bad", "1234", {"Test": 123}, [ IssueEvidence("Attention", "Very important information!!!", True), IssueEvidence("Evidence 2", "Not important", False), IssueEvidence("Evidence 3", "Nobody cares about this", False), ], ProfileFileIOGroupType, datetime.now(UTC), "info", "/api/123/", ) TEST_FEEDBACK_ISSUE_OCCURENCE = IssueOccurrence( id=uuid.uuid4().hex, project_id=1, event_id=uuid.uuid4().hex, fingerprint=["c" * 32], issue_title="User Feedback", subtitle="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel aliquam velit, nec condimentum mi. Maecenas accumsan, nunc ac venenatis hendrerit, mi libero facilisis nunc, fringilla molestie dui est vulputate diam. Duis ac justo euismod, sagittis est at, bibendum purus. Praesent nec tortor vel ante accumsan lobortis. Morbi mollis augue nec dolor feugiat congue. Nullam eget blandit nisi. Sed in arcu odio. Aenean malesuada tortor quis felis dapibus congue.d", culprit="api/123", resource_id="1234", evidence_data={ "contact_email": "test@test.com", "message": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel aliquam velit, nec condimentum mi. Maecenas accumsan, nunc ac venenatis hendrerit, mi libero facilisis nunc, fringilla molestie dui est vulputate diam. Duis ac justo euismod, sagittis est at, bibendum purus. Praesent nec tortor vel ante accumsan lobortis. Morbi mollis augue nec dolor feugiat congue. Nullam eget blandit nisi. Sed in arcu odio. Aenean malesuada tortor quis felis dapibus congue.", "name": "Test Name", }, evidence_display=[ IssueEvidence("contact_email", "test@test.com", False), IssueEvidence( "message", "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vel aliquam velit, nec condimentum mi. Maecenas accumsan, nunc ac venenatis hendrerit, mi libero facilisis nunc, fringilla molestie dui est vulputate diam. Duis ac justo euismod, sagittis est at, bibendum purus. Praesent nec tortor vel ante accumsan lobortis. Morbi mollis augue nec dolor feugiat congue. Nullam eget blandit nisi. Sed in arcu odio. Aenean malesuada tortor quis felis dapibus congue.", True, ), IssueEvidence("name", "Test Name", False), ], type=FeedbackGroup, detection_time=datetime.now(UTC), level="info", ) TEST_PERF_ISSUE_OCCURRENCE = IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["some-fingerprint"], "N+1 Query", "it was bad", "1234", {"Test": 123}, [ IssueEvidence( "db", "db - SELECT `books_author`.`id`, `books_author`.`name` FROM `books_author` WHERE `books_author`.`id` = %s LIMIT 21", True, ), ], PerformanceNPlusOneGroupType, datetime.now(UTC), "info", "/api/123/", ) SAMPLE_TO_OCCURRENCE_MAP = { "transaction-slow-db-query": IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["ad800f7f33d223e714d718cb4e7d3ce1"], "Slow DB Query", 'SELECT "marketing_information"."id", "marketing_information"."email", "marketing_information"."subscribed", "marketing_information"."updated_at", "marketing_information"."category", "marketing_information"."opted_out" FROM "marketing_information" WHERE "marketing_information"."email" IN (SELECT U0."email" FROM "users" U0 WHERE U0."user_id" = %s)', None, { "op": "db", "cause_span_ids": [], "parent_span_ids": [], "offender_span_ids": [ "b3da1046fed392a3", ], "transaction_name": "", "num_repeating_spans": "1", "repeating_spans": 'SELECT "marketing_information"."id", "marketing_information"."email", "marketing_information"."subscribed", "marketing_information"."updated_at", "marketing_information"."category", "marketing_information"."opted_out" FROM "marketing_information" WHERE "marketing_information"."email" IN (SELECT U0."email" FROM "users" U0 WHERE U0."user_id" = %s)', "repeating_spans_compact": 'SELECT "marketing_information"."id", "marketing_information"."email", "marketing_information"."subscribed", "marketing_information"."updated_at", "marketing_information"."category", "marketing_information"."opted_out" FROM "marketing_information" WHERE "marketing_information"."email" IN (SELECT U0."email" FROM "users" U0 WHERE U0."user_id" = %s)', }, [], PerformanceSlowDBQueryGroupType, datetime.now(UTC), "info", "/api/marketing-info/", ), "transaction-n-plus-one-api-call": IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["fed5919bb4cbfc1883a7284fb5946e17"], "N+1 API Call", "SELECT `books_author`.`id`, `books_author`.`name` FROM `books_author` WHERE `books_author`.`id` = %s LIMIT 21", None, { "op": "http.client", "cause_span_ids": [], "parent_span_ids": ["829d17842d952371"], "offender_span_ids": [ "b2af9392df36fa1f", "a39c22ce65e378cc", "ae58828e4fdd0bba", "8869e7e96076fa88", "ac71c2e69245f37d", "8e7189a4f1e24ac3", "ba5183ea752ce85a", "a530576977ba0714", "bd5f728e61f667cf", "9e87e2127c3a3136", "b38bff8a7d07b1bc", "ae5b2d34409bb315", "918be77fbfd326ca", "afa8a8b18afbad59", ], "transaction_name": "/", "num_repeating_spans": "14", "repeating_spans": "/author/278/book", "repeating_spans_compact": "/author/278/book", "parameters": ["{book_id: 96,44,22,43,79,50,55,48,90,69,1,36,78,67}"], }, [], PerformanceNPlusOneAPICallsGroupType, datetime.now(UTC), "info", "/books/", ), "transaction-n-plus-one": IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["e714d718cb4e7d3ce1ad800f7f33d223"], "N+1 Query", "SELECT `books_author`.`id`, `books_author`.`name` FROM `books_author` WHERE `books_author`.`id` = %s LIMIT 21", None, { "transaction_name": "/books/", "op": "db", "parent_span_ids": ["8dd7a5869a4f4583"], "parent_span": "django.view - index", "cause_span_ids": ["9179e43ae844b174"], "offender_span_ids": [ "b8be6138369491dd", "b2d4826e7b618f1b", "b3fdeea42536dbf1", "b409e78a092e642f", "86d2ede57bbf48d4", "8e554c84cdc9731e", "94d6230f3f910e12", "a210b87a2191ceb6", "88a5ccaf25b9bd8f", "bb32cf50fc56b296", ], "repeating_spans": "db - SELECT `books_author`.`id`, `books_author`.`name` FROM `books_author` WHERE `books_author`.`id` = %s LIMIT 21", "repeating_spans_compact": "SELECT `books_author`.`id`, `books_author`.`name` FROM `books_author` WHERE `books_author`.`id` = %s LIMIT 21", "num_repeating_spans": "10", }, [], PerformanceNPlusOneGroupType, datetime.now(UTC), "info", "/books/", ), "transaction-render-blocking-asset": IssueOccurrence( uuid.uuid4().hex, 1, uuid.uuid4().hex, ["9cef2831e86bdad927f4f2d0639e09a7eb9642f6"], "Large Render Blocking Asset", "/asset.js", None, { "op": "resource.script", "parent_span_ids": [], "cause_span_ids": [], "offender_span_ids": ["5b35bf3458d54fd7"], "transaction_name": "", "slow_span_description": "/asset.js", "slow_span_duration": 1000.0, "transaction_duration": 172422171096.56, "fcp": 2500.0, "repeating_spans": "resource.script - /asset.js", "repeating_spans_compact": "/asset.js", }, [], PerformanceRenderBlockingAssetSpanGroupType, datetime.now(UTC), "info", "/render-blocking-asset/", ), }
DummyNotificationWithMoreFields
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_variables.py
{ "start": 17791, "end": 23890 }
class ____(TestVariableEndpoint): @pytest.mark.enable_redact @pytest.mark.parametrize( ("body", "expected_response"), [ ( { "key": "new variable key", "value": "new variable value", "description": "new variable description", }, { "key": "new variable key", "value": "new variable value", "description": "new variable description", "is_encrypted": True, "team_id": None, }, ), ( { "key": "another_password", "value": "password_value", "description": "another password", }, { "key": "another_password", "value": "***", "description": "another password", "is_encrypted": True, "team_id": None, }, ), ( { "key": "another value with sensitive information", "value": '{"password": "new_password"}', "description": "some description", }, { "key": "another value with sensitive information", "value": '{"password": "***"}', "description": "some description", "is_encrypted": True, "team_id": None, }, ), ( { "key": "empty value variable", "value": "", "description": "some description", }, { "key": "empty value variable", "value": "", "description": "some description", "is_encrypted": True, "team_id": None, }, ), ], ) def test_post_should_respond_201(self, test_client, session, body, expected_response): self.create_variables() response = test_client.post("/variables", json=body) assert response.status_code == 201 assert response.json() == expected_response check_last_log(session, dag_id=None, event="post_variable", logical_date=None) def test_post_with_team_should_respond_201(self, test_client, testing_team, session): self.create_variables() body = { "key": "new variable key", "value": "new variable value", "description": "new variable description", "team_id": str(testing_team.id), } response = test_client.post("/variables", json=body) assert response.status_code == 201 assert response.json() == { "key": "new variable key", "value": "new variable value", "description": "new variable description", "is_encrypted": True, "team_id": str(testing_team.id), } check_last_log(session, dag_id=None, event="post_variable", logical_date=None) def test_post_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.post( "/variables", json={ "key": "new variable key", "value": "new variable value", "description": "new variable description", }, ) assert response.status_code == 401 def test_post_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.post( "/variables", json={ "key": "new variable key", "value": "new variable value", "description": "new variable description", }, ) assert response.status_code == 403 def test_post_should_respond_409_when_key_exists(self, test_client, session): self.create_variables() # Attempting to post a variable with an existing key response = test_client.post( "/variables", json={ "key": TEST_VARIABLE_KEY, "value": "duplicate value", "description": "duplicate description", }, ) assert response.status_code == 409 body = response.json() assert body["detail"] == f"The Variable with key: `{TEST_VARIABLE_KEY}` already exists" def test_post_should_respond_422_when_key_too_large(self, test_client): large_key = "a" * 251 # Exceeds the maximum length of 250 body = { "key": large_key, "value": "some_value", "description": "key too large", } response = test_client.post("/variables", json=body) assert response.status_code == 422 assert response.json() == { "detail": [ { "type": "string_too_long", "loc": ["body", "key"], "msg": "String should have at most 250 characters", "input": large_key, "ctx": {"max_length": 250}, } ] } @pytest.mark.parametrize( "body", [ { "key": "new variable key", "value": "new variable value", "description": "new variable description", }, ], ) @mock.patch("airflow.api_fastapi.logging.decorators._mask_variable_fields") def test_mask_variable_fields_called(self, mock_mask_variable_fields, test_client, body): mock_mask_variable_fields.return_value = {**body, "method": "POST"} response = test_client.post("/variables", json=body) assert response.status_code == 201 mock_mask_variable_fields.assert_called_once_with(body)
TestPostVariable
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
{ "start": 94210, "end": 96144 }
class ____(GeneratedAirbyteSource): @public def __init__( self, name: str, client_id: str, refresh_token: str, developer_token: str, reports_start_date: str, auth_method: Optional[str] = None, tenant_id: Optional[str] = None, client_secret: Optional[str] = None, ): """Airbyte Source for Bing Ads. Documentation can be found at https://docs.airbyte.com/integrations/sources/bing-ads Args: name (str): The name of the destination. tenant_id (Optional[str]): The Tenant ID of your Microsoft Advertising developer application. Set this to "common" unless you know you need a different value. client_id (str): The Client ID of your Microsoft Advertising developer application. client_secret (Optional[str]): The Client Secret of your Microsoft Advertising developer application. refresh_token (str): Refresh Token to renew the expired Access Token. developer_token (str): Developer token associated with user. See more info in the docs. reports_start_date (str): The start date from which to begin replicating report data. Any data generated before this date will not be replicated in reports. This is a UTC date in YYYY-MM-DD format. """ self.auth_method = check.opt_str_param(auth_method, "auth_method") self.tenant_id = check.opt_str_param(tenant_id, "tenant_id") self.client_id = check.str_param(client_id, "client_id") self.client_secret = check.opt_str_param(client_secret, "client_secret") self.refresh_token = check.str_param(refresh_token, "refresh_token") self.developer_token = check.str_param(developer_token, "developer_token") self.reports_start_date = check.str_param(reports_start_date, "reports_start_date") super().__init__("Bing Ads", name)
BingAdsSource
python
huggingface__transformers
src/transformers/models/xmod/modeling_xmod.py
{ "start": 14627, "end": 15310 }
class ____(nn.Module): # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput.__init__ def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = hidden_states + input_tensor return hidden_states
XmodSelfOutput
python
tiangolo__fastapi
scripts/notify_translations.py
{ "start": 1770, "end": 1861 }
class ____(BaseModel): updateDiscussionComment: UpdateDiscussionComment
UpdateCommentData
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 207832, "end": 208319 }
class ____(TestCase): def test_basic(self) -> None: greetings = ['Hello', 'Goodbye'] names = ['Alice', 'Bob', 'Carol'] greet = lambda greeting, name: f'{greeting}, {name}!' result = list(mi.outer_product(greet, greetings, names)) expected = [ ('Hello, Alice!', 'Hello, Bob!', 'Hello, Carol!'), ('Goodbye, Alice!', 'Goodbye, Bob!', 'Goodbye, Carol!'), ] self.assertEqual(result, expected)
OuterProductTests
python
huggingface__transformers
src/transformers/models/llava_next_video/modular_llava_next_video.py
{ "start": 12160, "end": 12242 }
class ____(LlavaNextMultiModalProjector): pass
LlavaNextVideoMultiModalProjector
python
pandas-dev__pandas
pandas/tests/arrays/sparse/test_libsparse.py
{ "start": 6480, "end": 11877 }
class ____: def test_int_internal(self): idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="integer") assert isinstance(idx, IntIndex) assert idx.npoints == 2 tm.assert_numpy_array_equal(idx.indices, np.array([2, 3], dtype=np.int32)) idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="integer") assert isinstance(idx, IntIndex) assert idx.npoints == 0 tm.assert_numpy_array_equal(idx.indices, np.array([], dtype=np.int32)) idx = make_sparse_index( 4, np.array([0, 1, 2, 3], dtype=np.int32), kind="integer" ) assert isinstance(idx, IntIndex) assert idx.npoints == 4 tm.assert_numpy_array_equal(idx.indices, np.array([0, 1, 2, 3], dtype=np.int32)) def test_block_internal(self): idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind="block") assert isinstance(idx, BlockIndex) assert idx.npoints == 2 tm.assert_numpy_array_equal(idx.blocs, np.array([2], dtype=np.int32)) tm.assert_numpy_array_equal(idx.blengths, np.array([2], dtype=np.int32)) idx = make_sparse_index(4, np.array([], dtype=np.int32), kind="block") assert isinstance(idx, BlockIndex) assert idx.npoints == 0 tm.assert_numpy_array_equal(idx.blocs, np.array([], dtype=np.int32)) tm.assert_numpy_array_equal(idx.blengths, np.array([], dtype=np.int32)) idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind="block") assert isinstance(idx, BlockIndex) assert idx.npoints == 4 tm.assert_numpy_array_equal(idx.blocs, np.array([0], dtype=np.int32)) tm.assert_numpy_array_equal(idx.blengths, np.array([4], dtype=np.int32)) idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind="block") assert isinstance(idx, BlockIndex) assert idx.npoints == 3 tm.assert_numpy_array_equal(idx.blocs, np.array([0, 2], dtype=np.int32)) tm.assert_numpy_array_equal(idx.blengths, np.array([1, 2], dtype=np.int32)) @pytest.mark.parametrize("kind", ["integer", "block"]) def test_lookup(self, kind): idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind=kind) assert idx.lookup(-1) == -1 assert idx.lookup(0) == -1 assert idx.lookup(1) == -1 assert idx.lookup(2) == 0 assert idx.lookup(3) == 1 assert idx.lookup(4) == -1 idx = make_sparse_index(4, np.array([], dtype=np.int32), kind=kind) for i in range(-1, 5): assert idx.lookup(i) == -1 idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind=kind) assert idx.lookup(-1) == -1 assert idx.lookup(0) == 0 assert idx.lookup(1) == 1 assert idx.lookup(2) == 2 assert idx.lookup(3) == 3 assert idx.lookup(4) == -1 idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind=kind) assert idx.lookup(-1) == -1 assert idx.lookup(0) == 0 assert idx.lookup(1) == -1 assert idx.lookup(2) == 1 assert idx.lookup(3) == 2 assert idx.lookup(4) == -1 @pytest.mark.parametrize("kind", ["integer", "block"]) def test_lookup_array(self, kind): idx = make_sparse_index(4, np.array([2, 3], dtype=np.int32), kind=kind) res = idx.lookup_array(np.array([-1, 0, 2], dtype=np.int32)) exp = np.array([-1, -1, 0], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) res = idx.lookup_array(np.array([4, 2, 1, 3], dtype=np.int32)) exp = np.array([-1, 0, -1, 1], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) idx = make_sparse_index(4, np.array([], dtype=np.int32), kind=kind) res = idx.lookup_array(np.array([-1, 0, 2, 4], dtype=np.int32)) exp = np.array([-1, -1, -1, -1], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) idx = make_sparse_index(4, np.array([0, 1, 2, 3], dtype=np.int32), kind=kind) res = idx.lookup_array(np.array([-1, 0, 2], dtype=np.int32)) exp = np.array([-1, 0, 2], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) res = idx.lookup_array(np.array([4, 2, 1, 3], dtype=np.int32)) exp = np.array([-1, 2, 1, 3], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) idx = make_sparse_index(4, np.array([0, 2, 3], dtype=np.int32), kind=kind) res = idx.lookup_array(np.array([2, 1, 3, 0], dtype=np.int32)) exp = np.array([1, -1, 2, 0], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) res = idx.lookup_array(np.array([1, 4, 2, 5], dtype=np.int32)) exp = np.array([-1, -1, 1, -1], dtype=np.int32) tm.assert_numpy_array_equal(res, exp) @pytest.mark.parametrize( "idx, expected", [ [0, -1], [5, 0], [7, 2], [8, -1], [9, -1], [10, -1], [11, -1], [12, 3], [17, 8], [18, -1], ], ) def test_lookup_basics(self, idx, expected): bindex = BlockIndex(20, [5, 12], [3, 6]) assert bindex.lookup(idx) == expected iindex = bindex.to_int_index() assert iindex.lookup(idx) == expected
TestSparseIndexCommon
python
pydantic__pydantic
pydantic/types.py
{ "start": 36970, "end": 37190 }
class ____(BaseModel): uuid8: UUID8 Model(uuid8=uuid.UUID('81a0b92e-6078-8551-9c81-8ccb666bdab8')) ``` """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @_dataclasses.dataclass
Model
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 91059, "end": 91893 }
class ____(QueryTest): def test_clause_element_query_resolve(self): from sqlalchemy.orm.properties import ColumnProperty User = self.classes.User class Comparator(ColumnProperty.Comparator): def __init__(self, expr): self.expr = expr def __clause_element__(self): return self.expr # this use case isn't exactly needed in this form, however it tests # that we resolve for multiple __clause_element__() calls as is needed # by systems like composites sess = fixture_session() eq_( sess.query(Comparator(User.id)) .order_by(Comparator(User.id)) .all(), [(7,), (8,), (9,), (10,)], ) # more slice tests are available in test/orm/generative.py
ComparatorTest
python
chroma-core__chroma
chromadb/telemetry/product/events.py
{ "start": 4242, "end": 6750 }
class ____(ProductTelemetryEvent): max_batch_size: ClassVar[int] = 3000 batch_size: int collection_uuid: str query_amount: int filtered_ids_amount: int with_metadata_filter: int with_document_filter: int n_results: int include_metadatas: int include_documents: int include_uris: int include_distances: int def __init__( self, collection_uuid: str, query_amount: int, filtered_ids_amount: int, with_metadata_filter: int, with_document_filter: int, n_results: int, include_metadatas: int, include_documents: int, include_uris: int, include_distances: int, batch_size: int = 1, ): super().__init__() self.collection_uuid = collection_uuid self.query_amount = query_amount self.filtered_ids_amount = filtered_ids_amount self.with_metadata_filter = with_metadata_filter self.with_document_filter = with_document_filter self.n_results = n_results self.include_metadatas = include_metadatas self.include_documents = include_documents self.include_uris = include_uris self.include_distances = include_distances self.batch_size = batch_size @property def batch_key(self) -> str: return self.collection_uuid + self.name def batch(self, other: "ProductTelemetryEvent") -> "CollectionQueryEvent": if not self.batch_key == other.batch_key: raise ValueError("Cannot batch events") other = cast(CollectionQueryEvent, other) total_amount = self.query_amount + other.query_amount return CollectionQueryEvent( collection_uuid=self.collection_uuid, query_amount=total_amount, filtered_ids_amount=self.filtered_ids_amount + other.filtered_ids_amount, with_metadata_filter=self.with_metadata_filter + other.with_metadata_filter, with_document_filter=self.with_document_filter + other.with_document_filter, n_results=self.n_results + other.n_results, include_metadatas=self.include_metadatas + other.include_metadatas, include_documents=self.include_documents + other.include_documents, include_uris=self.include_uris + other.include_uris, include_distances=self.include_distances + other.include_distances, batch_size=self.batch_size + other.batch_size, )
CollectionQueryEvent
python
getsentry__sentry
src/sentry/dynamic_sampling/rules/combinators/base.py
{ "start": 516, "end": 1530 }
class ____(ABC): """ Base class representing a way to define total order between biases. The need of this class arises as there is the need to be explicit w.r.t to the ordering semantics of the biases. """ def __init__(self) -> None: self.biases: dict[RuleType, OrderedBias] = {} def add_if(self, rule_type: RuleType, bias: Bias, block: Callable[[], bool]) -> None: if block(): self.add(rule_type, bias) def add(self, rule_type: RuleType, bias: Bias) -> None: # We assign to this bias an order discriminant, which can be leveraged by the get_combined_biases to # return an ordered dictionary following a defined total order. self.biases[rule_type] = OrderedBias(bias, self.get_next_order_number()) @abstractmethod def get_next_order_number(self) -> int: raise NotImplementedError @abstractmethod def get_combined_biases(self) -> OrderedDict[RuleType, Bias]: raise NotImplementedError
BiasesCombinator