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
|
keras-team__keras
|
keras/src/layers/preprocessing/image_preprocessing/random_translation.py
|
{
"start": 599,
"end": 14932
}
|
class ____(BaseImagePreprocessingLayer):
"""A preprocessing layer which randomly translates images during training.
This layer will apply random translations to each image during training,
filling empty space according to `fill_mode`.
Input pixel values can be of any range (e.g. `[0., 1.)` or `[0, 255]`) and
of integer or floating point dtype. By default, the layer will output
floats.
**Note:** This layer is safe to use inside a `tf.data` or `grain` pipeline
(independently of which backend you're using).
Input shape:
3D (unbatched) or 4D (batched) tensor with shape:
`(..., height, width, channels)`, in `"channels_last"` format,
or `(..., channels, height, width)`, in `"channels_first"` format.
Output shape:
3D (unbatched) or 4D (batched) tensor with shape:
`(..., target_height, target_width, channels)`,
or `(..., channels, target_height, target_width)`,
in `"channels_first"` format.
Args:
height_factor: a float represented as fraction of value, or a tuple of
size 2 representing lower and upper bound for shifting vertically. A
negative value means shifting image up, while a positive value means
shifting image down. When represented as a single positive float,
this value is used for both the upper and lower bound. For instance,
`height_factor=(-0.2, 0.3)` results in an output shifted by a random
amount in the range `[-20%, +30%]`. `height_factor=0.2` results in
an output height shifted by a random amount in the range
`[-20%, +20%]`.
width_factor: a float represented as fraction of value, or a tuple of
size 2 representing lower and upper bound for shifting horizontally.
A negative value means shifting image left, while a positive value
means shifting image right. When represented as a single positive
float, this value is used for both the upper and lower bound. For
instance, `width_factor=(-0.2, 0.3)` results in an output shifted
left by 20%, and shifted right by 30%. `width_factor=0.2` results
in an output height shifted left or right by 20%.
fill_mode: Points outside the boundaries of the input are filled
according to the given mode. Available methods are `"constant"`,
`"nearest"`, `"wrap"` and `"reflect"`. Defaults to `"constant"`.
- `"reflect"`: `(d c b a | a b c d | d c b a)`
The input is extended by reflecting about the edge of the last
pixel.
- `"constant"`: `(k k k k | a b c d | k k k k)`
The input is extended by filling all values beyond
the edge with the same constant value k specified by
`fill_value`.
- `"wrap"`: `(a b c d | a b c d | a b c d)`
The input is extended by wrapping around to the opposite edge.
- `"nearest"`: `(a a a a | a b c d | d d d d)`
The input is extended by the nearest pixel.
Note that when using torch backend, `"reflect"` is redirected to
`"mirror"` `(c d c b | a b c d | c b a b)` because torch does not
support `"reflect"`.
Note that torch backend does not support `"wrap"`.
interpolation: Interpolation mode. Supported values: `"nearest"`,
`"bilinear"`.
seed: Integer. Used to create a random seed.
fill_value: a float represents the value to be filled outside the
boundaries when `fill_mode="constant"`.
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, height, width, channels)`
while `"channels_first"` corresponds to inputs with shape
`(batch, channels, height, width)`. It defaults to the
`image_data_format` value found in your Keras config file at
`~/.keras/keras.json`. If you never set it, then it will be
`"channels_last"`.
**kwargs: Base layer keyword arguments, such as `name` and `dtype`.
"""
_USE_BASE_FACTOR = False
_FACTOR_VALIDATION_ERROR = (
"The `factor` argument should be a number (or a list of two numbers) "
"in the range [-1.0, 1.0]. "
)
_SUPPORTED_FILL_MODE = ("reflect", "wrap", "constant", "nearest")
_SUPPORTED_INTERPOLATION = ("nearest", "bilinear")
def __init__(
self,
height_factor,
width_factor,
fill_mode="reflect",
interpolation="bilinear",
seed=None,
fill_value=0.0,
data_format=None,
**kwargs,
):
super().__init__(data_format=data_format, **kwargs)
self.height_factor = height_factor
self.height_lower, self.height_upper = self._set_factor(
height_factor, "height_factor"
)
self.width_factor = width_factor
self.width_lower, self.width_upper = self._set_factor(
width_factor, "width_factor"
)
if fill_mode not in self._SUPPORTED_FILL_MODE:
raise NotImplementedError(
f"Unknown `fill_mode` {fill_mode}. Expected of one "
f"{self._SUPPORTED_FILL_MODE}."
)
if interpolation not in self._SUPPORTED_INTERPOLATION:
raise NotImplementedError(
f"Unknown `interpolation` {interpolation}. Expected of one "
f"{self._SUPPORTED_INTERPOLATION}."
)
self.fill_mode = fill_mode
self.fill_value = fill_value
self.interpolation = interpolation
self.seed = seed
self.generator = SeedGenerator(seed)
self.supports_jit = False
def _set_factor(self, factor, factor_name):
if isinstance(factor, (tuple, list)):
if len(factor) != 2:
raise ValueError(
self._FACTOR_VALIDATION_ERROR
+ f"Received: {factor_name}={factor}"
)
self._check_factor_range(factor[0])
self._check_factor_range(factor[1])
lower, upper = sorted(factor)
elif isinstance(factor, (int, float)):
self._check_factor_range(factor)
factor = abs(factor)
lower, upper = [-factor, factor]
else:
raise ValueError(
self._FACTOR_VALIDATION_ERROR
+ f"Received: {factor_name}={factor}"
)
return lower, upper
def _check_factor_range(self, input_number):
if input_number > 1.0 or input_number < -1.0:
raise ValueError(
self._FACTOR_VALIDATION_ERROR
+ f"Received: input_number={input_number}"
)
def transform_images(self, images, transformation, training=True):
images = self.backend.cast(images, self.compute_dtype)
if training:
return self._translate_inputs(images, transformation)
return images
def transform_labels(self, labels, transformation, training=True):
return labels
def get_transformed_x_y(self, x, y, transform):
a0, a1, a2, b0, b1, b2, c0, c1 = self.backend.numpy.split(
transform, 8, axis=-1
)
k = c0 * x + c1 * y + 1
x_transformed = (a0 * x + a1 * y + a2) / k
y_transformed = (b0 * x + b1 * y + b2) / k
return x_transformed, y_transformed
def get_shifted_bbox(self, bounding_boxes, w_shift_factor, h_shift_factor):
bboxes = bounding_boxes["boxes"]
x1, x2, x3, x4 = self.backend.numpy.split(bboxes, 4, axis=-1)
w_shift_factor = self.backend.convert_to_tensor(
w_shift_factor, dtype=x1.dtype
)
h_shift_factor = self.backend.convert_to_tensor(
h_shift_factor, dtype=x1.dtype
)
if len(bboxes.shape) == 3:
w_shift_factor = self.backend.numpy.expand_dims(w_shift_factor, -1)
h_shift_factor = self.backend.numpy.expand_dims(h_shift_factor, -1)
bounding_boxes["boxes"] = self.backend.numpy.concatenate(
[
x1 - w_shift_factor,
x2 - h_shift_factor,
x3 - w_shift_factor,
x4 - h_shift_factor,
],
axis=-1,
)
return bounding_boxes
def transform_bounding_boxes(
self,
bounding_boxes,
transformation,
training=True,
):
if training:
if backend_utils.in_tf_graph():
self.backend.set_backend("tensorflow")
if self.data_format == "channels_first":
height_axis = -2
width_axis = -1
else:
height_axis = -3
width_axis = -2
input_height, input_width = (
transformation["input_shape"][height_axis],
transformation["input_shape"][width_axis],
)
bounding_boxes = convert_format(
bounding_boxes,
source=self.bounding_box_format,
target="xyxy",
height=input_height,
width=input_width,
)
translations = transformation["translations"]
transform = self._get_translation_matrix(translations)
w_shift_factor, h_shift_factor = self.get_transformed_x_y(
0, 0, transform
)
bounding_boxes = self.get_shifted_bbox(
bounding_boxes, w_shift_factor, h_shift_factor
)
bounding_boxes = clip_to_image_size(
bounding_boxes=bounding_boxes,
height=input_height,
width=input_width,
bounding_box_format="xyxy",
)
bounding_boxes = convert_format(
bounding_boxes,
source="xyxy",
target=self.bounding_box_format,
height=input_height,
width=input_width,
)
self.backend.reset()
return bounding_boxes
def transform_segmentation_masks(
self, segmentation_masks, transformation, training=True
):
return self.transform_images(
segmentation_masks, transformation, training=training
)
def get_random_transformation(self, data, training=True, seed=None):
if not training:
return None
if isinstance(data, dict):
images = data["images"]
else:
images = data
images_shape = self.backend.shape(images)
unbatched = len(images_shape) == 3
if unbatched:
images_shape = self.backend.shape(images)
batch_size = 1
else:
batch_size = images_shape[0]
if self.data_format == "channels_first":
height = images_shape[-2]
width = images_shape[-1]
else:
height = images_shape[-3]
width = images_shape[-2]
if seed is None:
seed = self._get_seed_generator(self.backend._backend)
height_translate = self.backend.random.uniform(
minval=self.height_lower,
maxval=self.height_upper,
shape=[batch_size, 1],
seed=seed,
)
height_translate = self.backend.numpy.multiply(height_translate, height)
width_translate = self.backend.random.uniform(
minval=self.width_lower,
maxval=self.width_upper,
shape=[batch_size, 1],
seed=seed,
)
width_translate = self.backend.numpy.multiply(width_translate, width)
translations = self.backend.cast(
self.backend.numpy.concatenate(
[width_translate, height_translate], axis=1
),
dtype="float32",
)
return {"translations": translations, "input_shape": images_shape}
def _translate_inputs(self, inputs, transformation):
if transformation is None:
return inputs
inputs_shape = self.backend.shape(inputs)
unbatched = len(inputs_shape) == 3
if unbatched:
inputs = self.backend.numpy.expand_dims(inputs, axis=0)
translations = transformation["translations"]
outputs = self.backend.image.affine_transform(
inputs,
transform=self._get_translation_matrix(translations),
interpolation=self.interpolation,
fill_mode=self.fill_mode,
fill_value=self.fill_value,
data_format=self.data_format,
)
if unbatched:
outputs = self.backend.numpy.squeeze(outputs, axis=0)
return outputs
def _get_translation_matrix(self, translations):
num_translations = self.backend.shape(translations)[0]
# The translation matrix looks like:
# [[1 0 -dx]
# [0 1 -dy]
# [0 0 1]]
# where the last entry is implicit.
# translation matrices are always float32.
return self.backend.numpy.concatenate(
[
self.backend.numpy.ones((num_translations, 1)),
self.backend.numpy.zeros((num_translations, 1)),
-translations[:, 0:1],
self.backend.numpy.zeros((num_translations, 1)),
self.backend.numpy.ones((num_translations, 1)),
-translations[:, 1:],
self.backend.numpy.zeros((num_translations, 2)),
],
axis=1,
)
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
base_config = super().get_config()
config = {
"height_factor": self.height_factor,
"width_factor": self.width_factor,
"fill_mode": self.fill_mode,
"interpolation": self.interpolation,
"seed": self.seed,
"fill_value": self.fill_value,
"data_format": self.data_format,
}
return {**base_config, **config}
|
RandomTranslation
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/core_api/datamodels/event_logs.py
|
{
"start": 1620,
"end": 1773
}
|
class ____(BaseModel):
"""Event Log Collection Response."""
event_logs: Iterable[EventLogResponse]
total_entries: int
|
EventLogCollectionResponse
|
python
|
huggingface__transformers
|
src/transformers/models/oneformer/modeling_oneformer.py
|
{
"start": 119096,
"end": 119520
}
|
class ____(nn.Module):
def __init__(self, config: OneFormerConfig):
super().__init__()
self.task_mlp = OneFormerMLPPredictionHead(
config.task_seq_len,
config.hidden_dim,
config.hidden_dim,
2,
)
def forward(self, inputs: Tensor) -> Tensor:
task_tokens = self.task_mlp(inputs)
return task_tokens
@auto_docstring
|
OneFormerTaskModel
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/auth/managers/models/base_user.py
|
{
"start": 856,
"end": 1014
}
|
class ____:
"""User model interface."""
@abstractmethod
def get_id(self) -> str: ...
@abstractmethod
def get_name(self) -> str: ...
|
BaseUser
|
python
|
great-expectations__great_expectations
|
tests/data_context/test_data_context_variables.py
|
{
"start": 2421,
"end": 19327
}
|
class ____(_ConfigurationProvider):
def __init__(self, config_values=None) -> None:
self._config_values = config_values or {}
super().__init__()
def get_values(self):
return self._config_values
@pytest.fixture
def ephemeral_data_context_variables(
data_context_config: DataContextConfig,
) -> EphemeralDataContextVariables:
return EphemeralDataContextVariables(
config=data_context_config, config_provider=StubConfigurationProvider()
)
@pytest.fixture
def file_data_context_variables(
data_context_config: DataContextConfig, empty_data_context: FileDataContext
) -> FileDataContextVariables:
return FileDataContextVariables(
data_context=empty_data_context,
config=data_context_config,
config_provider=StubConfigurationProvider(),
)
@pytest.fixture
def cloud_data_context_variables(
data_context_config: DataContextConfig,
ge_cloud_base_url: str,
ge_cloud_organization_id: str,
ge_cloud_workspace_id: str,
ge_cloud_access_token: str,
) -> CloudDataContextVariables:
return CloudDataContextVariables(
ge_cloud_base_url=ge_cloud_base_url,
ge_cloud_organization_id=ge_cloud_organization_id,
ge_cloud_workspace_id=ge_cloud_workspace_id,
ge_cloud_access_token=ge_cloud_access_token,
config=data_context_config,
config_provider=StubConfigurationProvider(),
)
@pytest.fixture
def file_data_context(
tmp_path: pathlib.Path, data_context_config: DataContextConfig
) -> FileDataContext:
project_path = tmp_path / "file_data_context"
project_path.mkdir()
context_root_dir = project_path / FileDataContext.GX_DIR
context = FileDataContext(project_config=data_context_config, context_root_dir=context_root_dir)
project_manager.set_project(context)
return context
@pytest.fixture
def cloud_data_context(
tmp_path: pathlib.Path,
data_context_config: DataContextConfig,
ge_cloud_config_e2e: GXCloudConfig,
) -> CloudDataContext:
project_path = tmp_path / "cloud_data_context"
project_path.mkdir()
context_root_dir = project_path / FileDataContext.GX_DIR
cloud_data_context = CloudDataContext(
project_config=data_context_config,
cloud_base_url=ge_cloud_config_e2e.base_url,
cloud_access_token=ge_cloud_config_e2e.access_token,
cloud_organization_id=ge_cloud_config_e2e.organization_id,
context_root_dir=context_root_dir,
)
project_manager.set_project(cloud_data_context)
return cloud_data_context
def stores() -> dict:
return {
"checkpoint_store": {
"class_name": "CheckpointStore",
"store_backend": {
"class_name": "TupleFilesystemStoreBackend",
"base_directory": "checkpoints/",
},
},
}
@pytest.fixture
def data_docs_sites() -> dict:
return {
"local_site": {
"class_name": "SiteBuilder",
"show_how_to_buttons": True,
"store_backend": {
"class_name": "TupleFilesystemStoreBackend",
"base_directory": "uncommitted/data_docs/local_site/",
},
}
}
@pytest.fixture
def progress_bars() -> ProgressBarsConfig:
return ProgressBarsConfig(
globally=True,
)
@pytest.mark.unit
@pytest.mark.parametrize(
"target_attr",
[
pytest.param(
DataContextVariableSchema.CONFIG_VERSION,
id="config_version getter",
),
pytest.param(
DataContextVariableSchema.CONFIG_VARIABLES_FILE_PATH,
id="config_variables_file_path getter",
),
pytest.param(
DataContextVariableSchema.PLUGINS_DIRECTORY,
id="plugins_directory getter",
),
pytest.param(
DataContextVariableSchema.EXPECTATIONS_STORE_NAME,
id="expectations_store getter",
),
pytest.param(
DataContextVariableSchema.VALIDATIONS_STORE_NAME,
id="validation_results_store getter",
),
pytest.param(
DataContextVariableSchema.CHECKPOINT_STORE_NAME,
id="checkpoint_store getter",
),
pytest.param(DataContextVariableSchema.STORES, id="stores getter"),
pytest.param(
DataContextVariableSchema.DATA_DOCS_SITES,
id="data_docs_sites getter",
),
pytest.param(
DataContextVariableSchema.PROGRESS_BARS,
id="progress_bars getter",
),
],
)
@pytest.mark.slow # 1.20s
def test_data_context_variables_get(
ephemeral_data_context_variables: EphemeralDataContextVariables,
file_data_context_variables: FileDataContextVariables,
cloud_data_context_variables: CloudDataContextVariables,
data_context_config: dict,
target_attr: DataContextVariableSchema,
) -> None:
def _test_variables_get(type_: DataContextVariables) -> None:
res: Any = getattr(type_, target_attr.value)
expected_value: Any = data_context_config[target_attr.value]
assert res == expected_value
# EphemeralDataContextVariables
_test_variables_get(ephemeral_data_context_variables)
# FileDataContextVariables
_test_variables_get(file_data_context_variables)
# CloudDataContextVariables
_test_variables_get(cloud_data_context_variables)
@pytest.mark.unit
def test_data_context_variables_get_with_substitutions(
data_context_config_dict: dict,
) -> None:
env_var_name: str = "MY_CONFIG_VERSION"
value_associated_with_env_var: float = 7.0
data_context_config_dict[DataContextVariableSchema.CONFIG_VERSION] = f"${env_var_name}"
config: DataContextConfig = DataContextConfig(**data_context_config_dict)
config_values: dict = {
env_var_name: value_associated_with_env_var,
}
variables: DataContextVariables = EphemeralDataContextVariables(
config=config,
config_provider=StubConfigurationProvider(config_values=config_values),
)
assert variables.config_version == value_associated_with_env_var
@pytest.mark.unit
@pytest.mark.parametrize(
"input_value,target_attr",
[
pytest.param(
5.0,
DataContextVariableSchema.CONFIG_VERSION,
id="config_version setter",
),
pytest.param(
"uncommitted/my_config_file.yml",
DataContextVariableSchema.CONFIG_VARIABLES_FILE_PATH,
id="config_variables_file_path setter",
),
pytest.param(
"other_plugins/",
DataContextVariableSchema.PLUGINS_DIRECTORY,
id="plugins_directory setter",
),
pytest.param(
"my_expectations_store",
DataContextVariableSchema.EXPECTATIONS_STORE_NAME,
id="expectations_store setter",
),
pytest.param(
"my_validation_results_store",
DataContextVariableSchema.VALIDATIONS_STORE_NAME,
id="validation_results_store setter",
),
pytest.param(
"my_checkpoint_store",
DataContextVariableSchema.CHECKPOINT_STORE_NAME,
id="checkpoint_store setter",
),
pytest.param(stores, DataContextVariableSchema.STORES, id="stores setter"),
pytest.param(
data_docs_sites,
DataContextVariableSchema.DATA_DOCS_SITES,
id="data_docs_sites setter",
),
pytest.param(
progress_bars,
DataContextVariableSchema.PROGRESS_BARS,
id="progress_bars setter",
),
],
)
@pytest.mark.slow # 1.20s
def test_data_context_variables_set(
ephemeral_data_context_variables: EphemeralDataContextVariables,
file_data_context_variables: FileDataContextVariables,
cloud_data_context_variables: CloudDataContextVariables,
input_value: Any,
target_attr: DataContextVariableSchema,
) -> None:
def _test_variables_set(type_: DataContextVariables) -> None:
setattr(type_, target_attr.value, input_value)
res: Any = type_.config[target_attr.value]
assert res == input_value
# EphemeralDataContextVariables
_test_variables_set(ephemeral_data_context_variables)
# FileDataContextVariables
_test_variables_set(file_data_context_variables)
# CloudDataContextVariables
_test_variables_set(cloud_data_context_variables)
@pytest.mark.unit
def test_data_context_variables_save(
mocker: MockerFixture,
data_context_config_dict: dict,
ephemeral_data_context_variables: EphemeralDataContextVariables,
file_data_context_variables: FileDataContextVariables,
cloud_data_context_variables: CloudDataContextVariables,
# The below GX Cloud variables were used to instantiate the above CloudDataContextVariables
v1_cloud_base_url: str,
ge_cloud_organization_id: str,
ge_cloud_workspace_id: str,
ge_cloud_access_token: str,
) -> None:
# EphemeralDataContextVariables
ephemeral_data_context_variables.save()
key: ConfigurationIdentifier = ephemeral_data_context_variables.get_key()
persisted_value: DataContextConfig = ephemeral_data_context_variables.store.get(key=key)
assert persisted_value.to_json_dict() == ephemeral_data_context_variables.config.to_json_dict()
# FileDataContextVariables
mock_save = mocker.patch(
"great_expectations.data_context.store.InlineStoreBackend._save_changes",
autospec=True,
)
file_data_context_variables.save()
assert mock_save.call_count == 1
# CloudDataContextVariables
mock_put = mocker.patch("requests.Session.put", autospec=True)
type(mock_put.return_value).status_code = mocker.PropertyMock(return_value=200)
cloud_data_context_variables.save()
expected_config_dict = {
"analytics_enabled": True,
"data_context_id": "6a52bdfa-e182-455b-a825-e69f076e67d6",
"config_variables_file_path": "uncommitted/config_variables.yml",
"config_version": 3.0,
"data_docs_sites": {},
"plugins_directory": "plugins/",
"stores": {
"expectations_store": {
"class_name": "ExpectationsStore",
"store_backend": {
"class_name": "TupleFilesystemStoreBackend",
"base_directory": "expectations/",
},
},
"checkpoint_store": {"class_name": "CheckpointStore"},
"validation_results_store": {"class_name": "ValidationResultsStore"},
"validation_definition_store": {"class_name": "ValidationDefinitionStore"},
},
}
assert mock_put.call_count == 1
url = urllib.parse.urljoin(
v1_cloud_base_url,
f"organizations/{ge_cloud_organization_id}/workspaces/{ge_cloud_workspace_id}/data-context-variables",
)
mock_put.assert_called_with(
MOCK_ANY, # requests.Session object
url,
json={
"data": expected_config_dict,
},
)
@pytest.mark.unit
def test_data_context_variables_repr_and_str_only_reveal_config(
data_context_config: DataContextConfig,
) -> None:
config = data_context_config
variables = EphemeralDataContextVariables(
config=data_context_config,
config_provider=StubConfigurationProvider(),
)
variables_str = str(variables)
variables_repr = repr(variables)
assert variables_str == str(config)
assert variables_repr == repr(config)
@pytest.mark.big
def test_file_data_context_variables_e2e(
monkeypatch,
file_data_context: FileDataContext,
progress_bars: ProgressBarsConfig,
) -> None:
"""
What does this test do and why?
Tests the E2E workflow with a FileDataContextVariables instance.
1. User updates certain values and sets them as attributes.
2. User persists changes utilizing the save call defined by the Variables API.
3. Upon reading the result config from disk, we can confirm that changes were appropriately persisted.
It is also important to note that in the case of $VARS syntax, we NEVER want to persist the underlying
value in order to preserve sensitive information.
""" # noqa: E501 # FIXME CoP
# Prepare updated progress_bars to set and serialize to disk
updated_progress_bars: ProgressBarsConfig = copy.deepcopy(progress_bars)
updated_progress_bars.globally = False
# Prepare updated plugins directory to set and serialize to disk (ensuring we hide the true value behind $VARS syntax) # noqa: E501 # FIXME CoP
env_var_name: str = "MY_PLUGINS_DIRECTORY"
value_associated_with_env_var: str = "foo/bar/baz"
monkeypatch.setenv(env_var_name, value_associated_with_env_var)
# Set attributes defined above
file_data_context.variables.progress_bars = updated_progress_bars
file_data_context.variables.plugins_directory = f"${env_var_name}"
file_data_context.variables.save()
# Review great_expectations.yml where values were written and confirm changes
config_filepath = pathlib.Path(file_data_context.root_directory).joinpath(
file_data_context.GX_YML
)
with open(config_filepath) as f:
contents: dict = yaml.load(f)
config_saved_to_disk: DataContextConfig = DataContextConfig(**contents)
assert config_saved_to_disk.progress_bars == updated_progress_bars.to_dict()
assert file_data_context.variables.plugins_directory == value_associated_with_env_var
assert config_saved_to_disk.plugins_directory == f"${env_var_name}"
@pytest.mark.cloud
@pytest.mark.xfail(
strict=False,
reason="GX Cloud E2E tests are failing due to new top-level `analytics` and `data_context_id` variables not yet being recognized by the server", # noqa: E501 # FIXME CoP
)
def test_cloud_data_context_variables_successfully_hits_cloud_endpoint(
cloud_data_context: CloudDataContext,
data_context_config: DataContextConfig,
) -> None:
"""
What does this test do and why?
Ensures that the endpoint responsible for the DataContextVariables resource is accessible
through the Variables API.
"""
cloud_data_context.variables.config = data_context_config
success = cloud_data_context.variables.save()
assert success is True
@pytest.mark.cloud
@mock_patch(
"great_expectations.data_context.data_context.serializable_data_context.SerializableDataContext._save_project_config"
)
@pytest.mark.xfail(
strict=False,
reason="GX Cloud E2E tests are failing due to env vars not being consistently recognized by Docker; x-failing for purposes of 0.15.22 release", # noqa: E501 # FIXME CoP
)
def test_cloud_enabled_data_context_variables_e2e(
mock_save_project_config: MagicMock,
data_docs_sites: dict,
monkeypatch,
) -> None:
"""
What does this test do and why?
Tests the E2E workflow with a Cloud-enabled DataContext; as the CloudDataContext does not yet have 1-to-1
feature parity with the DataContext (as v0.15.15), this is the primary mechanism by which Great
Expectations Cloud interacts with variables.
1. User updates certain values and sets them as attributes.
2. User persists changes utilizing the save call defined by the Variables API.
3. Upon reading the result config from a GET request, we can confirm that changes were appropriately persisted.
It is also important to note that in the case of $VARS syntax, we NEVER want to persist the underlying
value in order to preserve sensitive information.
""" # noqa: E501 # FIXME CoP
# Prepare updated plugins directory to set and save to the Cloud backend.
# As values are persisted in the Cloud DB, we want to randomize our values each time for consistent test results # noqa: E501 # FIXME CoP
updated_plugins_dir = f"plugins_dir_{''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))}" # noqa: E501 # FIXME CoP
updated_data_docs_sites = data_docs_sites
new_site_name = f"docs_site_{''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8))}" # noqa: E501 # FIXME CoP
updated_data_docs_sites[new_site_name] = {}
context = get_context(cloud_mode=True)
assert context.variables.plugins_directory != updated_plugins_dir
assert context.variables.data_docs_sites != updated_data_docs_sites
context.variables.plugins_directory = updated_plugins_dir
context.variables.data_docs_sites = updated_data_docs_sites
assert context.variables.plugins_directory == updated_plugins_dir
assert context.variables.data_docs_sites == updated_data_docs_sites
context.variables.save()
context = get_context(cloud_mode=True)
assert context.variables.plugins_directory == updated_plugins_dir
assert context.variables.data_docs_sites == updated_data_docs_sites
|
StubConfigurationProvider
|
python
|
facebook__pyre-check
|
tools/incremental_test/batch.py
|
{
"start": 2745,
"end": 3145
}
|
class ____(FinishedRunnerResult):
def get_status(self) -> str:
return "pass"
def to_json(self, dont_show_discrepancy: bool) -> Dict[str, Any]:
# Don't bother include the input specification in the result if the test passes.
return {
"status": self.get_status(),
"output": self._output.to_json(dont_show_discrepancy),
}
|
PassedRunnerResult
|
python
|
bokeh__bokeh
|
src/bokeh/events.py
|
{
"start": 17337,
"end": 17859
}
|
class ____(PointEvent):
''' Announce a mouse movement event over a Bokeh plot.
Attributes:
sx (float) : x-coordinate of the event in *screen* space
sy (float) : y-coordinate of the event in *screen* space
x (float) : x-coordinate of the event in *data* space
y (float) : y-coordinate of the event in *data* space
.. note::
This event can fire at a very high rate, potentially increasing network
traffic or CPU load.
'''
event_name = 'mousemove'
|
MouseMove
|
python
|
lepture__authlib
|
authlib/oauth2/rfc7523/validator.py
|
{
"start": 633,
"end": 1668
}
|
class ____(BearerTokenValidator):
TOKEN_TYPE = "bearer"
token_cls = JWTBearerToken
def __init__(self, public_key, issuer=None, realm=None, **extra_attributes):
super().__init__(realm, **extra_attributes)
self.public_key = public_key
claims_options = {
"exp": {"essential": True},
"client_id": {"essential": True},
"grant_type": {"essential": True},
}
if issuer:
claims_options["iss"] = {"essential": True, "value": issuer}
self.claims_options = claims_options
def authenticate_token(self, token_string):
try:
claims = jwt.decode(
token_string,
self.public_key,
claims_options=self.claims_options,
claims_cls=self.token_cls,
)
claims.validate()
return claims
except JoseError as error:
logger.debug("Authenticate token failed. %r", error)
return None
|
JWTBearerTokenValidator
|
python
|
numba__numba
|
numba/testing/main.py
|
{
"start": 27289,
"end": 31545
}
|
class ____(runner.TextTestRunner):
"""
A test runner which delegates the actual running to a pool of child
processes.
"""
resultclass = ParallelTestResult
timeout = _TIMEOUT
def __init__(self, runner_cls, nprocs, useslice, **kwargs):
runner.TextTestRunner.__init__(self, **kwargs)
self.runner_cls = runner_cls
self.nprocs = nprocs
self.useslice = parse_slice(useslice)
self.runner_args = kwargs
self.resource_infos = []
def _run_inner(self, result):
# We hijack TextTestRunner.run()'s inner logic by passing this
# method as if it were a test case.
child_runner = _MinimalRunner(self.runner_cls, self.runner_args)
# Split the tests and recycle the worker process to tame memory usage.
chunk_size = 100
splitted_tests = [self._ptests[i:i + chunk_size]
for i in range(0, len(self._ptests), chunk_size)]
spawnctx = multiprocessing.get_context("spawn")
try:
for tests in splitted_tests:
pool = spawnctx.Pool(self.nprocs)
try:
self._run_parallel_tests(result, pool, child_runner, tests)
except:
# On exception, kill still active workers immediately
pool.terminate()
# Make sure exception is reported and not ignored
raise
else:
# Close the pool cleanly unless asked to early out
if result.shouldStop:
pool.terminate()
break
else:
pool.close()
finally:
# Always join the pool (this is necessary for coverage.py)
pool.join()
if not result.shouldStop:
# Run serial tests with memory tracking
stests = SerialSuite(self._stests)
stests.run(result)
# Add serial test resource infos to the main collection
self.resource_infos.extend(stests.resource_infos)
return result
finally:
# Always display the resource infos
if memoryutils.IS_SUPPORTED:
try:
print("=== Resource Infos ===")
for ri in self.resource_infos:
print(ri)
except Exception:
print("ERROR: Ignored exception in priting resource infos")
traceback.print_exc()
finally:
print("=== End Resource Infos ===")
def _run_parallel_tests(self, result, pool, child_runner, tests):
remaining_ids = set(t.id() for t in tests)
tests.sort(key=cuda_sensitive_mtime)
it = pool.imap_unordered(child_runner, tests)
while True:
try:
child_result = it.__next__(self.timeout)
except StopIteration:
return
except TimeoutError as e:
# Diagnose the names of unfinished tests
msg = ("Tests didn't finish before timeout (or crashed):\n%s"
% "".join("- %r\n" % tid for tid in sorted(remaining_ids))
)
e.args = (msg,) + e.args[1:]
raise e
else:
result.add_results(child_result)
self.resource_infos.append(child_result.resource_info)
remaining_ids.discard(child_result.test_id)
if child_result.shouldStop:
result.shouldStop = True
return
def run(self, test):
self._ptests, self._stests = _split_nonparallel_tests(test,
self.useslice)
print("Parallel: %s. Serial: %s" % (len(self._ptests),
len(self._stests)))
# This will call self._run_inner() on the created result object,
# and print out the detailed test results at the end.
return super(ParallelTestRunner, self).run(self._run_inner)
|
ParallelTestRunner
|
python
|
tensorflow__tensorflow
|
third_party/xla/xla/python_api/xla_shape_test.py
|
{
"start": 998,
"end": 4443
}
|
class ____(absltest.TestCase):
def assertShape(self, shape, expected_dimensions, expected_element_type):
self.assertEqual(shape.element_type(), expected_element_type)
self.assertEqual(shape.dimensions(), expected_dimensions)
def assertLayout(self, layout, expected_minor_to_major):
self.assertEqual(layout.minor_to_major, expected_minor_to_major)
def assertTupleShape(self, shape, expected):
self.assertEqual(shape.element_type(), xla_data_pb2.TUPLE)
for sub_shape, sub_message, sub_expected in zip(
shape.tuple_shapes(),
shape.message.tuple_shapes,
expected):
self.assertEqual(sub_shape.element_type(), sub_message.element_type)
if sub_shape.is_tuple():
self.assertTupleShape(sub_shape, sub_expected)
else:
expected_dimensions, expected_element_types = sub_expected
self.assertShape(
sub_shape, expected_dimensions, expected_element_types)
def testCreateShapeFromNumpy1D(self):
shape = xla_shape.CreateShapeFromNumpy(NumpyArrayF32([1.1, 2.2]))
self.assertShape(shape, [2], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [0])
def testCreateShapeFromNumpy2DRowMajor(self):
shape = xla_shape.CreateShapeFromNumpy(
NumpyArrayF32(
[[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]], order='C'))
self.assertShape(shape, [2, 3], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [1, 0])
def testCreateShapeFromNumpy2DColumnMajor(self):
shape = xla_shape.CreateShapeFromNumpy(
NumpyArrayF32(
[[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]], order='F'))
self.assertShape(shape, [2, 3], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [0, 1])
def testCreateShapeFromNumpy2DDefaultIsRowMajor(self):
# The default layout in Numpy is C (row major)
shape = xla_shape.CreateShapeFromNumpy(
NumpyArrayF32([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]))
self.assertShape(shape, [2, 3], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [1, 0])
def testCreateShapeFromNumpy3DRowMajor(self):
shape = xla_shape.CreateShapeFromNumpy(
NumpyArrayF32(
[[[1.1], [2.2], [3.3]], [[4.4], [5.5], [6.6]]], order='C'))
self.assertShape(shape, [2, 3, 1], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [2, 1, 0])
def testCreateShapeFromNumpy3DColumnMajor(self):
shape = xla_shape.CreateShapeFromNumpy(
NumpyArrayF32(
[[[1.1], [2.2], [3.3]], [[4.4], [5.5], [6.6]]], order='F'))
self.assertShape(shape, [2, 3, 1], xla_data_pb2.F32)
self.assertLayout(shape.layout(), [0, 1, 2])
def testCreateShapeFromTupleOfNumpy3D(self):
inner_array = NumpyArrayF32(
[[[1.1], [2.2], [3.3]], [[4.4], [5.5], [6.6]]])
inner_spec = ([2, 3, 1], xla_data_pb2.F32)
shape = xla_shape.CreateShapeFromNumpy(
(inner_array, inner_array, inner_array))
self.assertTupleShape(
shape,
(inner_spec, inner_spec, inner_spec))
def testCreateShapeFromNestedTupleOfNumpy3D(self):
inner_array = NumpyArrayF32(
[[[1.1], [2.2], [3.3]], [[4.4], [5.5], [6.6]]])
inner_spec = ([2, 3, 1], xla_data_pb2.F32)
shape = xla_shape.CreateShapeFromNumpy(
(inner_array, (inner_array, inner_array), inner_array))
self.assertTupleShape(
shape,
(inner_spec, (inner_spec, inner_spec), inner_spec))
if __name__ == '__main__':
absltest.main()
|
CreateShapeFromNumpyTest
|
python
|
spyder-ide__spyder
|
spyder/api/widgets/menus.py
|
{
"start": 980,
"end": 1162
}
|
class ____:
Context = 'context_menu'
Options = 'options_menu'
# ---- Style
# -----------------------------------------------------------------------------
|
PluginMainWidgetMenus
|
python
|
viewflow__viewflow
|
tests/json/test_json__basics.py
|
{
"start": 3028,
"end": 3131
}
|
class ____(forms.ModelForm):
class Meta:
model = Person
exclude = ["data"]
|
PersonForm
|
python
|
spyder-ide__spyder
|
spyder/plugins/preferences/widgets/configdialog.py
|
{
"start": 681,
"end": 4517
}
|
class ____(SidebarDialog):
"""Preferences dialog."""
# Signals
check_settings = Signal()
sig_size_changed = Signal(QSize)
sig_reset_preferences_requested = Signal()
# Constants
TITLE = _("Preferences")
MIN_WIDTH = 940 if MAC else (875 if WIN else 920)
MIN_HEIGHT = 700 if MAC else (660 if WIN else 670)
def __init__(self, parent=None):
self.ICON = ima.icon('configure')
SidebarDialog.__init__(self, parent)
# Attributes
self.main = parent
# Ensures that the config is present on spyder first run
CONF.set('main', 'interface_language', load_lang_conf())
# ---- Public API
# -------------------------------------------------------------------------
def get_index_by_name(self, name):
"""Return page index by CONF_SECTION name."""
for idx in range(self.pages_widget.count()):
page = self.get_page(idx)
# This is the case for separators
if page is None:
continue
section = page.plugin.NAME
if section == name:
return idx
else:
return None
def check_all_settings(self):
"""
This method is called to check all configuration page settings after
configuration dialog has been shown.
"""
self.check_settings.emit()
# ---- SidebarDialog API
# -------------------------------------------------------------------------
def button_clicked(self, button):
if button is self.apply_btn:
# Apply button was clicked
configpage = self.get_page()
if not configpage.is_valid():
return
configpage.apply_changes()
def current_page_changed(self, index):
widget = self.get_page(index)
self.apply_btn.setVisible(widget.apply_callback is not None)
self.apply_btn.setEnabled(widget.is_modified)
def add_page(self, page, initialize=False):
# Signals
self.check_settings.connect(page.check_settings)
page.apply_button_enabled.connect(self.apply_btn.setEnabled)
super().add_page(page, initialize=initialize)
def create_buttons(self):
bbox = SpyderDialogButtonBox(
QDialogButtonBox.Ok
| QDialogButtonBox.Apply
| QDialogButtonBox.Cancel
)
self.apply_btn = bbox.button(QDialogButtonBox.Apply)
# This is needed for our tests
self.ok_btn = bbox.button(QDialogButtonBox.Ok)
button_reset = QPushButton(_('Reset to defaults'))
button_reset.clicked.connect(self.sig_reset_preferences_requested)
bbox.addButton(button_reset, QDialogButtonBox.ResetRole)
layout = QHBoxLayout()
layout.addWidget(bbox)
return bbox, layout
# ---- Qt methods
# -------------------------------------------------------------------------
@Slot()
def accept(self):
for index in range(self.pages_widget.count()):
configpage = self.get_page(index)
# This can be the case for separators, which doesn't have a config
# page.
if configpage is None:
continue
if not configpage.is_valid():
return
configpage.apply_changes()
QDialog.accept(self)
def resizeEvent(self, event):
super().resizeEvent(event)
self._on_resize()
# ---- Private API
# -------------------------------------------------------------------------
@qdebounced(timeout=40)
def _on_resize(self):
"""
We name this method differently from SidebarDialog._on_resize_event
because we want to debounce this as well.
"""
self.sig_size_changed.emit(self.size())
|
ConfigDialog
|
python
|
getlogbook__logbook
|
src/logbook/queues.py
|
{
"start": 20897,
"end": 22431
}
|
class ____(WrapperHandler):
"""This handled uses a single background thread to dispatch log records
to a specific other handler using an internal queue. The idea is that if
you are using a handler that requires some time to hand off the log records
(such as the mail handler) and would block your request, you can let
Logbook do that in a background thread.
The threaded wrapper handler will automatically adopt the methods and
properties of the wrapped handler. All the values will be reflected:
>>> twh = ThreadedWrapperHandler(TestHandler())
>>> from logbook import WARNING
>>> twh.level_name = 'WARNING'
>>> twh.handler.level_name
'WARNING'
"""
_direct_attrs = frozenset(["handler", "queue", "controller"])
def __init__(self, handler, maxsize=0):
WrapperHandler.__init__(self, handler)
self.queue = ThreadQueue(maxsize)
self.controller = TWHThreadController(self)
self.controller.start()
def close(self):
self.controller.stop()
self.handler.close()
def emit(self, record):
item = (TWHThreadController.Command.emit, record)
try:
self.queue.put_nowait(item)
except Full:
# silently drop
pass
def emit_batch(self, records, reason):
item = (TWHThreadController.Command.emit_batch, records, reason)
try:
self.queue.put_nowait(item)
except Full:
# silently drop
pass
|
ThreadedWrapperHandler
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/src/hypothesis/strategies/_internal/strategies.py
|
{
"start": 31737,
"end": 39286
}
|
class ____(SearchStrategy[Ex]):
"""Implements a union of strategies. Given a number of strategies this
generates values which could have come from any of them.
The conditional distribution draws uniformly at random from some
non-empty subset of these strategies and then draws from the
conditional distribution of that strategy.
"""
def __init__(self, strategies: Sequence[SearchStrategy[Ex]]):
super().__init__()
self.original_strategies = tuple(strategies)
self.__element_strategies: Sequence[SearchStrategy[Ex]] | None = None
self.__in_branches = False
self._branches_lock = RLock()
def calc_is_empty(self, recur: RecurT) -> bool:
return all(recur(e) for e in self.original_strategies)
def calc_has_reusable_values(self, recur: RecurT) -> bool:
return all(recur(e) for e in self.original_strategies)
def calc_is_cacheable(self, recur: RecurT) -> bool:
return all(recur(e) for e in self.original_strategies)
@property
def element_strategies(self) -> Sequence[SearchStrategy[Ex]]:
if self.__element_strategies is None:
# While strategies are hashable, they use object.__hash__ and are
# therefore distinguished only by identity.
#
# In principle we could "just" define a __hash__ method
# (and __eq__, but that's easy in terms of type() and hash())
# to make this more powerful, but this is harder than it sounds:
#
# 1. Strategies are often distinguished by non-hashable attributes,
# or by attributes that have the same hash value ("^.+" / b"^.+").
# 2. LazyStrategy: can't reify the wrapped strategy without breaking
# laziness, so there's a hash each for the lazy and the nonlazy.
#
# Having made several attempts, the minor benefits of making strategies
# hashable are simply not worth the engineering effort it would take.
# See also issues #2291 and #2327.
seen: set[SearchStrategy] = {self}
strategies: list[SearchStrategy] = []
for arg in self.original_strategies:
check_strategy(arg)
if not arg.is_empty:
for s in arg.branches:
if s not in seen and not s.is_empty:
seen.add(s)
strategies.append(s)
self.__element_strategies = strategies
return self.__element_strategies
def calc_label(self) -> int:
return combine_labels(
self.class_label, *(p.label for p in self.original_strategies)
)
def do_draw(self, data: ConjectureData) -> Ex:
strategy = data.draw(
SampledFromStrategy(self.element_strategies).filter(
lambda s: not s.is_currently_empty(data)
)
)
return data.draw(strategy)
def __repr__(self) -> str:
return "one_of({})".format(", ".join(map(repr, self.original_strategies)))
def do_validate(self) -> None:
for e in self.element_strategies:
e.validate()
@property
def branches(self) -> Sequence[SearchStrategy[Ex]]:
if self.__element_strategies is not None:
# common fast path which avoids the lock
return self.element_strategies
with self._branches_lock:
if not self.__in_branches:
try:
self.__in_branches = True
return self.element_strategies
finally:
self.__in_branches = False
else:
return [self]
def filter(self, condition: Callable[[Ex], Any]) -> SearchStrategy[Ex]:
return FilteredStrategy(
OneOfStrategy([s.filter(condition) for s in self.original_strategies]),
conditions=(),
)
@overload
def one_of(
__args: Sequence[SearchStrategy[Ex]],
) -> SearchStrategy[Ex]: # pragma: no cover
...
@overload
def one_of(__a1: SearchStrategy[Ex]) -> SearchStrategy[Ex]: # pragma: no cover
...
@overload
def one_of(
__a1: SearchStrategy[Ex], __a2: SearchStrategy[T]
) -> SearchStrategy[Ex | T]: # pragma: no cover
...
@overload
def one_of(
__a1: SearchStrategy[Ex], __a2: SearchStrategy[T], __a3: SearchStrategy[T3]
) -> SearchStrategy[Ex | T | T3]: # pragma: no cover
...
@overload
def one_of(
__a1: SearchStrategy[Ex],
__a2: SearchStrategy[T],
__a3: SearchStrategy[T3],
__a4: SearchStrategy[T4],
) -> SearchStrategy[Ex | T | T3 | T4]: # pragma: no cover
...
@overload
def one_of(
__a1: SearchStrategy[Ex],
__a2: SearchStrategy[T],
__a3: SearchStrategy[T3],
__a4: SearchStrategy[T4],
__a5: SearchStrategy[T5],
) -> SearchStrategy[Ex | T | T3 | T4 | T5]: # pragma: no cover
...
@overload
def one_of(*args: SearchStrategy[Any]) -> SearchStrategy[Any]: # pragma: no cover
...
@defines_strategy(eager=True)
def one_of(
*args: Sequence[SearchStrategy[Any]] | SearchStrategy[Any],
) -> SearchStrategy[Any]:
# Mypy workaround alert: Any is too loose above; the return parameter
# should be the union of the input parameters. Unfortunately, Mypy <=0.600
# raises errors due to incompatible inputs instead. See #1270 for links.
# v0.610 doesn't error; it gets inference wrong for 2+ arguments instead.
"""Return a strategy which generates values from any of the argument
strategies.
This may be called with one iterable argument instead of multiple
strategy arguments, in which case ``one_of(x)`` and ``one_of(*x)`` are
equivalent.
Examples from this strategy will generally shrink to ones that come from
strategies earlier in the list, then shrink according to behaviour of the
strategy that produced them. In order to get good shrinking behaviour,
try to put simpler strategies first. e.g. ``one_of(none(), text())`` is
better than ``one_of(text(), none())``.
This is especially important when using recursive strategies. e.g.
``x = st.deferred(lambda: st.none() | st.tuples(x, x))`` will shrink well,
but ``x = st.deferred(lambda: st.tuples(x, x) | st.none())`` will shrink
very badly indeed.
"""
if len(args) == 1 and not isinstance(args[0], SearchStrategy):
try:
args = tuple(args[0])
except TypeError:
pass
if len(args) == 1 and isinstance(args[0], SearchStrategy):
# This special-case means that we can one_of over lists of any size
# without incurring any performance overhead when there is only one
# strategy, and keeps our reprs simple.
return args[0]
if args and not any(isinstance(a, SearchStrategy) for a in args):
# And this special case is to give a more-specific error message if it
# seems that the user has confused `one_of()` for `sampled_from()`;
# the remaining validation is left to OneOfStrategy. See PR #2627.
raise InvalidArgument(
f"Did you mean st.sampled_from({list(args)!r})? st.one_of() is used "
"to combine strategies, but all of the arguments were of other types."
)
# we've handled the case where args is a one-element sequence [(s1, s2, ...)]
# above, so we can assume it's an actual sequence of strategies.
args = cast(Sequence[SearchStrategy], args)
return OneOfStrategy(args)
|
OneOfStrategy
|
python
|
walkccc__LeetCode
|
solutions/1995. Count Special Quadruplets/1995.py
|
{
"start": 0,
"end": 296
}
|
class ____:
def countQuadruplets(self, nums: list[int]) -> int:
n = len(nums)
return sum(nums[a] + nums[b] + nums[c] == nums[d]
for a in range(n)
for b in range(a + 1, n)
for c in range(b + 1, n)
for d in range(c + 1, n))
|
Solution
|
python
|
getsentry__sentry
|
src/sentry/workflow_engine/migrations/0103_add_unique_constraint.py
|
{
"start": 230,
"end": 3473
}
|
class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = True
dependencies = [
("sentry", "1007_cleanup_failed_safe_deletes"),
("workflow_engine", "0102_cleanup_failed_safe_deletes"),
]
operations = [
migrations.SeparateDatabaseAndState(
database_operations=[
# First add the unique constraint (creates a unique index)
migrations.AddConstraint(
model_name="workflow",
constraint=models.UniqueConstraint(
fields=("when_condition_group_id",),
name="workflow_engine_workflow_when_condition_group_id_11d9ba05_uniq",
),
),
# Then drop the old regular index (db_index=False)
migrations.AlterField(
model_name="workflow",
name="when_condition_group",
field=sentry.db.models.fields.foreignkey.FlexibleForeignKey(
blank=True,
db_index=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="workflow_engine.dataconditiongroup",
),
),
],
state_operations=[
# Update Django's state to reflect the final model state
migrations.AlterField(
model_name="workflow",
name="when_condition_group",
field=sentry.db.models.fields.foreignkey.FlexibleForeignKey(
blank=True,
db_index=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="workflow_engine.dataconditiongroup",
),
),
migrations.AddConstraint(
model_name="workflow",
constraint=models.UniqueConstraint(
fields=("when_condition_group_id",),
name="workflow_engine_workflow_when_condition_group_id_11d9ba05_uniq",
),
),
],
),
]
|
Migration
|
python
|
django-debug-toolbar__django-debug-toolbar
|
tests/panels/test_async_panel_compatibility.py
|
{
"start": 247,
"end": 298
}
|
class ____(Panel):
is_async = False
|
MockSyncPanel
|
python
|
numpy__numpy
|
numpy/typing/tests/data/pass/ufunc_config.py
|
{
"start": 245,
"end": 318
}
|
class ____:
def write(self, a: str) -> None:
return None
|
Write1
|
python
|
huggingface__transformers
|
src/transformers/models/edgetam/modular_edgetam.py
|
{
"start": 6285,
"end": 6357
}
|
class ____(Sam2TwoWayAttentionBlock):
pass
|
EdgeTamTwoWayAttentionBlock
|
python
|
crytic__slither
|
slither/core/declarations/solidity_variables.py
|
{
"start": 5923,
"end": 7232
}
|
class ____(SourceMapping):
# Non standard handling of type(address). This function returns an undefined object
# The type is dynamic
# https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#type-information
# As a result, we set return_type during the Ir conversion
def __init__(self, name: str) -> None:
super().__init__()
assert name in SOLIDITY_FUNCTIONS
self._name = name
# Can be TypeInformation if type(address) is used
self._return_type: List[Union[TypeInformation, ElementaryType]] = [
ElementaryType(x) for x in SOLIDITY_FUNCTIONS[self.name]
]
@property
def name(self) -> str:
return self._name
@property
def full_name(self) -> str:
return self.name
@property
def return_type(self) -> List[Union[TypeInformation, ElementaryType]]:
return self._return_type
@return_type.setter
def return_type(self, r: List[Union[TypeInformation, ElementaryType]]) -> None:
self._return_type = r
def __str__(self) -> str:
return self._name
def __eq__(self, other: Any) -> bool:
return self.__class__ == other.__class__ and self.name == other.name
def __hash__(self) -> int:
return hash(self.name)
|
SolidityFunction
|
python
|
getsentry__sentry
|
src/sentry/integrations/base.py
|
{
"start": 5683,
"end": 5799
}
|
class ____(TypedDict):
type: str
external_id: str
data: dict[str, str]
scopes: list[str]
|
_UserIdentity
|
python
|
great-expectations__great_expectations
|
contrib/experimental/great_expectations_experimental/expectations/expect_column_skew_to_be_between.py
|
{
"start": 1009,
"end": 5372
}
|
class ____(ColumnAggregateMetricProvider):
"""MetricProvider Class for Aggregate Mean MetricProvider"""
metric_name = "column.custom.skew"
value_keys = ("abs",)
@column_aggregate_value(engine=PandasExecutionEngine)
def _pandas(cls, column, abs=False, **kwargs):
if abs:
return np.abs(stats.skew(column))
return stats.skew(column)
@column_aggregate_partial(engine=SparkDFExecutionEngine)
def _spark(cls, column, abs=False, **kwargs):
if abs:
return F.abs(F.skewness(column))
return F.skewness(column)
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(
cls,
execution_engine: "SqlAlchemyExecutionEngine",
metric_domain_kwargs: Dict,
metric_value_kwargs: Dict,
metrics: Dict[Tuple, Any],
runtime_configuration: Dict,
):
(
selectable,
_compute_domain_kwargs,
accessor_domain_kwargs,
) = execution_engine.get_compute_domain(metric_domain_kwargs, MetricDomainTypes.COLUMN)
column_name = accessor_domain_kwargs["column"]
column = sa.column(column_name)
dialect = execution_engine.dialect
column_mean = _get_query_result(
func=sa.func.avg(column * 1.0),
selectable=selectable,
execution_engine=execution_engine,
)
column_count = _get_query_result(
func=sa.func.count(column),
selectable=selectable,
execution_engine=execution_engine,
)
if dialect.name.lower() == "mssql":
standard_deviation = sa.func.stdev(column)
else:
standard_deviation = sa.func.stddev_samp(column)
column_std = _get_query_result(
func=standard_deviation,
selectable=selectable,
execution_engine=execution_engine,
)
column_third_moment = _get_query_result(
func=sa.func.sum(sa.func.pow(column - column_mean, 3)),
selectable=selectable,
execution_engine=execution_engine,
)
column_skew = column_third_moment / (column_std**3) / (column_count - 1)
if metric_value_kwargs["abs"]:
return np.abs(column_skew)
else:
return column_skew
def _get_query_result(func, selectable, execution_engine: SqlAlchemyExecutionEngine):
simple_query: sqlalchemy.Select = sa.select(func).select_from(selectable)
try:
result: sqlalchemy.Row = execution_engine.execute_query(simple_query).fetchone()[0]
return result
except sqlalchemy.ProgrammingError as pe:
exception_message: str = "An SQL syntax Exception occurred."
exception_traceback: str = traceback.format_exc()
exception_message += f'{type(pe).__name__}: "{pe!s}". Traceback: "{exception_traceback}".'
logger.error(exception_message) # noqa: TRY400
raise pe # noqa: TRY201
# @classmethod
# def _get_evaluation_dependencies(
# cls,
# metric: MetricConfiguration,
# configuration: Optional[ExpectationConfiguration] = None,
# execution_engine: Optional[ExecutionEngine] = None,
# runtime_configuration: Optional[dict] = None,
# ):
# """This should return a dictionary:
#
# {
# "dependency_name": MetricConfiguration,
# ...
# }
# """
#
# dependencies = super()._get_evaluation_dependencies(
# metric=metric,
# configuration=configuration,
# execution_engine=execution_engine,
# runtime_configuration=runtime_configuration,
# )
#
# table_domain_kwargs = {
# k: v for k, v in metric.metric_domain_kwargs.items() if k != "column"
# }
#
# dependencies.update(
# {
# "table.row_count": MetricConfiguration(
# "table.row_count", table_domain_kwargs
# )
# }
# )
#
# if isinstance(execution_engine, SqlAlchemyExecutionEngine):
# dependencies["column_values.nonnull.count"] = MetricConfiguration(
# "column_values.nonnull.count", metric.metric_domain_kwargs
# )
#
# return dependencies
|
ColumnSkew
|
python
|
apache__airflow
|
providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py
|
{
"start": 78450,
"end": 80520
}
|
class ____(SageMakerBaseOperator):
"""
Creates a SageMaker experiment, to be then associated to jobs etc.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:SageMakerCreateExperimentOperator`
:param name: name of the experiment, must be unique within the AWS account
:param description: description of the experiment, optional
:param tags: tags to attach to the experiment, optional
: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.html
:returns: the ARN of the experiment created, though experiments are referred to by name
"""
template_fields: Sequence[str] = aws_template_fields(
"name",
"description",
"tags",
)
def __init__(
self,
*,
name: str,
description: str | None = None,
tags: dict | None = None,
**kwargs,
):
super().__init__(config={}, **kwargs)
self.name = name
self.description = description
self.tags = tags or {}
def execute(self, context: Context) -> str:
params = {
"ExperimentName": self.name,
"Description": self.description,
"Tags": format_tags(self.tags),
}
ans = self.hook.conn.create_experiment(**trim_none_values(params))
arn = ans["ExperimentArn"]
self.log.info("Experiment %s created successfully with ARN %s.", self.name, arn)
return arn
|
SageMakerCreateExperimentOperator
|
python
|
joke2k__faker
|
tests/providers/test_date_time.py
|
{
"start": 41708,
"end": 42064
}
|
class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("pt_PT")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in PtPtProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in PtPtProvider.MONTH_NAMES.values()
|
TestPtPt
|
python
|
PyCQA__isort
|
scripts/mkstdlibs.py
|
{
"start": 564,
"end": 1606
}
|
class ____:
srcdir = ""
config = FakeConfig()
for version_module in VERSIONS:
version_match = re.match(
r"^stdlibs\.py(?P<major>\d)(?P<minor>\d+)$",
version_module.__name__,
)
version_info = (version_match.groupdict()["major"], version_match.groupdict()["minor"])
# Any modules we want to enforce across Python versions stdlib can be included in set init
modules = {"_ast", "posixpath", "ntpath", "sre_constants", "sre_parse", "sre_compile", "sre"}
modules.update(
{
module_name
for module_name in version_module.module_names
if not module_name.startswith("_")
}
)
path = PATH.format("".join(version_info))
with open(path, "w") as stdlib_file:
docstring = DOCSTRING.format(".".join(version_info))
stdlib_file.write(f'"""{docstring}"""\n\n')
stdlib_file.write("stdlib = {\n")
for module in sorted(modules):
stdlib_file.write(f' "{module}",\n')
stdlib_file.write("}\n")
|
FakeApp
|
python
|
pydantic__pydantic
|
pydantic/v1/types.py
|
{
"start": 32326,
"end": 34622
}
|
class ____(int):
@classmethod
def __get_validators__(cls) -> 'CallableGenerator':
yield cls.validate
@classmethod
def validate(cls, v: StrIntFloat) -> 'ByteSize':
try:
return cls(int(v))
except ValueError:
pass
str_match = byte_string_re.match(str(v))
if str_match is None:
raise errors.InvalidByteSize()
scalar, unit = str_match.groups()
if unit is None:
unit = 'b'
try:
unit_mult = BYTE_SIZES[unit.lower()]
except KeyError:
raise errors.InvalidByteSizeUnit(unit=unit)
return cls(int(float(scalar) * unit_mult))
def human_readable(self, decimal: bool = False) -> str:
if decimal:
divisor = 1000
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
final_unit = 'EB'
else:
divisor = 1024
units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
final_unit = 'EiB'
num = float(self)
for unit in units:
if abs(num) < divisor:
return f'{num:0.1f}{unit}'
num /= divisor
return f'{num:0.1f}{final_unit}'
def to(self, unit: str) -> float:
try:
unit_div = BYTE_SIZES[unit.lower()]
except KeyError:
raise errors.InvalidByteSizeUnit(unit=unit)
return self / unit_div
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if TYPE_CHECKING:
PastDate = date
FutureDate = date
else:
class PastDate(date):
@classmethod
def __get_validators__(cls) -> 'CallableGenerator':
yield parse_date
yield cls.validate
@classmethod
def validate(cls, value: date) -> date:
if value >= date.today():
raise errors.DateNotInThePastError()
return value
class FutureDate(date):
@classmethod
def __get_validators__(cls) -> 'CallableGenerator':
yield parse_date
yield cls.validate
@classmethod
def validate(cls, value: date) -> date:
if value <= date.today():
raise errors.DateNotInTheFutureError()
return value
|
ByteSize
|
python
|
PyCQA__pylint
|
pylint/config/callback_actions.py
|
{
"start": 1572,
"end": 2591
}
|
class ____(_CallbackAction):
"""Action that has access to the Run object."""
def __init__(
self,
option_strings: Sequence[str],
dest: str,
nargs: None = None,
const: None = None,
default: None = None,
type: None = None,
choices: None = None,
required: bool = False,
help: str = "",
metavar: str = "",
**kwargs: Run,
) -> None:
self.run = kwargs["Run"]
super().__init__(
option_strings,
dest,
0,
const,
default,
type,
choices,
required,
help,
metavar,
)
@abc.abstractmethod
def __call__(
self,
parser: argparse.ArgumentParser,
namespace: argparse.Namespace,
values: str | Sequence[Any] | None,
option_string: str | None = None,
) -> None:
raise NotImplementedError # pragma: no cover
|
_AccessRunObjectAction
|
python
|
euske__pdfminer
|
pdfminer/ccitt.py
|
{
"start": 367,
"end": 1271
}
|
class ____:
def __init__(self):
self._pos = 0
return
@classmethod
def add(klass, root, v, bits):
p = root
b = None
for i in range(len(bits)):
if 0 < i:
if p[b] is None:
p[b] = [None, None]
p = p[b]
if bits[i] == '1':
b = 1
else:
b = 0
p[b] = v
return
def feedbytes(self, data):
for b in data:
for m in (128, 64, 32, 16, 8, 4, 2, 1):
self._parse_bit(b & m)
return
def _parse_bit(self, x):
if x:
v = self._state[1]
else:
v = self._state[0]
self._pos += 1
if isinstance(v, list):
self._state = v
else:
self._state = self._accept(v)
return
## CCITTG4Parser
##
|
BitParser
|
python
|
kamyu104__LeetCode-Solutions
|
Python/basic-calculator-ii.py
|
{
"start": 47,
"end": 1373
}
|
class ____(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
def compute(operands, operators):
right, left = operands.pop(), operands.pop()
operands.append(ops[operators.pop()](left, right))
ops = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}
precedence = {'+':0, '-':0, '*':1, '/':1}
operands, operators, operand = [], [], 0
for i in xrange(len(s)):
if s[i].isdigit():
operand = operand*10 + int(s[i])
if i == len(s)-1 or not s[i+1].isdigit():
operands.append(operand)
operand = 0
elif s[i] == '(':
operators.append(s[i])
elif s[i] == ')':
while operators[-1] != '(':
compute(operands, operators)
operators.pop()
elif s[i] in precedence:
while operators and operators[-1] in precedence and \
precedence[operators[-1]] >= precedence[s[i]]:
compute(operands, operators)
operators.append(s[i])
while operators:
compute(operands, operators)
return operands[-1]
# Time: O(n)
# Space: O(n)
|
Solution
|
python
|
matplotlib__matplotlib
|
lib/matplotlib/rcsetup.py
|
{
"start": 29200,
"end": 52944
}
|
class ____(list):
"""A marker class indicating that a list-of-str is case-insensitive."""
def _convert_validator_spec(key, conv):
if isinstance(conv, list):
ignorecase = isinstance(conv, _ignorecase)
return ValidateInStrings(key, conv, ignorecase=ignorecase)
else:
return conv
# Mapping of rcParams to validators.
# Converters given as lists or _ignorecase are converted to ValidateInStrings
# immediately below.
# The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which
# gets copied to matplotlib/mpl-data/matplotlibrc by the setup script.
_validators = {
"backend": validate_backend,
"backend_fallback": validate_bool,
"figure.hooks": validate_stringlist,
"toolbar": _validate_toolbar,
"interactive": validate_bool,
"timezone": validate_string,
"webagg.port": validate_int,
"webagg.address": validate_string,
"webagg.open_in_browser": validate_bool,
"webagg.port_retries": validate_int,
# line props
"lines.linewidth": validate_float, # line width in points
"lines.linestyle": _validate_linestyle, # solid line
"lines.color": validate_color, # first color in color cycle
"lines.marker": _validate_marker, # marker name
"lines.markerfacecolor": validate_color_or_auto, # default color
"lines.markeredgecolor": validate_color_or_auto, # default color
"lines.markeredgewidth": validate_float,
"lines.markersize": validate_float, # markersize, in points
"lines.antialiased": validate_bool, # antialiased (no jaggies)
"lines.dash_joinstyle": JoinStyle,
"lines.solid_joinstyle": JoinStyle,
"lines.dash_capstyle": CapStyle,
"lines.solid_capstyle": CapStyle,
"lines.dashed_pattern": validate_floatlist,
"lines.dashdot_pattern": validate_floatlist,
"lines.dotted_pattern": validate_floatlist,
"lines.scale_dashes": validate_bool,
# marker props
"markers.fillstyle": validate_fillstyle,
## pcolor(mesh) props:
"pcolor.shading": ["auto", "flat", "nearest", "gouraud"],
"pcolormesh.snap": validate_bool,
## patch props
"patch.linewidth": validate_float, # line width in points
"patch.edgecolor": validate_color,
"patch.force_edgecolor": validate_bool,
"patch.facecolor": validate_color, # first color in cycle
"patch.antialiased": validate_bool, # antialiased (no jaggies)
## hatch props
"hatch.color": _validate_color_or_edge,
"hatch.linewidth": validate_float,
## Histogram properties
"hist.bins": validate_hist_bins,
## Boxplot properties
"boxplot.notch": validate_bool,
"boxplot.vertical": validate_bool,
"boxplot.whiskers": validate_whiskers,
"boxplot.bootstrap": validate_int_or_None,
"boxplot.patchartist": validate_bool,
"boxplot.showmeans": validate_bool,
"boxplot.showcaps": validate_bool,
"boxplot.showbox": validate_bool,
"boxplot.showfliers": validate_bool,
"boxplot.meanline": validate_bool,
"boxplot.flierprops.color": validate_color,
"boxplot.flierprops.marker": _validate_marker,
"boxplot.flierprops.markerfacecolor": validate_color_or_auto,
"boxplot.flierprops.markeredgecolor": validate_color,
"boxplot.flierprops.markeredgewidth": validate_float,
"boxplot.flierprops.markersize": validate_float,
"boxplot.flierprops.linestyle": _validate_linestyle,
"boxplot.flierprops.linewidth": validate_float,
"boxplot.boxprops.color": validate_color,
"boxplot.boxprops.linewidth": validate_float,
"boxplot.boxprops.linestyle": _validate_linestyle,
"boxplot.whiskerprops.color": validate_color,
"boxplot.whiskerprops.linewidth": validate_float,
"boxplot.whiskerprops.linestyle": _validate_linestyle,
"boxplot.capprops.color": validate_color,
"boxplot.capprops.linewidth": validate_float,
"boxplot.capprops.linestyle": _validate_linestyle,
"boxplot.medianprops.color": validate_color,
"boxplot.medianprops.linewidth": validate_float,
"boxplot.medianprops.linestyle": _validate_linestyle,
"boxplot.meanprops.color": validate_color,
"boxplot.meanprops.marker": _validate_marker,
"boxplot.meanprops.markerfacecolor": validate_color,
"boxplot.meanprops.markeredgecolor": validate_color,
"boxplot.meanprops.markersize": validate_float,
"boxplot.meanprops.linestyle": _validate_linestyle,
"boxplot.meanprops.linewidth": validate_float,
## font props
"font.enable_last_resort": validate_bool,
"font.family": validate_stringlist, # used by text object
"font.style": validate_string,
"font.variant": validate_string,
"font.stretch": validate_fontstretch,
"font.weight": validate_fontweight,
"font.size": validate_float, # Base font size in points
"font.serif": validate_stringlist,
"font.sans-serif": validate_stringlist,
"font.cursive": validate_stringlist,
"font.fantasy": validate_stringlist,
"font.monospace": validate_stringlist,
# text props
"text.color": validate_color,
"text.usetex": validate_bool,
"text.latex.preamble": validate_string,
"text.hinting": ["default", "no_autohint", "force_autohint",
"no_hinting", "auto", "native", "either", "none"],
"text.hinting_factor": validate_int,
"text.kerning_factor": validate_int,
"text.antialiased": validate_bool,
"text.parse_math": validate_bool,
"mathtext.cal": validate_font_properties,
"mathtext.rm": validate_font_properties,
"mathtext.tt": validate_font_properties,
"mathtext.it": validate_font_properties,
"mathtext.bf": validate_font_properties,
"mathtext.bfit": validate_font_properties,
"mathtext.sf": validate_font_properties,
"mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix",
"stixsans", "custom"],
"mathtext.default": ["rm", "cal", "bfit", "it", "tt", "sf", "bf", "default",
"bb", "frak", "scr", "regular"],
"mathtext.fallback": _validate_mathtext_fallback,
"image.aspect": validate_aspect, # equal, auto, a number
"image.interpolation": validate_string,
"image.interpolation_stage": ["auto", "data", "rgba"],
"image.cmap": _validate_cmap, # gray, jet, etc.
"image.lut": validate_int, # lookup table
"image.origin": ["upper", "lower"],
"image.resample": validate_bool,
# Specify whether vector graphics backends will combine all images on a
# set of Axes into a single composite image
"image.composite_image": validate_bool,
# contour props
"contour.negative_linestyle": _validate_linestyle,
"contour.corner_mask": validate_bool,
"contour.linewidth": validate_float_or_None,
"contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"],
# errorbar props
"errorbar.capsize": validate_float,
# axis props
# alignment of x/y axis title
"xaxis.labellocation": ["left", "center", "right"],
"yaxis.labellocation": ["bottom", "center", "top"],
# Axes props
"axes.axisbelow": validate_axisbelow,
"axes.facecolor": validate_color, # background color
"axes.edgecolor": validate_color, # edge color
"axes.linewidth": validate_float, # edge linewidth
"axes.spines.left": validate_bool, # Set visibility of axes spines,
"axes.spines.right": validate_bool, # i.e., the lines around the chart
"axes.spines.bottom": validate_bool, # denoting data boundary.
"axes.spines.top": validate_bool,
"axes.titlesize": validate_fontsize, # Axes title fontsize
"axes.titlelocation": ["left", "center", "right"], # Axes title alignment
"axes.titleweight": validate_fontweight, # Axes title font weight
"axes.titlecolor": validate_color_or_auto, # Axes title font color
# title location, axes units, None means auto
"axes.titley": validate_float_or_None,
# pad from Axes top decoration to title in points
"axes.titlepad": validate_float,
"axes.grid": validate_bool, # display grid or not
"axes.grid.which": ["minor", "both", "major"], # which grids are drawn
"axes.grid.axis": ["x", "y", "both"], # grid type
"axes.labelsize": validate_fontsize, # fontsize of x & y labels
"axes.labelpad": validate_float, # space between label and axis
"axes.labelweight": validate_fontweight, # fontsize of x & y labels
"axes.labelcolor": validate_color, # color of axis label
# use scientific notation if log10 of the axis range is smaller than the
# first or larger than the second
"axes.formatter.limits": _listify_validator(validate_int, n=2),
# use current locale to format ticks
"axes.formatter.use_locale": validate_bool,
"axes.formatter.use_mathtext": validate_bool,
# minimum exponent to format in scientific notation
"axes.formatter.min_exponent": validate_int,
"axes.formatter.useoffset": validate_bool,
"axes.formatter.offset_threshold": validate_int,
"axes.unicode_minus": validate_bool,
# This entry can be either a cycler object or a string repr of a
# cycler-object, which gets eval()'ed to create the object.
"axes.prop_cycle": validate_cycler,
# If "data", axes limits are set close to the data.
# If "round_numbers" axes limits are set to the nearest round numbers.
"axes.autolimit_mode": ["data", "round_numbers"],
"axes.xmargin": _validate_greaterthan_minushalf, # margin added to xaxis
"axes.ymargin": _validate_greaterthan_minushalf, # margin added to yaxis
"axes.zmargin": _validate_greaterthan_minushalf, # margin added to zaxis
"polaraxes.grid": validate_bool, # display polar grid or not
"axes3d.grid": validate_bool, # display 3d grid
"axes3d.automargin": validate_bool, # automatically add margin when
# manually setting 3D axis limits
"axes3d.xaxis.panecolor": validate_color, # 3d background pane
"axes3d.yaxis.panecolor": validate_color, # 3d background pane
"axes3d.zaxis.panecolor": validate_color, # 3d background pane
"axes3d.depthshade": validate_bool, # depth shade for 3D scatter plots
"axes3d.depthshade_minalpha": validate_float, # min alpha value for depth shading
"axes3d.mouserotationstyle": ["azel", "trackball", "sphere", "arcball"],
"axes3d.trackballsize": validate_float,
"axes3d.trackballborder": validate_float,
# scatter props
"scatter.marker": _validate_marker,
"scatter.edgecolors": validate_string,
"date.epoch": _validate_date,
"date.autoformatter.year": validate_string,
"date.autoformatter.month": validate_string,
"date.autoformatter.day": validate_string,
"date.autoformatter.hour": validate_string,
"date.autoformatter.minute": validate_string,
"date.autoformatter.second": validate_string,
"date.autoformatter.microsecond": validate_string,
'date.converter': ['auto', 'concise'],
# for auto date locator, choose interval_multiples
'date.interval_multiples': validate_bool,
# legend properties
"legend.fancybox": validate_bool,
"legend.loc": _validate_legend_loc,
# the number of points in the legend line
"legend.numpoints": validate_int,
# the number of points in the legend line for scatter
"legend.scatterpoints": validate_int,
"legend.fontsize": validate_fontsize,
"legend.title_fontsize": validate_fontsize_None,
# color of the legend
"legend.labelcolor": _validate_color_or_linecolor,
# the relative size of legend markers vs. original
"legend.markerscale": validate_float,
# using dict in rcParams not yet supported, so make sure it is bool
"legend.shadow": validate_bool,
# whether or not to draw a frame around legend
"legend.frameon": validate_bool,
# alpha value of the legend frame
"legend.framealpha": validate_float_or_None,
## the following dimensions are in fraction of the font size
"legend.borderpad": validate_float, # units are fontsize
# the vertical space between the legend entries
"legend.labelspacing": validate_float,
# the length of the legend lines
"legend.handlelength": validate_float,
# the length of the legend lines
"legend.handleheight": validate_float,
# the space between the legend line and legend text
"legend.handletextpad": validate_float,
# the border between the Axes and legend edge
"legend.borderaxespad": validate_float,
# the border between the Axes and legend edge
"legend.columnspacing": validate_float,
"legend.facecolor": validate_color_or_inherit,
"legend.edgecolor": validate_color_or_inherit,
# tick properties
"xtick.top": validate_bool, # draw ticks on top side
"xtick.bottom": validate_bool, # draw ticks on bottom side
"xtick.labeltop": validate_bool, # draw label on top
"xtick.labelbottom": validate_bool, # draw label on bottom
"xtick.major.size": validate_float, # major xtick size in points
"xtick.minor.size": validate_float, # minor xtick size in points
"xtick.major.width": validate_float, # major xtick width in points
"xtick.minor.width": validate_float, # minor xtick width in points
"xtick.major.pad": validate_float, # distance to label in points
"xtick.minor.pad": validate_float, # distance to label in points
"xtick.color": validate_color, # color of xticks
"xtick.labelcolor": validate_color_or_inherit, # color of xtick labels
"xtick.minor.visible": validate_bool, # visibility of minor xticks
"xtick.minor.top": validate_bool, # draw top minor xticks
"xtick.minor.bottom": validate_bool, # draw bottom minor xticks
"xtick.major.top": validate_bool, # draw top major xticks
"xtick.major.bottom": validate_bool, # draw bottom major xticks
# number of minor xticks
"xtick.minor.ndivs": _validate_minor_tick_ndivs,
"xtick.labelsize": validate_fontsize, # fontsize of xtick labels
"xtick.direction": ["out", "in", "inout"], # direction of xticks
"xtick.alignment": ["center", "right", "left"],
"ytick.left": validate_bool, # draw ticks on left side
"ytick.right": validate_bool, # draw ticks on right side
"ytick.labelleft": validate_bool, # draw tick labels on left side
"ytick.labelright": validate_bool, # draw tick labels on right side
"ytick.major.size": validate_float, # major ytick size in points
"ytick.minor.size": validate_float, # minor ytick size in points
"ytick.major.width": validate_float, # major ytick width in points
"ytick.minor.width": validate_float, # minor ytick width in points
"ytick.major.pad": validate_float, # distance to label in points
"ytick.minor.pad": validate_float, # distance to label in points
"ytick.color": validate_color, # color of yticks
"ytick.labelcolor": validate_color_or_inherit, # color of ytick labels
"ytick.minor.visible": validate_bool, # visibility of minor yticks
"ytick.minor.left": validate_bool, # draw left minor yticks
"ytick.minor.right": validate_bool, # draw right minor yticks
"ytick.major.left": validate_bool, # draw left major yticks
"ytick.major.right": validate_bool, # draw right major yticks
# number of minor yticks
"ytick.minor.ndivs": _validate_minor_tick_ndivs,
"ytick.labelsize": validate_fontsize, # fontsize of ytick labels
"ytick.direction": ["out", "in", "inout"], # direction of yticks
"ytick.alignment": [
"center", "top", "bottom", "baseline", "center_baseline"],
"grid.color": validate_color, # grid color
"grid.linestyle": _validate_linestyle, # solid
"grid.linewidth": validate_float, # in points
"grid.alpha": validate_float,
"grid.major.color": _validate_color_or_None, # grid color
"grid.major.linestyle": _validate_linestyle_or_None, # solid
"grid.major.linewidth": validate_float_or_None, # in points
"grid.major.alpha": validate_float_or_None,
"grid.minor.color": _validate_color_or_None, # grid color
"grid.minor.linestyle": _validate_linestyle_or_None, # solid
"grid.minor.linewidth": validate_float_or_None, # in points
"grid.minor.alpha": validate_float_or_None,
## figure props
# figure title
"figure.titlesize": validate_fontsize,
"figure.titleweight": validate_fontweight,
# figure labels
"figure.labelsize": validate_fontsize,
"figure.labelweight": validate_fontweight,
# figure size in inches: width by height
"figure.figsize": _listify_validator(validate_float, n=2),
"figure.dpi": validate_float,
"figure.facecolor": validate_color,
"figure.edgecolor": validate_color,
"figure.frameon": validate_bool,
"figure.autolayout": validate_bool,
"figure.max_open_warning": validate_int,
"figure.raise_window": validate_bool,
"macosx.window_mode": ["system", "tab", "window"],
"figure.subplot.left": validate_float,
"figure.subplot.right": validate_float,
"figure.subplot.bottom": validate_float,
"figure.subplot.top": validate_float,
"figure.subplot.wspace": validate_float,
"figure.subplot.hspace": validate_float,
"figure.constrained_layout.use": validate_bool, # run constrained_layout?
# wspace and hspace are fraction of adjacent subplots to use for space.
# Much smaller than above because we don't need room for the text.
"figure.constrained_layout.hspace": validate_float,
"figure.constrained_layout.wspace": validate_float,
# buffer around the Axes, in inches.
"figure.constrained_layout.h_pad": validate_float,
"figure.constrained_layout.w_pad": validate_float,
## Saving figure's properties
'savefig.dpi': validate_dpi,
'savefig.facecolor': validate_color_or_auto,
'savefig.edgecolor': validate_color_or_auto,
'savefig.orientation': ['landscape', 'portrait'],
"savefig.format": validate_string,
"savefig.bbox": validate_bbox, # "tight", or "standard" (= None)
"savefig.pad_inches": validate_float,
# default directory in savefig dialog box
"savefig.directory": _validate_pathlike,
"savefig.transparent": validate_bool,
"tk.window_focus": validate_bool, # Maintain shell focus for TkAgg
# Set the papersize/type
"ps.papersize": _ignorecase(
["figure", "letter", "legal", "ledger",
*[f"{ab}{i}" for ab in "ab" for i in range(11)]]),
"ps.useafm": validate_bool,
# use ghostscript or xpdf to distill ps output
"ps.usedistiller": validate_ps_distiller,
"ps.distiller.res": validate_int, # dpi
"ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
"pdf.compression": validate_int, # 0-9 compression level; 0 to disable
"pdf.inheritcolor": validate_bool, # skip color setting commands
# use only the 14 PDF core fonts embedded in every PDF viewing application
"pdf.use14corefonts": validate_bool,
"pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
"pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
"pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
"pgf.preamble": validate_string, # custom LaTeX preamble
# write raster image data into the svg file
"svg.image_inline": validate_bool,
"svg.fonttype": ["none", "path"], # save text as text ("none") or "paths"
"svg.hashsalt": validate_string_or_None,
"svg.id": validate_string_or_None,
# set this when you want to generate hardcopy docstring
"docstring.hardcopy": validate_bool,
"path.simplify": validate_bool,
"path.simplify_threshold": _validate_greaterequal0_lessequal1,
"path.snap": validate_bool,
"path.sketch": validate_sketch,
"path.effects": validate_anylist,
"agg.path.chunksize": validate_int, # 0 to disable chunking
# key-mappings (multi-character mappings should be a list/tuple)
"keymap.fullscreen": validate_stringlist,
"keymap.home": validate_stringlist,
"keymap.back": validate_stringlist,
"keymap.forward": validate_stringlist,
"keymap.pan": validate_stringlist,
"keymap.zoom": validate_stringlist,
"keymap.save": validate_stringlist,
"keymap.quit": validate_stringlist,
"keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q"
"keymap.grid": validate_stringlist,
"keymap.grid_minor": validate_stringlist,
"keymap.yscale": validate_stringlist,
"keymap.xscale": validate_stringlist,
"keymap.help": validate_stringlist,
"keymap.copy": validate_stringlist,
# Animation settings
"animation.html": ["html5", "jshtml", "none"],
# Limit, in MB, of size of base64 encoded animation in HTML
# (i.e. IPython notebook)
"animation.embed_limit": validate_float,
"animation.writer": validate_string,
"animation.codec": validate_string,
"animation.bitrate": validate_int,
# Controls image format when frames are written to disk
"animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm",
"sgi", "bmp", "pbm", "svg"],
# Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
"animation.ffmpeg_path": _validate_pathlike,
# Additional arguments for ffmpeg movie writer (using pipes)
"animation.ffmpeg_args": validate_stringlist,
# Path to convert binary. If just binary name, subprocess uses $PATH.
"animation.convert_path": _validate_pathlike,
# Additional arguments for convert movie writer (using pipes)
"animation.convert_args": validate_stringlist,
# Classic (pre 2.0) compatibility mode
# This is used for things that are hard to make backward compatible
# with a sane rcParam alone. This does *not* turn on classic mode
# altogether. For that use `matplotlib.style.use("classic")`.
"_internal.classic_mode": validate_bool
}
_hardcoded_defaults = { # Defaults not inferred from
# lib/matplotlib/mpl-data/matplotlibrc...
# ... because they are private:
"_internal.classic_mode": False,
# ... because they are deprecated:
# No current deprecations.
# backend is handled separately when constructing rcParamsDefault.
}
_validators = {k: _convert_validator_spec(k, conv)
for k, conv in _validators.items()}
|
_ignorecase
|
python
|
crytic__slither
|
slither/core/declarations/solidity_import_placeholder.py
|
{
"start": 366,
"end": 1522
}
|
class ____(Variable):
"""
Placeholder for import on top level objects
See the example at https://blog.soliditylang.org/2020/09/02/solidity-0.7.1-release-announcement/
In the long term we should remove this and better integrate import aliases
"""
def __init__(self, import_directive: Import) -> None:
super().__init__()
assert import_directive.alias is not None
self._import_directive = import_directive
self._name = import_directive.alias
self._type = ElementaryType("string")
self._initialized = True
self._visibility = "private"
self._is_constant = True
@property
def type(self) -> ElementaryType:
return ElementaryType("string")
def __eq__(self, other: Union[Contract, SolidityVariable]) -> bool:
return (
self.__class__ == other.__class__
and self._import_directive.filename == self._import_directive.filename
)
@property
def import_directive(self) -> Import:
return self._import_directive
def __hash__(self):
return hash(str(self.import_directive))
|
SolidityImportPlaceHolder
|
python
|
django__django
|
tests/multiple_database/tests.py
|
{
"start": 79782,
"end": 80167
}
|
class ____(TestCase):
databases = {"default", "other"}
def test_pickling(self):
for db in self.databases:
Book.objects.using(db).create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
qs = Book.objects.all()
self.assertEqual(qs.db, pickle.loads(pickle.dumps(qs)).db)
|
PickleQuerySetTestCase
|
python
|
django__django
|
tests/admin_views/models.py
|
{
"start": 7885,
"end": 7989
}
|
class ____(Account):
"""A service-specific account of type Bar."""
servicename = "bar"
|
BarAccount
|
python
|
anthropics__anthropic-sdk-python
|
tests/test_legacy_response.py
|
{
"start": 1930,
"end": 3595
}
|
class ____(BaseModel):
foo: str
bar: int
def test_response_parse_custom_model(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
obj = response.parse(to=CustomModel)
assert obj.foo == "hello!"
assert obj.bar == 2
def test_response_basemodel_request_id(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(
200,
headers={"request-id": "my-req-id"},
content=json.dumps({"foo": "hello!", "bar": 2}),
),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
obj = response.parse(to=CustomModel)
assert obj._request_id == "my-req-id"
assert obj.foo == "hello!"
assert obj.bar == 2
assert obj.to_dict() == {"foo": "hello!", "bar": 2}
def test_response_parse_annotated_type(client: Anthropic) -> None:
response = LegacyAPIResponse(
raw=httpx.Response(200, content=json.dumps({"foo": "hello!", "bar": 2})),
client=client,
stream=False,
stream_cls=None,
cast_to=str,
options=FinalRequestOptions.construct(method="get", url="/foo"),
)
obj = response.parse(
to=cast("type[CustomModel]", Annotated[CustomModel, "random metadata"]),
)
assert obj.foo == "hello!"
assert obj.bar == 2
|
CustomModel
|
python
|
ethereum__web3.py
|
web3/providers/persistent/subscription_container.py
|
{
"start": 137,
"end": 1697
}
|
class ____:
def __init__(self) -> None:
self.subscriptions: list[EthSubscription[Any]] = []
self.subscriptions_by_id: dict[HexStr, EthSubscription[Any]] = {}
self.subscriptions_by_label: dict[str, EthSubscription[Any]] = {}
def __len__(self) -> int:
return len(self.subscriptions)
def __iter__(self) -> Iterator[EthSubscription[Any]]:
return iter(self.subscriptions)
def add_subscription(self, subscription: EthSubscription[Any]) -> None:
self.subscriptions.append(subscription)
self.subscriptions_by_id[subscription.id] = subscription
self.subscriptions_by_label[subscription.label] = subscription
def remove_subscription(self, subscription: EthSubscription[Any]) -> None:
self.subscriptions.remove(subscription)
self.subscriptions_by_id.pop(subscription.id)
self.subscriptions_by_label.pop(subscription.label)
def get_by_id(self, sub_id: HexStr) -> EthSubscription[Any]:
return self.subscriptions_by_id.get(sub_id)
def get_by_label(self, label: str) -> EthSubscription[Any]:
return self.subscriptions_by_label.get(label)
@property
def handler_subscriptions(self) -> list[EthSubscription[Any]]:
return [sub for sub in self.subscriptions if sub._handler is not None]
def get_handler_subscription_by_id(
self, sub_id: HexStr
) -> EthSubscription[Any] | None:
sub = self.get_by_id(sub_id)
if sub and sub._handler:
return sub
return None
|
SubscriptionContainer
|
python
|
django__django
|
tests/delete_regress/models.py
|
{
"start": 2746,
"end": 2805
}
|
class ____(Image):
class Meta:
proxy = True
|
Photo
|
python
|
django__django
|
django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py
|
{
"start": 86,
"end": 802
}
|
class ____(migrations.Migration):
dependencies = [
("auth", "0006_require_contenttypes_0002"),
]
operations = [
migrations.AlterField(
model_name="user",
name="username",
field=models.CharField(
error_messages={"unique": "A user with that username already exists."},
help_text=(
"Required. 30 characters or fewer. Letters, digits and @/./+/-/_ "
"only."
),
max_length=30,
unique=True,
validators=[validators.UnicodeUsernameValidator()],
verbose_name="username",
),
),
]
|
Migration
|
python
|
pytorch__pytorch
|
test/functorch/test_control_flow.py
|
{
"start": 140401,
"end": 155937
}
|
class ____(TestCase):
def setUp(self):
torch._dynamo.reset()
super().setUp()
def _check_autograd(self, result, result_exp, autograd_param):
grad_param = [p for p in autograd_param if p.requires_grad]
result_flatten, _ = pytree.tree_flatten(result)
result_exp_flatten, _ = pytree.tree_flatten(result_exp)
result_flatten = [r for r in result_flatten if r.requires_grad]
result_exp_flatten = [r for r in result_exp_flatten if r.requires_grad]
# Check the result and parameter lists
assert len(result_flatten) == len(result_exp_flatten), (
"The number of elements requiring gradients is different for the results and the expected results"
)
grad_exp_init = [torch.ones_like(el) for el in result_exp_flatten]
expected_grads = torch.autograd.grad(
result_exp_flatten, grad_param, grad_exp_init
)
grad_init = [torch.ones_like(el) for el in result_flatten]
grads = torch.autograd.grad(result_flatten, grad_param, grad_init)
self.assertEqual(grads, expected_grads, atol=6e-05, rtol=6e-06)
def _run_test(self, model, model_fake, inputs, autograd_param=None):
result = model(inputs)
result_exp = model_fake(inputs)
self.assertEqual(result, result_exp)
if autograd_param is not None and any(
par.requires_grad for par in autograd_param
):
result_flat = pytree.tree_leaves(result)
result_exp_flat = pytree.tree_leaves(result_exp)
exp_grad_mask = [bool(r.requires_grad) for r in result_exp_flat]
self._check_autograd(
[r for r, m in zip(result_flat, exp_grad_mask) if m],
[r for r, m in zip(result_exp_flat, exp_grad_mask) if m],
autograd_param,
)
# Return the result of the functions under test for further investigations
return result
def _prepare_fake_kwargs(self, original_kwargs):
kwargs_fake = original_kwargs.copy()
kwargs_fake["compile_mode"] = "fake"
return kwargs_fake
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("reverse", [False, True])
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("combine_mode", ["pointwise", "generic"])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
# Skipping the combination of combine_mode=pointwise and device=cpu
# as the current implementation of pointwise does only support CUDA device
# Skipping the combination of combine_mode=pointwise and compile_mode=compile_dynamic_shape
# as the current implementation does not support lifted arguments
@decorateIf(
unittest.skip,
lambda params: (
params["combine_mode"] == "pointwise"
and (
params["device"] == torch.device("cpu")
or params["compile_mode"] == "compile_dynamic_shape"
)
),
)
# # Skipping this combination as there is a CPP compilation failure that
# # may be unrelated to associative_scan itself. There is a dedicated tests for
# # this case below.
# @decorateIf(
# unittest.skip,
# lambda params: (
# params["compile_mode"] == "compile_dynamic_shape"
# and params["combine_mode"] == "generic"
# and params["device"] == torch.device("cpu")
# and params["autograd"]
# ),
# )
def test_associative_scan_compile(
self, combine_mode, reverse, compile_mode, device, autograd
):
x = torch.randn(3, 10, 2, device=device, requires_grad=autograd)
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_mode": combine_mode,
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
results = self._run_test(
model=AssociativeScanModels.Simple(**kwargs),
model_fake=AssociativeScanModels.Simple(**kwargs_fake),
inputs=x,
autograd_param=None if not autograd else (x,),
)
if not reverse:
results_torch = []
for op_pt in [torch.cumsum, torch.cumprod]:
results_torch.append(op_pt(x, 0))
self.assertEqual(results, results_torch)
# Jax Examples
x = torch.arange(
0, 4, device=device, dtype=torch.float32, requires_grad=autograd
)
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_fn": get_scan_combine_fn("add", True),
"combine_mode": combine_mode,
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
result = self._run_test(
model=AssociativeScanModels.CombineFn(**kwargs),
model_fake=AssociativeScanModels.CombineFn(**kwargs_fake),
inputs=x,
autograd_param=None if not autograd else (x,),
)
if not reverse:
results_torch = torch.tensor([0.0, 1.0, 3.0, 6.0], dtype=torch.float32)
else:
results_torch = torch.tensor([6.0, 6.0, 5.0, 3.0], dtype=torch.float32)
self.assertEqual(result, results_torch)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("reverse", [False, True])
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("combine_mode", ["pointwise", "generic"])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
# Skipping the combination of combine_mode=pointwise and device=cpu
# as the current implementation of pointwise does only support CUDA device
# Skipping the combination of combine_mode=pointwise and compile_mode=compile_dynamic_shape
# as the current implementation does not support lifted arguments
@decorateIf(
unittest.skip,
lambda params: (
params["combine_mode"] == "pointwise"
and (
params["device"] == torch.device("cpu")
or params["compile_mode"] == "compile_dynamic_shape"
)
),
)
def test_associative_scan_dim(
self, combine_mode, compile_mode, reverse, device, autograd
):
import random
random.seed(1234)
num_dims = [random.randint(2, 5) for _ in range(4)]
for num_dim in num_dims:
# To avoid triggering automatic dynamic shape
torch._dynamo.reset()
shapes = [random.randint(1, 9) for _ in range(num_dim)]
rnd_scan_dim = random.randint(0, num_dim - 1)
x = torch.randn(*shapes, device=device, requires_grad=autograd)
kwargs = {
"dim": rnd_scan_dim,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_mode": combine_mode,
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
results = self._run_test(
model=AssociativeScanModels.Simple(**kwargs),
model_fake=AssociativeScanModels.Simple(**kwargs_fake),
inputs=x,
autograd_param=None if not autograd else (x,),
)
if not reverse:
results_torch = []
for op_pt in [torch.cumsum, torch.cumprod]:
results_torch.append(op_pt(x, 0))
self.assertEqual(results, results_torch)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@unittest.expectedFailure
def test_associative_scan_dim_shape_failure(self, compile_mode, combine_mode):
num_dims = [2]
for num_dim in num_dims:
shapes = [9 for _ in range(num_dim)]
rnd_scan_dim = 0
x = torch.randn(*shapes, device=torch.device("cuda"))
kwargs = {
"dim": rnd_scan_dim,
"reverse": True,
"compile_mode": "compile",
"combine_mode": "generic",
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
self._run_test(
model=AssociativeScanModels.Simple(**kwargs),
model_fake=AssociativeScanModels.Simple(**kwargs_fake),
inputs=x,
)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("combine_mode", ["pointwise", "generic"])
@parametrize("reverse", [False, True])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
# Skipping the combination of combine_mode=pointwise and device=cpu
# as the current implementation of pointwise does only support CUDA device
# Skipping the combination of combine_mode=pointwise and compile_mode=compile_dynamic_shape
# as the current implementation does not support lifted arguments
@decorateIf(
unittest.skip,
lambda params: (
params["combine_mode"] == "pointwise"
and (
params["device"] == torch.device("cpu")
or params["compile_mode"] == "compile_dynamic_shape"
)
),
)
def test_associative_scan_tuple(
self, compile_mode, combine_mode, reverse, device, autograd
):
x = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
y = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
inp = (x, y)
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_fn": get_scan_combine_fn("tuple_fct", True),
"combine_mode": combine_mode,
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
self._run_test(
model=AssociativeScanModels.CombineFn(**kwargs),
model_fake=AssociativeScanModels.CombineFn(**kwargs_fake),
inputs=inp,
autograd_param=None if not autograd else inp,
)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("reverse", [False, True])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
def test_associative_scan_expand_in_combine_fn(
self, compile_mode, reverse, device, autograd
):
x = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
def combine_fn(x, y):
return x * torch.sum(y, -1).expand(x.shape)
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_fn": combine_fn,
"combine_mode": "generic",
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
self._run_test(
model=AssociativeScanModels.CombineFn(**kwargs),
model_fake=AssociativeScanModels.CombineFn(**kwargs_fake),
inputs=x,
autograd_param=None if not autograd else (x,),
)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("reverse", [False, True])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
def test_associative_scan_non_contiguous_tensor(
self, compile_mode, reverse, device, autograd
):
x = (
torch.arange(30, device=device, dtype=torch.float32, requires_grad=autograd)
.view(10, 3)
.t()
)
assert not x.is_contiguous()
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_fn": get_scan_combine_fn("add", True),
"combine_mode": "generic",
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
self._run_test(
model=AssociativeScanModels.CombineFn(**kwargs),
model_fake=AssociativeScanModels.CombineFn(**kwargs_fake),
inputs=x,
autograd_param=None if not autograd else (x,),
)
@unittest.skipIf(not SM70OrLater, "triton")
@requires_cuda
@parametrize("compile_mode", ["none", "eager", "compile", "compile_dynamic_shape"])
@parametrize("combine_mode", ["pointwise", "generic"])
@parametrize("reverse", [False, True])
@parametrize("device", [torch.device("cpu"), torch.device("cuda")])
@parametrize("autograd", [False, True])
# Skipping the combination of combine_mode=pointwise and device=cpu
# as the current implementation of pointwise does only support CUDA device
# Skipping the combination of combine_mode=pointwise and compile_mode=compile_dynamic_shape
# as the current implementation does not support lifted arguments
@decorateIf(
unittest.skip,
lambda params: (
params["combine_mode"] == "pointwise"
and (
params["device"] == torch.device("cpu")
or params["compile_mode"] == "compile_dynamic_shape"
)
),
)
def test_associative_scan_complex_pytree(
self, compile_mode, combine_mode, reverse, device, autograd
):
x = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
y = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
z = torch.randn(3, 2, 2, device=device, requires_grad=autograd)
inp = {"i": x, "j": ([y], [{"o": z}])}
kwargs = {
"dim": 0,
"reverse": reverse,
"compile_mode": compile_mode,
"combine_fn": get_scan_combine_fn("complex_pointwise", True),
"combine_mode": combine_mode,
}
kwargs_fake = self._prepare_fake_kwargs(kwargs)
self._run_test(
model=AssociativeScanModels.CombineFn(**kwargs),
model_fake=AssociativeScanModels.CombineFn(**kwargs_fake),
inputs=inp,
autograd_param=None if not autograd else (x, y, z),
)
@skipIfTorchDynamo("don't test compile on compile")
@skipIfNoDynamoSupport
@skipIfCrossRef # Arg order changes with crossref
def test_associative_scan_pytree_output(self):
x = (
(
torch.randn(3, 10, 2, device=torch.device("cpu")),
(torch.randn(3, 10, 2, device=torch.device("cpu")),),
),
torch.randn(3, 10, 2, device=torch.device("cpu")),
)
def f(fct, xs):
return associative_scan(
fct, xs, dim=0, reverse=True, combine_mode="generic"
)
def combine_fn(x: torch.Tensor, y: torch.Tensor):
a, b = (x[0][0] + y[1], x[0][1][0] - y[1])
return (a, (b,)), a - b
# Check graph
backend = EagerAndRecordGraphs()
torch.compile(f, backend=backend)(combine_fn, x)
gm = backend.graphs[0]
self.assertExpectedInline(
normalize_gm(gm.print_readable(print_output=False)),
"""\
|
AssociativeScanTests
|
python
|
tensorflow__tensorflow
|
tensorflow/compiler/mlir/quantization/tensorflow/python/integration_test/quantize_model_test.py
|
{
"start": 6893,
"end": 13005
}
|
class ____(quantize_model_test_base.QuantizedModelTest):
"""Test cases regarding the use of QuantizationOptions proto.
Run all tests cases in both the graph mode (default in TF1) and the eager mode
(default in TF2) to ensure support for when TF2 is disabled.
"""
class SimpleModel(module.Module):
def __init__(self):
self.filters = np.random.uniform(low=-1.0, high=1.0, size=(4, 3)).astype(
'f4'
)
@def_function.function(
input_signature=[
tensor_spec.TensorSpec(shape=[1, 4], dtype=dtypes.float32)
]
)
def __call__(self, input_tensor: core.Tensor) -> Mapping[str, core.Tensor]:
"""Performs a matrix multiplication.
Args:
input_tensor: Input tensor to matmul with the filter.
Returns:
A map of: output key -> output result.
"""
out = math_ops.matmul(input_tensor, self.filters)
return {'output': out}
def _simple_model_data_gen(self) -> repr_dataset.RepresentativeDataset:
"""Creates an interable of representative samples.
Yields:
Representative samples, which is basically a mapping of: input key ->
input value.
"""
for _ in range(8):
yield {
'input_tensor': ops.convert_to_tensor(
np.random.uniform(low=0, high=150, size=(1, 4)).astype('f4')
),
}
def test_static_range_quantization_by_default(self):
model = self.SimpleModel()
saved_model_save.save(model, self._input_saved_model_path)
# Use default QuantizationOptions.
converted_model = quantize_model.quantize(
self._input_saved_model_path,
representative_dataset=self._simple_model_data_gen(),
)
self.assertIsNotNone(converted_model)
self.assertCountEqual(
converted_model.signatures._signatures.keys(), {'serving_default'}
)
# Indirectly prove that it is performing a static-range quantization
# by checking that it complains about representative_dataset when it is
# not provided.
with self.assertRaisesRegex(ValueError, 'representative_dataset'):
quantize_model.quantize(self._input_saved_model_path)
def test_method_unspecified_raises_value_error(self):
model = self.SimpleModel()
saved_model_save.save(model, self._input_saved_model_path)
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(
preset_method=_PresetMethod.METHOD_UNSPECIFIED
)
)
with self.assertRaises(ValueError):
quantize_model.quantize(
self._input_saved_model_path, quantization_options=options
)
def test_predefined_method_component_spec(self):
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(
preset_method=_PresetMethod.METHOD_STATIC_RANGE_INT8
)
)
quantize_model._populate_quantization_component_spec(
options.quantization_method
)
# Quantize activation, weight and bias for static range quantization.
self.assertLen(options.quantization_method.quantization_component_specs, 3)
def test_invalid_spec_raise_value_error(self):
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(
quantization_component_specs=[
quant_opts_pb2.QuantizationComponentSpec(
quantization_component=(
_QuantizationComponent.COMPONENT_ACTIVATION
),
tensor_type=_TensorType.TENSORTYPE_INT_4,
)
]
)
)
with self.assertRaises(ValueError):
# Activation 4bit is not a valid configuration.
quantize_model._populate_quantization_component_spec(
options.quantization_method
)
def test_invalid_method_raises_value_error(self):
model = self.SimpleModel()
saved_model_save.save(model, self._input_saved_model_path)
# Set an invalid value of -1 to QuantizationMethod.preset_method.
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(preset_method=-1)
)
with self.assertRaises(ValueError):
quantize_model.quantize(
self._input_saved_model_path, quantization_options=options
)
def test_drq_per_channel_for_non_uniform_opset_raises_value_error(
self,
):
model = self.SimpleModel()
saved_model_save.save(model, self._input_saved_model_path)
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(
preset_method=_PresetMethod.METHOD_DYNAMIC_RANGE_INT8
),
op_set=quant_opts_pb2.TF,
enable_per_channel_quantization=True,
)
with self.assertRaises(ValueError):
quantize_model.quantize(
self._input_saved_model_path, quantization_options=options
)
def test_force_graph_mode_calibration(self):
model = self.SimpleModel()
saved_model_save.save(model, self._input_saved_model_path)
options = quant_opts_pb2.QuantizationOptions(
quantization_method=quant_opts_pb2.QuantizationMethod(
preset_method=_PresetMethod.METHOD_STATIC_RANGE_INT8
),
op_set=quant_opts_pb2.TF,
force_graph_mode_calibration=True,
)
with self.assertLogs(level='INFO') as info_logs:
# Save the logger verbosity.
prev_log_level = logging.get_verbosity()
logging.set_verbosity(logging.INFO)
try:
quantize_model.quantize(
self._input_saved_model_path,
quantization_options=options,
representative_dataset=self._simple_model_data_gen(),
)
finally:
# Restore the logger verbosity.
logging.set_verbosity(prev_log_level)
self.assertNotEmpty(info_logs.records)
self.assertTrue(
self._any_log_contains(
'Calibration step is executed in graph mode.',
info_logs.records,
)
)
|
QuantizationOptionsTest
|
python
|
google__pytype
|
pytype/abstract/abstract_utils.py
|
{
"start": 2669,
"end": 2815
}
|
class ____:
def __init__(self, container):
self.container = container
DUMMY_CONTAINER: DummyContainer = DummyContainer(None)
|
DummyContainer
|
python
|
realpython__materials
|
bulk-file-rename-tool-python/source_code_final/rprename/rename.py
|
{
"start": 182,
"end": 941
}
|
class ____(QObject):
# Define custom signals
progressed = pyqtSignal(int)
renamedFile = pyqtSignal(Path)
finished = pyqtSignal()
def __init__(self, files, prefix):
super().__init__()
self._files = files
self._prefix = prefix
def renameFiles(self):
for fileNumber, file in enumerate(self._files, 1):
newFile = file.parent.joinpath(
f"{self._prefix}{str(fileNumber)}{file.suffix}"
)
file.rename(newFile)
time.sleep(0.1) # Comment this line to rename files faster.
self.progressed.emit(fileNumber)
self.renamedFile.emit(newFile)
self.progressed.emit(0) # Reset the progress
self.finished.emit()
|
Renamer
|
python
|
bokeh__bokeh
|
src/bokeh/plotting/contour.py
|
{
"start": 2378,
"end": 2562
}
|
class ____:
''' Coordinates for all contour lines over a whole sequence of contour levels.
'''
xs: list[np.ndarray]
ys: list[np.ndarray]
@dataclass(frozen=True)
|
LineCoords
|
python
|
apache__airflow
|
airflow-core/src/airflow/api_fastapi/core_api/datamodels/hitl.py
|
{
"start": 3022,
"end": 3146
}
|
class ____(BaseHITLDetail):
"""Schema for Human-in-the-loop detail."""
task_instance: TaskInstanceResponse
|
HITLDetail
|
python
|
pytest-dev__pytest
|
testing/acceptance_test.py
|
{
"start": 534,
"end": 19961
}
|
class ____:
def test_config_error(self, pytester: Pytester) -> None:
pytester.copy_example("conftest_usageerror/conftest.py")
result = pytester.runpytest(pytester.path)
assert result.ret == ExitCode.USAGE_ERROR
result.stderr.fnmatch_lines(["*ERROR: hello"])
result.stdout.fnmatch_lines(["*pytest_unconfigure_called"])
def test_root_conftest_syntax_error(self, pytester: Pytester) -> None:
pytester.makepyfile(conftest="raise SyntaxError\n")
result = pytester.runpytest()
result.stderr.fnmatch_lines(["*raise SyntaxError*"])
assert result.ret != 0
def test_early_hook_error_issue38_1(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_sessionstart():
0 / 0
"""
)
result = pytester.runpytest(pytester.path)
assert result.ret != 0
# tracestyle is native by default for hook failures
result.stdout.fnmatch_lines(
["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
)
result = pytester.runpytest(pytester.path, "--fulltrace")
assert result.ret != 0
# tracestyle is native by default for hook failures
result.stdout.fnmatch_lines(
["*INTERNALERROR*def pytest_sessionstart():*", "*INTERNALERROR*0 / 0*"]
)
def test_early_hook_configure_error_issue38(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_configure():
0 / 0
"""
)
result = pytester.runpytest(pytester.path)
assert result.ret != 0
# here we get it on stderr
result.stderr.fnmatch_lines(
["*INTERNALERROR*File*conftest.py*line 2*", "*0 / 0*"]
)
def test_file_not_found(self, pytester: Pytester) -> None:
result = pytester.runpytest("asd")
assert result.ret != 0
result.stderr.fnmatch_lines(["ERROR: file or directory not found: asd"])
def test_file_not_found_unconfigure_issue143(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_configure():
print("---configure")
def pytest_unconfigure():
print("---unconfigure")
"""
)
result = pytester.runpytest("-s", "asd")
assert result.ret == ExitCode.USAGE_ERROR
result.stderr.fnmatch_lines(["ERROR: file or directory not found: asd"])
result.stdout.fnmatch_lines(["*---configure", "*---unconfigure"])
def test_config_preparse_plugin_option(self, pytester: Pytester) -> None:
pytester.makepyfile(
pytest_xyz="""
def pytest_addoption(parser):
parser.addoption("--xyz", dest="xyz", action="store")
"""
)
pytester.makepyfile(
test_one="""
def test_option(pytestconfig):
assert pytestconfig.option.xyz == "123"
"""
)
result = pytester.runpytest("-p", "pytest_xyz", "--xyz=123", syspathinsert=True)
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
@pytest.mark.parametrize("load_cov_early", [True, False])
def test_early_load_setuptools_name(
self, pytester: Pytester, monkeypatch, load_cov_early
) -> None:
monkeypatch.delenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
pytester.makepyfile(mytestplugin1_module="")
pytester.makepyfile(mytestplugin2_module="")
pytester.makepyfile(mycov_module="")
pytester.syspathinsert()
loaded = []
@dataclasses.dataclass
class DummyEntryPoint:
name: str
module: str
group: str = "pytest11"
def load(self):
mod = importlib.import_module(self.module)
loaded.append(self.name)
return mod
entry_points = [
DummyEntryPoint("myplugin1", "mytestplugin1_module"),
DummyEntryPoint("myplugin2", "mytestplugin2_module"),
DummyEntryPoint("mycov", "mycov_module"),
]
@dataclasses.dataclass
class DummyDist:
entry_points: object
files: object = ()
def my_dists():
return (DummyDist(entry_points),)
monkeypatch.setattr(importlib.metadata, "distributions", my_dists)
params = ("-p", "mycov") if load_cov_early else ()
pytester.runpytest_inprocess(*params)
if load_cov_early:
assert loaded == ["mycov", "myplugin1", "myplugin2"]
else:
assert loaded == ["myplugin1", "myplugin2", "mycov"]
@pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"])
def test_assertion_rewrite(self, pytester: Pytester, import_mode) -> None:
p = pytester.makepyfile(
"""
def test_this():
x = 0
assert x
"""
)
result = pytester.runpytest(p, f"--import-mode={import_mode}")
result.stdout.fnmatch_lines(["> assert x", "E assert 0"])
assert result.ret == 1
def test_nested_import_error(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import import_fails
def test_this():
assert import_fails.a == 1
"""
)
pytester.makepyfile(import_fails="import does_not_work")
result = pytester.runpytest(p)
result.stdout.fnmatch_lines(
[
"ImportError while importing test module*",
"*No module named *does_not_work*",
]
)
assert result.ret == 2
def test_not_collectable_arguments(self, pytester: Pytester) -> None:
p1 = pytester.makepyfile("")
p2 = pytester.makefile(".pyc", "123")
result = pytester.runpytest(p1, p2)
assert result.ret == ExitCode.USAGE_ERROR
result.stderr.fnmatch_lines(
[
f"ERROR: not found: {p2}",
"(no match in any of *)",
"",
]
)
@pytest.mark.filterwarnings("default")
def test_better_reporting_on_conftest_load_failure(
self, pytester: Pytester
) -> None:
"""Show a user-friendly traceback on conftest import failures (#486, #3332)"""
pytester.makepyfile("")
conftest = pytester.makeconftest(
"""
def foo():
import qwerty
foo()
"""
)
result = pytester.runpytest("--help")
result.stdout.fnmatch_lines(
"""
*--version*
*warning*conftest.py*
"""
)
result = pytester.runpytest()
assert result.stdout.lines == []
assert result.stderr.lines == [
f"ImportError while loading conftest '{conftest}'.",
"conftest.py:3: in <module>",
" foo()",
"conftest.py:2: in foo",
" import qwerty",
"E ModuleNotFoundError: No module named 'qwerty'",
]
def test_early_skip(self, pytester: Pytester) -> None:
pytester.mkdir("xyz")
pytester.makeconftest(
"""
import pytest
def pytest_collect_file():
pytest.skip("early")
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
result.stdout.fnmatch_lines(["*1 skip*"])
def test_issue88_initial_file_multinodes(self, pytester: Pytester) -> None:
pytester.copy_example("issue88_initial_file_multinodes")
p = pytester.makepyfile("def test_hello(): pass")
result = pytester.runpytest(p, "--collect-only")
result.stdout.fnmatch_lines(["*MyFile*test_issue88*", "*Module*test_issue88*"])
def test_issue93_initialnode_importing_capturing(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import sys
print("should not be seen")
sys.stderr.write("stder42\\n")
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
result.stdout.no_fnmatch_line("*should not be seen*")
assert "stderr42" not in result.stderr.str()
def test_conftest_printing_shows_if_error(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
print("should be seen")
assert 0
"""
)
result = pytester.runpytest()
assert result.ret != 0
assert "should be seen" in result.stdout.str()
def test_issue109_sibling_conftests_not_loaded(self, pytester: Pytester) -> None:
sub1 = pytester.mkdir("sub1")
sub2 = pytester.mkdir("sub2")
sub1.joinpath("conftest.py").write_text("assert 0", encoding="utf-8")
result = pytester.runpytest(sub2)
assert result.ret == ExitCode.NO_TESTS_COLLECTED
sub2.joinpath("__init__.py").touch()
p = sub2.joinpath("test_hello.py")
p.touch()
result = pytester.runpytest(p)
assert result.ret == ExitCode.NO_TESTS_COLLECTED
result = pytester.runpytest(sub1)
assert result.ret == ExitCode.USAGE_ERROR
def test_directory_skipped(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
def pytest_ignore_collect():
pytest.skip("intentional")
"""
)
pytester.makepyfile("def test_hello(): pass")
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
result.stdout.fnmatch_lines(["*1 skipped*"])
def test_multiple_items_per_collector_byid(self, pytester: Pytester) -> None:
c = pytester.makeconftest(
"""
import pytest
class MyItem(pytest.Item):
def runtest(self):
pass
class MyCollector(pytest.File):
def collect(self):
return [MyItem.from_parent(name="xyz", parent=self)]
def pytest_collect_file(file_path, parent):
if file_path.name.startswith("conftest"):
return MyCollector.from_parent(path=file_path, parent=parent)
"""
)
result = pytester.runpytest(c.name + "::" + "xyz")
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 pass*"])
def test_skip_on_generated_funcarg_id(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize('x', [3], ids=['hello-123'])
def pytest_runtest_setup(item):
print(item.keywords)
if 'hello-123' in item.keywords:
pytest.skip("hello")
assert 0
"""
)
p = pytester.makepyfile("""def test_func(x): pass""")
res = pytester.runpytest(p)
assert res.ret == 0
res.stdout.fnmatch_lines(["*1 skipped*"])
def test_direct_addressing_selects(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize('i', [1, 2], ids=["1", "2"])
def test_func(i):
pass
"""
)
res = pytester.runpytest(p.name + "::" + "test_func[1]")
assert res.ret == 0
res.stdout.fnmatch_lines(["*1 passed*"])
def test_direct_addressing_selects_duplicates(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("a", [1, 2, 10, 11, 2, 1, 12, 11])
def test_func(a):
pass
"""
)
result = pytester.runpytest(p)
result.assert_outcomes(failed=0, passed=8)
def test_direct_addressing_selects_duplicates_1(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("a", [1, 2, 10, 11, 2, 1, 12, 1_1,2_1])
def test_func(a):
pass
"""
)
result = pytester.runpytest(p)
result.assert_outcomes(failed=0, passed=9)
def test_direct_addressing_selects_duplicates_2(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("a", ["a","b","c","a","a1"])
def test_func(a):
pass
"""
)
result = pytester.runpytest(p)
result.assert_outcomes(failed=0, passed=5)
def test_direct_addressing_notfound(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def test_func():
pass
"""
)
res = pytester.runpytest(p.name + "::" + "test_notfound")
assert res.ret
res.stderr.fnmatch_lines(["*ERROR*not found*"])
def test_docstring_on_hookspec(self) -> None:
from _pytest import hookspec
for name, value in vars(hookspec).items():
if name.startswith("pytest_"):
assert value.__doc__, f"no docstring for {name}"
def test_initialization_error_issue49(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_configure():
x
"""
)
result = pytester.runpytest()
assert result.ret == 3 # internal error
result.stderr.fnmatch_lines(["INTERNAL*pytest_configure*", "INTERNAL*x*"])
assert "sessionstarttime" not in result.stderr.str()
@pytest.mark.parametrize("lookfor", ["test_fun.py::test_a"])
def test_issue134_report_error_when_collecting_member(
self, pytester: Pytester, lookfor
) -> None:
pytester.makepyfile(
test_fun="""
def test_a():
pass
def"""
)
result = pytester.runpytest(lookfor)
result.stdout.fnmatch_lines(["*SyntaxError*"])
if "::" in lookfor:
result.stderr.fnmatch_lines(["*ERROR*"])
assert result.ret == 4 # usage error only if item not found
def test_report_all_failed_collections_initargs(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
from _pytest.config import ExitCode
def pytest_sessionfinish(exitstatus):
assert exitstatus == ExitCode.USAGE_ERROR
print("pytest_sessionfinish_called")
"""
)
pytester.makepyfile(test_a="def", test_b="def")
result = pytester.runpytest("test_a.py::a", "test_b.py::b")
result.stderr.fnmatch_lines(["*ERROR*test_a.py::a*", "*ERROR*test_b.py::b*"])
result.stdout.fnmatch_lines(["pytest_sessionfinish_called"])
assert result.ret == ExitCode.USAGE_ERROR
def test_namespace_import_doesnt_confuse_import_hook(
self, pytester: Pytester
) -> None:
"""Ref #383.
Python 3.3's namespace package messed with our import hooks.
Importing a module that didn't exist, even if the ImportError was
gracefully handled, would make our test crash.
"""
pytester.mkdir("not_a_package")
p = pytester.makepyfile(
"""
try:
from not_a_package import doesnt_exist
except ImportError:
# We handle the import error gracefully here
pass
def test_whatever():
pass
"""
)
res = pytester.runpytest(p.name)
assert res.ret == 0
def test_unknown_option(self, pytester: Pytester) -> None:
result = pytester.runpytest("--qwlkej")
result.stderr.fnmatch_lines(
"""
*unrecognized*
"""
)
def test_getsourcelines_error_issue553(
self, pytester: Pytester, monkeypatch
) -> None:
monkeypatch.setattr("inspect.getsourcelines", None)
p = pytester.makepyfile(
"""
def raise_error(obj):
raise OSError('source code not available')
import inspect
inspect.getsourcelines = raise_error
def test_foo(invalid_fixture):
pass
"""
)
res = pytester.runpytest(p)
res.stdout.fnmatch_lines(
["*source code not available*", "E*fixture 'invalid_fixture' not found"]
)
def test_plugins_given_as_strings(
self, pytester: Pytester, monkeypatch, _sys_snapshot
) -> None:
"""Test that str values passed to main() as `plugins` arg are
interpreted as module names to be imported and registered (#855)."""
with pytest.raises(ImportError) as excinfo:
pytest.main([str(pytester.path)], plugins=["invalid.module"])
assert "invalid" in str(excinfo.value)
p = pytester.path.joinpath("test_test_plugins_given_as_strings.py")
p.write_text("def test_foo(): pass", encoding="utf-8")
mod = types.ModuleType("myplugin")
monkeypatch.setitem(sys.modules, "myplugin", mod)
assert pytest.main(args=[str(pytester.path)], plugins=["myplugin"]) == 0
def test_parametrized_with_bytes_regex(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import re
import pytest
@pytest.mark.parametrize('r', [re.compile(b'foo')])
def test_stuff(r):
pass
"""
)
res = pytester.runpytest(p)
res.stdout.fnmatch_lines(["*1 passed*"])
def test_parametrized_with_null_bytes(self, pytester: Pytester) -> None:
"""Test parametrization with values that contain null bytes and unicode characters (#2644, #2957)"""
p = pytester.makepyfile(
"""\
import pytest
@pytest.mark.parametrize("data", [b"\\x00", "\\x00", 'ação'])
def test_foo(data):
assert data
"""
)
res = pytester.runpytest(p)
res.assert_outcomes(passed=3)
# Warning ignore because of:
# https://github.com/python/cpython/issues/85308
# Can be removed once Python<3.12 support is dropped.
@pytest.mark.filterwarnings("ignore:'encoding' argument not specified")
def test_command_line_args_from_file(
self, pytester: Pytester, tmp_path: Path
) -> None:
pytester.makepyfile(
test_file="""
import pytest
class TestClass:
@pytest.mark.parametrize("a", ["x","y"])
def test_func(self, a):
pass
"""
)
tests = [
"test_file.py::TestClass::test_func[x]",
"test_file.py::TestClass::test_func[y]",
"-q",
]
args_file = pytester.maketxtfile(tests="\n".join(tests))
result = pytester.runpytest(f"@{args_file}")
result.assert_outcomes(failed=0, passed=2)
|
TestGeneralUsage
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-sftp-bulk/source_sftp_bulk/client.py
|
{
"start": 516,
"end": 2838
}
|
class ____:
_connection: paramiko.SFTPClient = None
def __init__(
self,
host: str,
username: str,
password: str = None,
private_key: Optional[str] = None,
port: Optional[int] = None,
timeout: Optional[int] = REQUEST_TIMEOUT,
):
self.host = host
self.username = username
self.password = password
self.port = int(port) or 22
self.key = paramiko.RSAKey.from_private_key(io.StringIO(private_key)) if private_key else None
self.timeout = float(timeout) if timeout else REQUEST_TIMEOUT
self._connect()
# If connection is snapped during connect flow, retry up to a
# minute for SSH connection to succeed. 2^6 + 2^5 + ...
@backoff.on_exception(backoff.expo, EOFError, max_tries=6, on_backoff=handle_backoff, jitter=None, factor=2)
def _connect(self):
if self._connection is not None:
return
try:
self.transport = paramiko.Transport((self.host, self.port))
self.transport.use_compression(True)
self.transport.connect(username=self.username, password=self.password, hostkey=None, pkey=self.key)
self._connection = paramiko.SFTPClient.from_transport(self.transport)
# get 'socket' to set the timeout
socket = self._connection.get_channel()
# set request timeout
socket.settimeout(self.timeout)
except AuthenticationException as ex:
raise AirbyteTracedException(
failure_type=FailureType.config_error,
message="SSH Authentication failed, please check username, password or private key and try again",
internal_message="Authentication failed: %s" % ex,
)
def __del__(self):
if self._connection is not None:
try:
self._connection.close()
self.transport.close()
self._connection = None
# Known paramiko issue: https://github.com/paramiko/paramiko/issues/1617
except Exception as e:
if str(e) != "'NoneType' object has no attribute 'time'":
raise
@property
def sftp_connection(self) -> paramiko.SFTPClient:
return self._connection
|
SFTPClient
|
python
|
airbytehq__airbyte
|
airbyte-ci/connectors/connectors_insights/src/connectors_insights/result_backends.py
|
{
"start": 1402,
"end": 2499
}
|
class ____(ResultBackend):
def __init__(self, local_directory: Path):
super().__init__()
if not local_directory.exists():
local_directory.mkdir(parents=True)
self.local_directory = local_directory
def _write(self, connector: Connector, file_to_persist: FileToPersist) -> None:
assert file_to_persist.file_content is not None
connector_result_directory = self.local_directory / connector.technical_name / connector.version
connector_result_directory.mkdir(parents=True, exist_ok=True)
file_path = connector_result_directory / file_to_persist.file_name
with open(file_path, "w") as f:
f.write(file_to_persist.file_content)
self.logger.info(f"{file_to_persist.file_name} written to {file_path}")
def artifact_already_exists(self, connector: Connector, file_to_persist: FileToPersist) -> bool:
connector_result_directory = self.local_directory / connector.technical_name / connector.version
return (connector_result_directory / file_to_persist.file_name).exists()
|
LocalDir
|
python
|
getsentry__sentry
|
fixtures/integrations/jira/mock.py
|
{
"start": 160,
"end": 2876
}
|
class ____(StubJiraApiClient, MockService):
def get_projects_list(self, cached: bool = True):
"""
List all projects in the Jira data format.
:return: list of project objects
"""
return [
{
"self": f"http://www.example.com/jira/rest/api/2/project/{project_name}",
"id": project_name,
"key": project_name,
"name": project_name,
"projectCategory": {
"self": f"http://www.example.com/jira/rest/api/2/projectCategory/{project_name}",
"id": project_name,
"name": project_name,
"description": project_name,
},
"simplified": False,
}
for project_name in self._get_project_names() + [DEFAULT_PROJECT_ID]
]
def set_createmeta(self, project, createmeta):
"""
This special method lets you seed the stub data with your own metadata.
# TODO validate createmeta
:param project:
:param createmeta:
:return:
"""
return self._set_data(project, "createmeta", createmeta)
def get_create_meta_for_project(self, project):
"""
Get the Jira "createmeta" for a project.
:param project: String name of a Jira project
:return: Object containing the "createmeta" of the project.
"""
self._throw_if_broken()
createmeta = self._get_data(project, "createmeta")
if createmeta:
return createmeta
# Fallback to stub data
return super().get_create_meta_for_project(project)
def create_issue(self, raw_form_data):
"""
Create a new Jira issue. Currently overwrites if the issue already exists.
:param raw_form_data: Object containing issue parameters
:return: Object containing the newly created ticket's "key" as a string.
"""
self._throw_if_broken()
project = raw_form_data.get("project", {}).get("id")
ticket_key = self._get_new_ticket_name(project)
self._set_data(project, ticket_key, {"fields": raw_form_data})
return {"key": ticket_key}
def get_issue(self, issue_key):
"""
Get a saved issue from Jira.
:param issue_key: string
:return: Object containing Jira Issue data
"""
project = issue_key.split("-")[0]
data = self._get_data(project, issue_key)
if not data:
return None
data.update(
{
"id": issue_key,
"key": issue_key,
}
)
return data
|
MockJira
|
python
|
networkx__networkx
|
networkx/generators/tests/test_lattice.py
|
{
"start": 5950,
"end": 7950
}
|
class ____:
"Tests for :func:`networkx.generators.lattice.triangular_lattice_graph`"
def test_lattice_points(self):
"""Tests that the graph is really a triangular lattice."""
for m, n in [(2, 3), (2, 2), (2, 1), (3, 3), (3, 2), (3, 4)]:
G = nx.triangular_lattice_graph(m, n)
N = (n + 1) // 2
assert len(G) == (m + 1) * (1 + N) - (n % 2) * ((m + 1) // 2)
for i, j in G.nodes():
nbrs = G[(i, j)]
if i < N:
assert (i + 1, j) in nbrs
if j < m:
assert (i, j + 1) in nbrs
if j < m and (i > 0 or j % 2) and (i < N or (j + 1) % 2):
assert (i + 1, j + 1) in nbrs or (i - 1, j + 1) in nbrs
def test_directed(self):
"""Tests for creating a directed triangular lattice."""
G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
H = nx.triangular_lattice_graph(3, 4, create_using=nx.DiGraph())
assert H.is_directed()
for u, v in H.edges():
assert v[1] >= u[1]
if v[1] == u[1]:
assert v[0] > u[0]
def test_multigraph(self):
"""Tests for creating a triangular lattice multigraph."""
G = nx.triangular_lattice_graph(3, 4, create_using=nx.Graph())
H = nx.triangular_lattice_graph(3, 4, create_using=nx.MultiGraph())
assert list(H.edges()) == list(G.edges())
def test_periodic(self):
G = nx.triangular_lattice_graph(4, 6, periodic=True)
assert len(G) == 12
assert G.size() == 36
# all degrees are 6
assert len([n for n, d in G.degree() if d != 6]) == 0
G = nx.triangular_lattice_graph(5, 7, periodic=True)
TLG = nx.triangular_lattice_graph
pytest.raises(nx.NetworkXError, TLG, 2, 4, periodic=True)
pytest.raises(nx.NetworkXError, TLG, 4, 4, periodic=True)
pytest.raises(nx.NetworkXError, TLG, 2, 6, periodic=True)
|
TestTriangularLatticeGraph
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/typeParams2.py
|
{
"start": 205,
"end": 295
}
|
class ____[T, S]: ...
# This should generate an error if <3.12
def func1[T, S](): ...
|
ClassA
|
python
|
scipy__scipy
|
scipy/optimize/_hessian_update_strategy.py
|
{
"start": 3815,
"end": 10735
}
|
class ____(HessianUpdateStrategy):
"""Hessian update strategy with full dimensional internal representation.
"""
_syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update
_syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update
# Symmetric matrix-vector product
_symv = get_blas_funcs('symv', dtype='d')
def __init__(self, init_scale='auto'):
self.init_scale = init_scale
# Until initialize is called we can't really use the class,
# so it makes sense to set everything to None.
self.first_iteration = None
self.approx_type = None
self.B = None
self.H = None
def initialize(self, n, approx_type):
"""Initialize internal matrix.
Allocate internal memory for storing and updating
the Hessian or its inverse.
Parameters
----------
n : int
Problem dimension.
approx_type : {'hess', 'inv_hess'}
Selects either the Hessian or the inverse Hessian.
When set to 'hess' the Hessian will be stored and updated.
When set to 'inv_hess' its inverse will be used instead.
"""
self.first_iteration = True
self.n = n
self.approx_type = approx_type
if approx_type not in ('hess', 'inv_hess'):
raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.")
# Create matrix
if self.approx_type == 'hess':
self.B = np.eye(n, dtype=float)
else:
self.H = np.eye(n, dtype=float)
def _auto_scale(self, delta_x, delta_grad):
# Heuristic to scale matrix at first iteration.
# Described in Nocedal and Wright "Numerical Optimization"
# p.143 formula (6.20).
s_norm2 = np.dot(delta_x, delta_x)
y_norm2 = np.dot(delta_grad, delta_grad)
ys = np.abs(np.dot(delta_grad, delta_x))
if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0:
return 1
if self.approx_type == 'hess':
return y_norm2 / ys
else:
return ys / y_norm2
def _update_implementation(self, delta_x, delta_grad):
raise NotImplementedError("The method ``_update_implementation``"
" is not implemented.")
def update(self, delta_x, delta_grad):
"""Update internal matrix.
Update Hessian matrix or its inverse (depending on how 'approx_type'
is defined) using information about the last evaluated points.
Parameters
----------
delta_x : ndarray
The difference between two points the gradient
function have been evaluated at: ``delta_x = x2 - x1``.
delta_grad : ndarray
The difference between the gradients:
``delta_grad = grad(x2) - grad(x1)``.
"""
if np.all(delta_x == 0.0):
return
if np.all(delta_grad == 0.0):
warn('delta_grad == 0.0. Check if the approximated '
'function is linear. If the function is linear '
'better results can be obtained by defining the '
'Hessian as zero instead of using quasi-Newton '
'approximations.',
UserWarning, stacklevel=2)
return
if self.first_iteration:
# Get user specific scale
if isinstance(self.init_scale, str) and self.init_scale == "auto":
scale = self._auto_scale(delta_x, delta_grad)
else:
scale = self.init_scale
# Check for complex: numpy will silently cast a complex array to
# a real one but not so for scalar as it raises a TypeError.
# Checking here brings a consistent behavior.
replace = False
if np.size(scale) == 1:
# to account for the legacy behavior having the exact same cast
scale = float(scale)
elif np.iscomplexobj(scale):
raise TypeError("init_scale contains complex elements, "
"must be real.")
else: # test explicitly for allowed shapes and values
replace = True
if self.approx_type == 'hess':
shape = np.shape(self.B)
dtype = self.B.dtype
else:
shape = np.shape(self.H)
dtype = self.H.dtype
# copy, will replace the original
scale = np.array(scale, dtype=dtype, copy=True)
# it has to match the shape of the matrix for the multiplication,
# no implicit broadcasting is allowed
if shape != (init_shape := np.shape(scale)):
raise ValueError("If init_scale is an array, it must have the "
f"dimensions of the hess/inv_hess: {shape}."
f" Got {init_shape}.")
if not issymmetric(scale):
raise ValueError("If init_scale is an array, it must be"
" symmetric (passing scipy.linalg.issymmetric)"
" to be an approximation of a hess/inv_hess.")
# Scale initial matrix with ``scale * np.eye(n)`` or replace
# This is not ideal, we could assign the scale directly in
# initialize, but we would need to
if self.approx_type == 'hess':
if replace:
self.B = scale
else:
self.B *= scale
else:
if replace:
self.H = scale
else:
self.H *= scale
self.first_iteration = False
self._update_implementation(delta_x, delta_grad)
def dot(self, p):
"""Compute the product of the internal matrix with the given vector.
Parameters
----------
p : array_like
1-D array representing a vector.
Returns
-------
Hp : array
1-D represents the result of multiplying the approximation matrix
by vector p.
"""
if self.approx_type == 'hess':
return self._symv(1, self.B, p)
else:
return self._symv(1, self.H, p)
def get_matrix(self):
"""Return the current internal matrix.
Returns
-------
M : ndarray, shape (n, n)
Dense matrix containing either the Hessian or its inverse
(depending on how `approx_type` was defined).
"""
if self.approx_type == 'hess':
M = np.copy(self.B)
else:
M = np.copy(self.H)
li = np.tril_indices_from(M, k=-1)
M[li] = M.T[li]
return M
|
FullHessianUpdateStrategy
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_23/tasks.py
|
{
"start": 84978,
"end": 85632
}
|
class ____(dict, NonStrictDataModel):
"""
Task section params
"""
_schema = {
"additionalProperties": True,
"description": "Task section params",
"type": "object",
}
def __init__(self, *args, **kwargs):
self.assert_isinstance(args, "section_params", dict, is_array=True)
kwargs.update(args)
self.assert_isinstance(
kwargs.values(), "params", (ParamsItem, dict), is_array=True
)
for k, v in kwargs.items():
if isinstance(v, dict):
kwargs[k] = ParamsItem(**v)
super(SectionParams, self).__init__(**kwargs)
|
SectionParams
|
python
|
apache__airflow
|
providers/microsoft/azure/tests/unit/microsoft/azure/sensors/test_wasb.py
|
{
"start": 3163,
"end": 7991
}
|
class ____:
def get_dag_run(self, dag_id: str = "test_dag_id", run_id: str = "test_dag_id") -> DagRun:
if hasattr(DagRun, "execution_date"): # for 2.x
dag_run = DagRun( # type: ignore[call-arg]
dag_id=dag_id,
run_type="manual",
execution_date=timezone.datetime(2022, 1, 1),
run_id=run_id,
)
else:
dag_run = DagRun(
dag_id=dag_id,
run_type="manual",
logical_date=timezone.datetime(2022, 1, 1),
run_id=run_id,
)
return dag_run
def get_task_instance(self, task: BaseOperator) -> TaskInstance:
if AIRFLOW_V_3_0_PLUS:
return TaskInstance(task, run_id=timezone.datetime(2022, 1, 1), dag_version_id=mock.MagicMock())
return TaskInstance(task, timezone.datetime(2022, 1, 1))
def get_conn(self) -> Connection:
return Connection(
conn_id="test_conn",
extra={},
)
def create_context(self, task, dag=None):
if dag is None:
dag = DAG(dag_id="dag", schedule=None)
tzinfo = pendulum.timezone("UTC")
logical_date = timezone.datetime(2022, 1, 1, 1, 0, 0, tzinfo=tzinfo)
if hasattr(DagRun, "execution_date"): # for 2.x
dag_run = DagRun(
dag_id=dag.dag_id,
execution_date=logical_date,
run_id=DagRun.generate_run_id(DagRunType.MANUAL, logical_date),
)
else:
dag_run = DagRun(
dag_id=dag.dag_id,
logical_date=logical_date,
run_id=DagRun.generate_run_id(
run_type=DagRunType.MANUAL, logical_date=logical_date, run_after=logical_date
),
)
if AIRFLOW_V_3_0_PLUS:
task_instance = TaskInstance(task=task, dag_version_id=mock.MagicMock())
else:
task_instance = TaskInstance(task=task)
task_instance.dag_run = dag_run
task_instance.xcom_push = mock.Mock()
date_key = "execution_date" if hasattr(DagRun, "execution_date") else "logical_date"
return {
"dag": dag,
"ts": logical_date.isoformat(),
"task": task,
"ti": task_instance,
"task_instance": task_instance,
"run_id": dag_run.run_id,
"dag_run": dag_run,
"data_interval_end": logical_date,
date_key: logical_date,
}
SENSOR = WasbBlobSensor(
task_id="wasb_blob_async_sensor",
container_name=TEST_DATA_STORAGE_CONTAINER_NAME,
blob_name=TEST_DATA_STORAGE_BLOB_NAME,
timeout=5,
deferrable=True,
)
@mock.patch("airflow.providers.microsoft.azure.sensors.wasb.WasbHook")
@mock.patch("airflow.providers.microsoft.azure.sensors.wasb.WasbBlobSensor.defer")
def test_wasb_blob_sensor_finish_before_deferred(self, mock_defer, mock_hook):
mock_hook.return_value.check_for_blob.return_value = True
self.SENSOR.execute(mock.MagicMock())
assert not mock_defer.called
@mock.patch("airflow.providers.microsoft.azure.sensors.wasb.WasbHook")
def test_wasb_blob_sensor_async(self, mock_hook):
"""Assert execute method defer for wasb blob sensor"""
mock_hook.return_value.check_for_blob.return_value = False
with pytest.raises(TaskDeferred) as exc:
self.SENSOR.execute(self.create_context(self.SENSOR))
assert isinstance(exc.value.trigger, WasbBlobSensorTrigger), "Trigger is not a WasbBlobSensorTrigger"
assert exc.value.timeout == datetime.timedelta(seconds=5)
@pytest.mark.parametrize(
"event",
[None, {"status": "success", "message": "Job completed"}],
)
def test_wasb_blob_sensor_execute_complete_success(self, event):
"""Assert execute_complete log success message when trigger fire with target status."""
if not event:
with pytest.raises(AirflowException) as exception_info:
self.SENSOR.execute_complete(context=None, event=None)
assert exception_info.value.args[0] == "Did not receive valid event from the triggerer"
else:
with mock.patch.object(self.SENSOR.log, "info") as mock_log_info:
self.SENSOR.execute_complete(context={}, event=event)
mock_log_info.assert_called_with(event["message"])
def test_wasb_blob_sensor_execute_complete_failure(self):
"""Assert execute_complete method raises an exception when the triggerer fires an error event."""
with pytest.raises(AirflowException):
self.SENSOR.execute_complete(context={}, event={"status": "error", "message": ""})
|
TestWasbBlobAsyncSensor
|
python
|
kamyu104__LeetCode-Solutions
|
Python/bold-words-in-string.py
|
{
"start": 154,
"end": 1272
}
|
class ____(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for i, word in enumerate(words):
functools.reduce(dict.__getitem__, word, trie).setdefault("_end")
lookup = [False] * len(S)
for i in xrange(len(S)):
curr = trie
k = -1
for j in xrange(i, len(S)):
if S[j] not in curr:
break
curr = curr[S[j]]
if "_end" in curr:
k = j
for j in xrange(i, k+1):
lookup[j] = True
result = []
for i in xrange(len(S)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(S[i])
if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)
# Time: O(n * d * l), l is the average length of words
# Space: O(n)
|
Solution
|
python
|
tensorflow__tensorflow
|
tensorflow/python/module/module_test.py
|
{
"start": 12704,
"end": 13042
}
|
class ____(module.Module):
def __init__(self, depth, trainable=True):
super().__init__(name="badger")
with self.name_scope:
self.child = None
if depth > 1:
self.child = RecursiveModule(depth - 1, trainable=trainable)
self.w = variables.Variable(1.0, trainable=trainable, name="mushroom")
|
RecursiveModule
|
python
|
walkccc__LeetCode
|
solutions/3040. Maximum Number of Operations With the Same Score II/3040.py
|
{
"start": 0,
"end": 915
}
|
class ____:
def maxOperations(self, nums: list[int]) -> int:
@functools.lru_cache(None)
def dp(i: int, j: int, score: int) -> int:
"""
Returns the maximum number of operations that can be performed for
nums[i..j], s.t. all operations have the same `score`.
"""
if i >= j:
return 0
deleteFirstTwo = (1 + dp(i + 2, j, score)
if nums[i] + nums[i + 1] == score else 0)
deleteLastTwo = (1 + dp(i, j - 2, score)
if nums[j] + nums[j - 1] == score else 0)
deleteFirstAndLast = (1 + dp(i + 1, j - 1, score)
if nums[i] + nums[j] == score else 0)
return max(deleteFirstTwo, deleteLastTwo, deleteFirstAndLast)
n = len(nums)
return max(dp(0, n - 1, nums[0] + nums[1]),
dp(0, n - 1, nums[-1] + nums[-2]),
dp(0, n - 1, nums[0] + nums[-1]))
|
Solution
|
python
|
apache__airflow
|
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py
|
{
"start": 23860,
"end": 24522
}
|
class ____:
@pytest.fixture(autouse=True)
def setup(self) -> None:
clear_db_assets()
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
def teardown_method(self) -> None:
clear_db_assets()
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
@provide_session
def create_asset_aliases(self, num: int = 2, *, session):
_create_asset_aliases(num=num, session=session)
@provide_session
def create_provided_asset_alias(self, asset_alias: AssetAliasModel, session):
_create_provided_asset_alias(session=session, asset_alias=asset_alias)
|
TestAssetAliases
|
python
|
kamyu104__LeetCode-Solutions
|
Python/graph-valid-tree.py
|
{
"start": 947,
"end": 1848
}
|
class ____(object):
# @param {integer} n
# @param {integer[][]} edges
# @return {boolean}
def validTree(self, n, edges):
# A structure to track each node's [visited_from, neighbors]
visited_from = [-1] * n
neighbors = collections.defaultdict(list)
for u, v in edges:
neighbors[u].append(v)
neighbors[v].append(u)
# BFS to check whether the graph is valid tree.
q = collections.deque([0])
visited = set([0])
while q:
i = q.popleft()
for node in neighbors[i]:
if node != visited_from[i]:
if node in visited:
return False
else:
visited.add(node)
visited_from[node] = i
q.append(node)
return len(visited) == n
|
Solution2
|
python
|
dagster-io__dagster
|
scripts/gen_airbyte_classes.py
|
{
"start": 3928,
"end": 4435
}
|
class ____(SchemaType):
def __init__(self, inner: SchemaType):
self.inner = inner
def __str__(self):
return f"List[{self.inner}]"
def annotation(
self, scope: Optional[str] = None, quote: bool = False, hide_default: bool = False
):
return f"List[{self.inner.annotation(scope, quote, hide_default)}]"
def get_check(self, name: str, scope: Optional[str] = None):
return f"check.list_param({name}, '{name}', {self.inner.annotation(scope)})"
|
ListType
|
python
|
doocs__leetcode
|
lcof/面试题55 - II. 平衡二叉树/Solution.py
|
{
"start": 164,
"end": 502
}
|
class ____:
def isBalanced(self, root: TreeNode) -> bool:
def dfs(root):
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
if l == -1 or r == -1 or abs(l - r) > 1:
return -1
return 1 + max(l, r)
return dfs(root) != -1
|
Solution
|
python
|
getsentry__sentry
|
src/sentry/monitors/serializers.py
|
{
"start": 5295,
"end": 5660
}
|
class ____(MonitorSerializerResponseOptional):
id: str
name: str
slug: str
status: str
isMuted: bool
isUpserting: bool
config: MonitorConfigSerializerResponse
dateCreated: datetime
project: ProjectSerializerResponse
environments: MonitorEnvironmentSerializerResponse
owner: ActorSerializerResponse
|
MonitorSerializerResponse
|
python
|
getsentry__sentry
|
src/sentry/analytics/events/comment_webhooks.py
|
{
"start": 365,
"end": 458
}
|
class ____(CommentEvent):
pass
@analytics.eventclass("comment.deleted")
|
CommentUpdatedEvent
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_errorbars02.py
|
{
"start": 315,
"end": 1798
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_errorbars02.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with error bars."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
chart.axis_ids = [63385984, 63387904]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"y_error_bars": {
"type": "fixed",
"value": 2,
"end_style": 0,
"direction": "minus",
},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
"y_error_bars": {"type": "percentage", "value": 5, "direction": "plus"},
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/types.py
|
{
"start": 1018,
"end": 1822
}
|
class ____:
@classmethod
def enums(cls):
attrs = []
for attr in cls.__dict__.values():
if isinstance(attr, EnumMeta):
attrs.append(attr)
return attrs
@classmethod
def contains(cls, value) -> bool:
for enum in cls.enums():
with suppress(ValueError):
if enum(value):
return True
return False
@classmethod
def split(cls, value: str) -> tuple[str, str]:
if cls.contains(value):
parts = value.split(":", 1)
return (parts[0], parts[1])
raise ValueError("Invalid tag value", value)
agent_strategy = AgentStrategyTags
server_strategy = ServerStrategyTags
source = SourceTags
subcommand = SubcommandTags
|
CliEventTags
|
python
|
huggingface__transformers
|
src/transformers/models/flaubert/modeling_flaubert.py
|
{
"start": 18543,
"end": 24476
}
|
class ____(nn.Module):
r"""
A SQuAD head inspired by XLNet.
Args:
config ([`FlaubertConfig`]):
The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
to use.
"""
def __init__(self, config: FlaubertConfig):
super().__init__()
self.start_n_top = config.start_n_top
self.end_n_top = config.end_n_top
self.start_logits = FlaubertPoolerStartLogits(config)
self.end_logits = FlaubertPoolerEndLogits(config)
self.answer_class = FlaubertPoolerAnswerClass(config)
@auto_docstring
def forward(
self,
hidden_states: torch.FloatTensor,
start_positions: Optional[torch.LongTensor] = None,
end_positions: Optional[torch.LongTensor] = None,
cls_index: Optional[torch.LongTensor] = None,
is_impossible: Optional[torch.LongTensor] = None,
p_mask: Optional[torch.FloatTensor] = None,
return_dict: bool = False,
) -> Union[FlaubertSquadHeadOutput, tuple[torch.FloatTensor]]:
r"""
hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
Final hidden states of the model on the sequence tokens.
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Positions of the first token for the labeled span.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Positions of the last token for the labeled span.
cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Whether the question has a possible answer in the paragraph or not.
p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
should be masked.
"""
start_logits = self.start_logits(hidden_states, p_mask=p_mask)
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, let's remove the dimension added by batch splitting
for x in (start_positions, end_positions, cls_index, is_impossible):
if x is not None and x.dim() > 1:
x.squeeze_(-1)
# during training, compute the end logits based on the ground truth of the start position
end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
loss_fct = CrossEntropyLoss()
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if cls_index is not None and is_impossible is not None:
# Predict answerability from the representation of CLS and START
cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
loss_fct_cls = nn.BCEWithLogitsLoss()
cls_loss = loss_fct_cls(cls_logits, is_impossible)
# note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
total_loss += cls_loss * 0.5
return FlaubertSquadHeadOutput(loss=total_loss) if return_dict else (total_loss,)
else:
# during inference, compute the end logits based on beam search
bsz, slen, hsz = hidden_states.size()
start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
start_top_log_probs, start_top_index = torch.topk(
start_log_probs, self.start_n_top, dim=-1
) # shape (bsz, start_n_top)
start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
start_states
) # shape (bsz, slen, start_n_top, hsz)
p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
end_top_log_probs, end_top_index = torch.topk(
end_log_probs, self.end_n_top, dim=1
) # shape (bsz, end_n_top, start_n_top)
end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
start_states = torch.einsum("blh,bl->bh", hidden_states, start_log_probs)
cls_logits = self.answer_class(hidden_states, start_states=start_states, cls_index=cls_index)
if not return_dict:
return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
else:
return FlaubertSquadHeadOutput(
start_top_log_probs=start_top_log_probs,
start_top_index=start_top_index,
end_top_log_probs=end_top_log_probs,
end_top_index=end_top_index,
cls_logits=cls_logits,
)
# Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->Flaubert
|
FlaubertSQuADHead
|
python
|
huggingface__transformers
|
src/transformers/models/dinov2/modeling_dinov2.py
|
{
"start": 11352,
"end": 12399
}
|
class ____(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
return hidden_state * self.lambda1
# Copied from transformers.models.beit.modeling_beit.drop_path
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
"""
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
"""
if drop_prob == 0.0 or not training:
return input
keep_prob = 1 - drop_prob
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
random_tensor.floor_() # binarize
output = input.div(keep_prob) * random_tensor
return output
# Copied from transformers.models.beit.modeling_beit.BeitDropPath
|
Dinov2LayerScale
|
python
|
Textualize__textual
|
tests/snapshot_tests/snapshot_apps/keyline.py
|
{
"start": 168,
"end": 980
}
|
class ____(App):
CSS = """
Vertical {
keyline: thin red;
}
Horizontal {
keyline: heavy green;
}
Grid {
keyline: double magenta;
}
Box {
width: 1fr;
height: 1fr;
}
Horizontal > Box, Vertical > Box {
margin: 1;
}
Grid {
grid-size: 2;
grid-gutter: 1;
}
"""
def compose(self) -> ComposeResult:
with Vertical():
yield Box("1")
yield Box("2")
yield Box("3")
with Horizontal():
yield Box("4")
yield Box("5")
yield Box("6")
with Grid():
yield Box("7")
yield Box("8")
yield Box("9")
if __name__ == "__main__":
app = KeylineApp()
app.run()
|
KeylineApp
|
python
|
numpy__numpy
|
benchmarks/benchmarks/bench_io.py
|
{
"start": 123,
"end": 996
}
|
class ____(Benchmark):
params = ["int8", "int16", "float32", "float64",
"complex64", "complex128"]
param_names = ['type']
def setup(self, typename):
dtype = np.dtype(typename)
self.d = np.arange((50 * 500), dtype=dtype).reshape((500, 50))
self.e = np.arange((50 * 500), dtype=dtype).reshape((50, 500))
self.e_d = self.e.reshape(self.d.shape)
self.dflat = np.arange((50 * 500), dtype=dtype)
def time_memcpy(self, typename):
self.d[...] = self.e_d
def time_memcpy_large_out_of_place(self, typename):
l = np.ones(1024**2, dtype=np.dtype(typename))
l.copy()
def time_cont_assign(self, typename):
self.d[...] = 1
def time_strided_copy(self, typename):
self.d[...] = self.e.T
def time_strided_assign(self, typename):
self.dflat[::2] = 2
|
Copy
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py
|
{
"start": 1452,
"end": 1580
}
|
class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
@attr.s(auto_attribs=False) # auto_attribs = False
|
C
|
python
|
python-pillow__Pillow
|
src/PIL/_util.py
|
{
"start": 282,
"end": 684
}
|
class ____:
def __init__(self, ex: BaseException):
self.ex = ex
def __getattr__(self, elt: str) -> NoReturn:
raise self.ex
@staticmethod
def new(ex: BaseException) -> Any:
"""
Creates an object that raises the wrapped exception ``ex`` when used,
and casts it to :py:obj:`~typing.Any` type.
"""
return DeferredError(ex)
|
DeferredError
|
python
|
huggingface__transformers
|
src/transformers/generation/continuous_batching/cache_manager.py
|
{
"start": 9954,
"end": 11812
}
|
class ____(ABC):
"""Abstract base class for cache managers. Cache managers keep track of per-request cache allocations, determine
when a new physical block needs to be allocated and compute physical indices for reading or writing to the cache."""
_index: int
block_table: dict[str, list[int]] # request_id -> list of block_ids allocated to the request
@abstractmethod
def allocate_blocks(self, n_blocks: int, request_id: str, block_manager: BlockManager) -> int | None:
"""Allocates (n_blocks) for a given (request_id) using the (block_manager). Returns the num of blocks allocated
if successful and None otherwise."""
def free_blocks(self, request_id: str, block_manager: BlockManager) -> None:
"""Frees all blocks associated with a (request_id) using the (block_manager)."""
if request_id in self.block_table:
blocks_to_free = self.block_table.pop(request_id)
block_manager.free_blocks(blocks_to_free)
else:
logger.warning(
f"CacheAllocator {self._index} attempted to free blocks for non-existent request_id: {request_id}"
)
@abstractmethod
def get_read_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
"""Returns the physical indices of where to read request_id's cache in the cache tensor."""
@abstractmethod
def get_write_indices(self, request_id: str, past_length: int, query_length: int) -> list[int]:
"""Returns the physical indices of where to write request_id's cache in the cache tensor."""
@abstractmethod
def get_seqlens_k(self, request_id: str, past_length: int, query_length: int) -> tuple[str, int]:
"""Returns the attention type of the cache allocator and the key sequence length for the given request_id."""
|
CacheAllocator
|
python
|
sympy__sympy
|
sympy/polys/polyoptions.py
|
{
"start": 7123,
"end": 7889
}
|
class ____(Option, metaclass=OptionType):
"""``gens`` option to polynomial manipulation functions. """
option = 'gens'
requires: list[str] = []
excludes: list[str] = []
@classmethod
def default(cls):
return ()
@classmethod
def preprocess(cls, gens):
if isinstance(gens, Basic):
gens = (gens,)
elif len(gens) == 1 and is_sequence(gens[0]):
gens = gens[0]
if gens == (None,):
gens = ()
elif has_dups(gens):
raise GeneratorsError("duplicated generators: %s" % str(gens))
elif any(gen.is_commutative is False for gen in gens):
raise GeneratorsError("non-commutative generators: %s" % str(gens))
return tuple(gens)
|
Gens
|
python
|
ray-project__ray
|
rllib/env/wrappers/unity3d_env.py
|
{
"start": 453,
"end": 12475
}
|
class ____(MultiAgentEnv):
# Default base port when connecting directly to the Editor
_BASE_PORT_EDITOR = 5004
# Default base port when connecting to a compiled environment
_BASE_PORT_ENVIRONMENT = 5005
# The worker_id for each environment instance
_WORKER_ID = 0
def __init__(
self,
file_name: str = None,
port: Optional[int] = None,
seed: int = 0,
no_graphics: bool = False,
timeout_wait: int = 300,
episode_horizon: int = 1000,
):
super().__init__()
if file_name is None:
print(
"No game binary provided, will use a running Unity editor "
"instead.\nMake sure you are pressing the Play (|>) button in "
"your editor to start."
)
import mlagents_envs
from mlagents_envs.environment import UnityEnvironment
# Try connecting to the Unity3D game instance. If a port is blocked
port_ = None
while True:
# Sleep for random time to allow for concurrent startup of many
# environments (num_env_runners >> 1). Otherwise, would lead to port
# conflicts sometimes.
if port_ is not None:
time.sleep(random.randint(1, 10))
port_ = port or (
self._BASE_PORT_ENVIRONMENT if file_name else self._BASE_PORT_EDITOR
)
# cache the worker_id and
# increase it for the next environment
worker_id_ = Unity3DEnv._WORKER_ID if file_name else 0
Unity3DEnv._WORKER_ID += 1
try:
self.unity_env = UnityEnvironment(
file_name=file_name,
worker_id=worker_id_,
base_port=port_,
seed=seed,
no_graphics=no_graphics,
timeout_wait=timeout_wait,
)
print("Created UnityEnvironment for port {}".format(port_ + worker_id_))
except mlagents_envs.exception.UnityWorkerInUseException:
pass
else:
break
# ML-Agents API version.
self.api_version = self.unity_env.API_VERSION.split(".")
self.api_version = [int(s) for s in self.api_version]
# Reset entire env every this number of step calls.
self.episode_horizon = episode_horizon
# Keep track of how many times we have called `step` so far.
self.episode_timesteps = 0
def step(
self, action_dict: MultiAgentDict
) -> Tuple[
MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict, MultiAgentDict
]:
from mlagents_envs.base_env import ActionTuple
# Set only the required actions (from the DecisionSteps) in Unity3D.
all_agents = []
for behavior_name in self.unity_env.behavior_specs:
# New ML-Agents API: Set all agents actions at the same time
# via an ActionTuple. Since API v1.4.0.
if self.api_version[0] > 1 or (
self.api_version[0] == 1 and self.api_version[1] >= 4
):
actions = []
for agent_id in self.unity_env.get_steps(behavior_name)[0].agent_id:
key = behavior_name + "_{}".format(agent_id)
all_agents.append(key)
actions.append(action_dict[key])
if actions:
if actions[0].dtype == np.float32:
action_tuple = ActionTuple(continuous=np.array(actions))
else:
action_tuple = ActionTuple(discrete=np.array(actions))
self.unity_env.set_actions(behavior_name, action_tuple)
# Old behavior: Do not use an ActionTuple and set each agent's
# action individually.
else:
for agent_id in self.unity_env.get_steps(behavior_name)[
0
].agent_id_to_index.keys():
key = behavior_name + "_{}".format(agent_id)
all_agents.append(key)
self.unity_env.set_action_for_agent(
behavior_name, agent_id, action_dict[key]
)
# Do the step.
self.unity_env.step()
obs, rewards, terminateds, truncateds, infos = self._get_step_results()
# Global horizon reached? -> Return __all__ truncated=True, so user
# can reset. Set all agents' individual `truncated` to True as well.
self.episode_timesteps += 1
if self.episode_timesteps > self.episode_horizon:
return (
obs,
rewards,
terminateds,
dict({"__all__": True}, **{agent_id: True for agent_id in all_agents}),
infos,
)
return obs, rewards, terminateds, truncateds, infos
def reset(
self, *, seed=None, options=None
) -> Tuple[MultiAgentDict, MultiAgentDict]:
"""Resets the entire Unity3D scene (a single multi-agent episode)."""
self.episode_timesteps = 0
self.unity_env.reset()
obs, _, _, _, infos = self._get_step_results()
return obs, infos
def _get_step_results(self):
obs = {}
rewards = {}
infos = {}
for behavior_name in self.unity_env.behavior_specs:
decision_steps, terminal_steps = self.unity_env.get_steps(behavior_name)
# Important: Only update those sub-envs that are currently
# available within _env_state.
# Loop through all envs ("agents") and fill in, whatever
# information we have.
for agent_id, idx in decision_steps.agent_id_to_index.items():
key = behavior_name + "_{}".format(agent_id)
os = tuple(o[idx] for o in decision_steps.obs)
os = os[0] if len(os) == 1 else os
obs[key] = os
rewards[key] = (
decision_steps.reward[idx] + decision_steps.group_reward[idx]
)
for agent_id, idx in terminal_steps.agent_id_to_index.items():
key = behavior_name + "_{}".format(agent_id)
# Only overwrite rewards (last reward in episode), b/c obs
# here is the last obs (which doesn't matter anyways).
# Unless key does not exist in obs.
if key not in obs:
os = tuple(o[idx] for o in terminal_steps.obs)
obs[key] = os = os[0] if len(os) == 1 else os
rewards[key] = (
terminal_steps.reward[idx] + terminal_steps.group_reward[idx]
)
# Only use dones if all agents are done, then we should do a reset.
return obs, rewards, {"__all__": False}, {"__all__": False}, infos
@staticmethod
def get_policy_configs_for_game(
game_name: str,
) -> Tuple[dict, Callable[[AgentID], PolicyID]]:
# The RLlib server must know about the Spaces that the Client will be
# using inside Unity3D, up-front.
obs_spaces = {
# 3DBall.
"3DBall": Box(float("-inf"), float("inf"), (8,)),
# 3DBallHard.
"3DBallHard": Box(float("-inf"), float("inf"), (45,)),
# GridFoodCollector
"GridFoodCollector": Box(float("-inf"), float("inf"), (40, 40, 6)),
# Pyramids.
"Pyramids": TupleSpace(
[
Box(float("-inf"), float("inf"), (56,)),
Box(float("-inf"), float("inf"), (56,)),
Box(float("-inf"), float("inf"), (56,)),
Box(float("-inf"), float("inf"), (4,)),
]
),
# SoccerTwos.
"SoccerPlayer": TupleSpace(
[
Box(-1.0, 1.0, (264,)),
Box(-1.0, 1.0, (72,)),
]
),
# SoccerStrikersVsGoalie.
"Goalie": Box(float("-inf"), float("inf"), (738,)),
"Striker": TupleSpace(
[
Box(float("-inf"), float("inf"), (231,)),
Box(float("-inf"), float("inf"), (63,)),
]
),
# Sorter.
"Sorter": TupleSpace(
[
Box(
float("-inf"),
float("inf"),
(
20,
23,
),
),
Box(float("-inf"), float("inf"), (10,)),
Box(float("-inf"), float("inf"), (8,)),
]
),
# Tennis.
"Tennis": Box(float("-inf"), float("inf"), (27,)),
# VisualHallway.
"VisualHallway": Box(float("-inf"), float("inf"), (84, 84, 3)),
# Walker.
"Walker": Box(float("-inf"), float("inf"), (212,)),
# FoodCollector.
"FoodCollector": TupleSpace(
[
Box(float("-inf"), float("inf"), (49,)),
Box(float("-inf"), float("inf"), (4,)),
]
),
}
action_spaces = {
# 3DBall.
"3DBall": Box(-1.0, 1.0, (2,), dtype=np.float32),
# 3DBallHard.
"3DBallHard": Box(-1.0, 1.0, (2,), dtype=np.float32),
# GridFoodCollector.
"GridFoodCollector": MultiDiscrete([3, 3, 3, 2]),
# Pyramids.
"Pyramids": MultiDiscrete([5]),
# SoccerStrikersVsGoalie.
"Goalie": MultiDiscrete([3, 3, 3]),
"Striker": MultiDiscrete([3, 3, 3]),
# SoccerTwos.
"SoccerPlayer": MultiDiscrete([3, 3, 3]),
# Sorter.
"Sorter": MultiDiscrete([3, 3, 3]),
# Tennis.
"Tennis": Box(-1.0, 1.0, (3,)),
# VisualHallway.
"VisualHallway": MultiDiscrete([5]),
# Walker.
"Walker": Box(-1.0, 1.0, (39,)),
# FoodCollector.
"FoodCollector": MultiDiscrete([3, 3, 3, 2]),
}
# Policies (Unity: "behaviors") and agent-to-policy mapping fns.
if game_name == "SoccerStrikersVsGoalie":
policies = {
"Goalie": PolicySpec(
observation_space=obs_spaces["Goalie"],
action_space=action_spaces["Goalie"],
),
"Striker": PolicySpec(
observation_space=obs_spaces["Striker"],
action_space=action_spaces["Striker"],
),
}
def policy_mapping_fn(agent_id, episode, worker, **kwargs):
return "Striker" if "Striker" in agent_id else "Goalie"
elif game_name == "SoccerTwos":
policies = {
"PurplePlayer": PolicySpec(
observation_space=obs_spaces["SoccerPlayer"],
action_space=action_spaces["SoccerPlayer"],
),
"BluePlayer": PolicySpec(
observation_space=obs_spaces["SoccerPlayer"],
action_space=action_spaces["SoccerPlayer"],
),
}
def policy_mapping_fn(agent_id, episode, worker, **kwargs):
return "BluePlayer" if "1_" in agent_id else "PurplePlayer"
else:
policies = {
game_name: PolicySpec(
observation_space=obs_spaces[game_name],
action_space=action_spaces[game_name],
),
}
def policy_mapping_fn(agent_id, episode, worker, **kwargs):
return game_name
return policies, policy_mapping_fn
|
Unity3DEnv
|
python
|
huggingface__transformers
|
src/transformers/models/mamba/modeling_mamba.py
|
{
"start": 33281,
"end": 40027
}
|
class ____(MambaPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "backbone.embeddings.weight"}
def __init__(self, config):
super().__init__(config)
self.backbone = MambaModel(config)
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.backbone.get_input_embeddings()
def set_input_embeddings(self, new_embeddings):
return self.backbone.set_input_embeddings(new_embeddings)
def _update_model_kwargs_for_generation(
self, outputs: ModelOutput, model_kwargs: dict[str, Any], num_new_tokens: int = 1, **kwargs
) -> dict[str, Any]:
model_kwargs["cache_params"] = outputs.get("cache_params", None)
if (
model_kwargs.get("use_cache", True)
and "cache_position" in model_kwargs
and model_kwargs["cache_position"] is not None
):
model_kwargs["cache_position"] = model_kwargs["cache_position"][-1:] + num_new_tokens
if "attention_mask" in model_kwargs:
attention_mask = model_kwargs["attention_mask"]
model_kwargs["attention_mask"] = torch.cat(
[attention_mask, attention_mask.new_ones((attention_mask.shape[0], 1))], dim=-1
)
return model_kwargs
def prepare_inputs_for_generation(
self,
input_ids,
inputs_embeds=None,
use_cache=None,
cache_params: Optional[MambaCache] = None,
cache_position: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
**kwargs,
):
# Overwritten -- uses `cache_params` as opposed to `past_key_values`
model_inputs = {"input_ids": input_ids.contiguous()}
if use_cache and cache_params is None:
# we initialize the `cache_position` to full size of `conv_states` at prefill stage
# considering padding will be applied when input length is shorter, and truncation
# will be applied when it is longer, so it will be equivalent to always have it match
# the length of `cache_params.conv_states`, which is `config.conv_kernel`
cache_position = torch.arange(0, self.backbone.config.conv_kernel, device=input_ids.device)
if inputs_embeds is not None:
model_inputs = {"inputs_embeds": inputs_embeds}
max_batch_size = inputs_embeds.size(0)
else:
max_batch_size = input_ids.size(0)
cache_params = MambaCache(self.backbone.config, max_batch_size, device=self.device, dtype=self.dtype)
if use_cache and cache_position[0] > 0:
model_inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1).contiguous()
attention_mask = None
if not use_cache and inputs_embeds is not None:
model_inputs = {"inputs_embeds": inputs_embeds}
model_inputs.update(
{
"cache_params": cache_params,
"use_cache": use_cache,
"cache_position": cache_position,
"attention_mask": attention_mask,
}
)
# Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
for key, value in kwargs.items():
if key not in model_inputs:
model_inputs[key] = value
return model_inputs
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.LongTensor] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
cache_params: Optional[MambaCache] = None,
labels: Optional[torch.LongTensor] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.Tensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs, # for now we need this for generation
) -> Union[tuple, MambaCausalLMOutput]:
r"""
cache_params (`MambaCache`, *optional*):
If passed along, the model uses the previous state in all the blocks (which will give the output for the
`input_ids` provided as if the model add `state_input_ids + input_ids` as context).
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
use_cache (`bool`, *optional*):
If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
mamba_outputs = self.backbone(
input_ids,
cache_params=cache_params,
inputs_embeds=inputs_embeds,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
use_cache=use_cache,
cache_position=cache_position,
attention_mask=attention_mask,
)
hidden_states = mamba_outputs[0]
# Only compute necessary logits
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :].to(self.lm_head.weight.dtype)).float()
loss = None
if labels is not None:
# move labels to correct device
labels = labels.to(logits.device)
# Shift so that tokens < n predict n
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
# Flatten the tokens
loss_fct = CrossEntropyLoss()
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
if not return_dict:
output = (logits,) + mamba_outputs[1:]
return ((loss,) + output) if loss is not None else output
return MambaCausalLMOutput(
loss=loss,
logits=logits,
cache_params=mamba_outputs.cache_params,
hidden_states=mamba_outputs.hidden_states,
)
__all__ = ["MambaForCausalLM", "MambaModel", "MambaPreTrainedModel", "MambaCache"]
|
MambaForCausalLM
|
python
|
doocs__leetcode
|
solution/3100-3199/3142.Check if Grid Satisfies Conditions/Solution.py
|
{
"start": 0,
"end": 394
}
|
class ____:
def satisfiesConditions(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
for i, row in enumerate(grid):
for j, x in enumerate(row):
if i + 1 < m and x != grid[i + 1][j]:
return False
if j + 1 < n and x == grid[i][j + 1]:
return False
return True
|
Solution
|
python
|
google__jax
|
tests/distributed_test.py
|
{
"start": 913,
"end": 2381
}
|
class ____(jtu.JaxTestCase):
# TODO(phawkins): Enable after https://github.com/jax-ml/jax/issues/11222
# is fixed.
@unittest.SkipTest
def testInitializeAndShutdown(self):
if not jtu.test_device_matches(["gpu"]):
self.skipTest("Test only works with GPUs.")
# Tests the public APIs. Since they use global state, we cannot use
# concurrency to simulate multiple tasks.
port = portpicker.pick_unused_port()
jax.distributed.initialize(
coordinator_address=f"localhost:{port}",
num_processes=1,
process_id=0,
cluster_detection_method="deactivate",
)
jax.distributed.shutdown()
@parameterized.parameters([1, 2, 4])
def testConcurrentInitializeAndShutdown(self, n):
if not jtu.test_device_matches(["gpu"]):
self.skipTest("Test only works with GPUs.")
port = portpicker.pick_unused_port()
def task(i):
# We can't call the public APIs directly because they use global state.
state = distributed.State()
state.initialize(
coordinator_address=f"localhost:{port}",
num_processes=n,
process_id=i,
cluster_detection_method="deactivate",
)
state.shutdown()
threads = [threading.Thread(target=task, args=(i,)) for i in range(n)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
|
DistributedTest
|
python
|
tensorflow__tensorflow
|
tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_ops_test.py
|
{
"start": 3834,
"end": 56510
}
|
class ____(test.TestCase, parameterized.TestCase):
@classmethod
def setUpClass(cls): # pylint: disable=g-missing-super-call
cls._gpu_available = test_util.is_gpu_available()
# TODO(ebrevdo): This will work once we find a way to get rendezvous
# working for CSRSparseMatrix and can remove the HostMemory
# annotations for the other ops.
@test_util.run_in_graph_and_eager_modes
def DISABLEDtestFromProto(self):
if not self._gpu_available:
return
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.asarray([1.0, 5.0], dtype=np.float32)
a_dense_shape = np.asarray([5, 6], dtype=np.int64)
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
a_col_inds = a_csr_mat.indices
a_row_ptrs = a_csr_mat.indptr
# Format of SparseMatrix:
# type_name == "tensorflow::CSRSparseMatrix"
# metadata == b (validated)
# tensors == [dense_shape, row_ptrs, col_indices, values]
dense_shape_proto = tensor_util.make_tensor_proto(a_dense_shape)
row_ptrs_proto = tensor_util.make_tensor_proto(a_row_ptrs)
col_inds_proto = tensor_util.make_tensor_proto(a_col_inds)
values_proto = tensor_util.make_tensor_proto(a_values)
variant_tensor_data = tensor_pb2.VariantTensorDataProto(
type_name="tensorflow::CSRSparseMatrix",
metadata=np.asarray(True).tobytes(),
tensors=[
dense_shape_proto, row_ptrs_proto, col_inds_proto, values_proto
])
tensor_proto = tensor_pb2.TensorProto(
dtype=dtypes.variant.as_datatype_enum,
tensor_shape=tensor_shape.TensorShape([]).as_proto())
tensor_proto.variant_val.extend([variant_tensor_data])
a_sm = constant_op.constant(tensor_proto)
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, type=dtypes.float32)
self.evaluate(a_rt)
@test_util.run_in_graph_and_eager_modes
def testSparseTensorConversion(self):
a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])
a_values = [1.0, 5.0, -1.0, -2.0]
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
# Convert 2D SparseTensor to CSR Matrix
a_st = sparse_tensor.SparseTensor(a_indices, a_values, a_dense_shape)
a_st = math_ops.cast(a_st, dtypes.float32)
a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
a_st.indices, a_st.values, a_st.dense_shape)
# Get row indices and columns for batch 0.
a_sm_row_ptrs, a_sm_col_inds, a_sm_values = (
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, 0, type=a_st.dtype))
a_sm_row_ptrs_values, a_sm_col_inds_values, a_sm_values_values = (
self.evaluate((a_sm_row_ptrs, a_sm_col_inds, a_sm_values)))
self.assertAllEqual(a_csr_mat.indices, a_sm_col_inds_values)
self.assertAllEqual(a_csr_mat.indptr, a_sm_row_ptrs_values)
self.assertAllClose(a_values, a_sm_values_values)
# Convert CSR Matrix to 2D SparseTensor
a_st_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
a_sm, type=a_st.dtype)
a_st_rt_value = self.evaluate(a_st_rt)
self.assertAllEqual(a_indices, a_st_rt_value.indices)
self.assertAllClose(a_values, a_st_rt_value.values)
self.assertAllEqual(a_dense_shape, a_st_rt_value.dense_shape)
def testSparseTensorConversionInvalidInputShapes(self):
values = constant_op.constant(0.554979503, shape=[5], dtype=dtypes.float32)
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), "must be rank 1"
):
indices = constant_op.constant(0, shape=[5, 2], dtype=dtypes.int64)
dense_shape = constant_op.constant(53, shape=[], dtype=dtypes.int64)
csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
indices=indices, values=values, dense_shape=dense_shape
)
self.evaluate(csr)
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError), "must be rank 2"
):
indices = constant_op.constant(0, shape=[5], dtype=dtypes.int64)
dense_shape = constant_op.constant(53, shape=[1], dtype=dtypes.int64)
csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
indices=indices, values=values, dense_shape=dense_shape
)
self.evaluate(csr)
int32max = 2**31 - 1
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
"batch_size must be < Int32Max",
):
indices = constant_op.constant(0, shape=[5, 3], dtype=dtypes.int64)
dense_shape = constant_op.constant(
[int32max, 1, 1], shape=[3], dtype=dtypes.int64
)
csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
indices=indices, values=values, dense_shape=dense_shape
)
self.evaluate(csr)
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
"csr row index size.*must be <= Int32Max",
):
indices = constant_op.constant(0, shape=[5, 3], dtype=dtypes.int64)
dense_shape = constant_op.constant(
[(int32max // 2), 10, 1], shape=[3], dtype=dtypes.int64
)
csr = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
indices=indices, values=values, dense_shape=dense_shape
)
self.evaluate(csr)
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
"Index rank .* and shape rank .* do not match",
):
self.evaluate(
sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
indices=[[0, 0, 0], [0, 0, 1]],
values=[10.0, 20.0],
dense_shape=[33, 73],
)
)
# TODO(b/139491352): Add handle_data propagation to array_ops.identity.
@test_util.run_deprecated_v1
def testCSRSparseMatrixResourceVariable(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
a_sm = dense_to_csr_sparse_matrix(a_mats)
with ops.device("/gpu:0"):
v = variable_scope.get_variable("sm", initializer=a_sm, use_resource=True)
v_id = array_ops.identity(v)
self.assertEqual(
sparse_csr_matrix_ops.dense_shape_and_type(v_id).shape, a_mats.shape)
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
v, type=dtypes.float32)
v_reassign = state_ops.assign(v, v_id).op
with self.assertRaisesOpError("uninitialized"):
self.evaluate(a_rt)
self.evaluate(v.initializer)
a_rt_value = self.evaluate(a_rt)
self.assertAllClose(a_mats, a_rt_value)
self.evaluate(v_reassign)
a_rt_reassigned_value = self.evaluate(a_rt)
self.assertAllClose(a_mats, a_rt_reassigned_value)
@test_util.run_in_graph_and_eager_modes
def testBatchSparseTensorConversion(self):
a_indices = np.array([[0, 0, 0], [0, 2, 3], [2, 0, 1]])
a_values = [1.0, 5.0, 6.0]
a_dense_shape = [3, 5, 6]
a_sparse_mats = [
sparse.coo_matrix(([1.0, 5.0], ([0, 2], [0, 3])),
shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([6.0], ([0], [1])), shape=a_dense_shape[1:])
]
a_csr_mats = [m.tocsr() for m in a_sparse_mats]
# Convert 3D SparseTensor to CSR Matrix
a_st = sparse_tensor.SparseTensor(a_indices, a_values, a_dense_shape)
a_st = math_ops.cast(a_st, dtypes.float32)
a_sm = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
a_st.indices, a_st.values, a_st.dense_shape)
# Get row indices and columns for batches.
a_sm_components = [
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, i, type=a_st.dtype) for i in range(3)
]
a_sm_values = self.evaluate(a_sm_components)
for i, (a_sm_val, a_csr_mat) in enumerate(zip(a_sm_values, a_csr_mats)):
tf_logging.info("Comparing batch %d" % i)
self.assertAllEqual(a_csr_mat.indptr, a_sm_val.row_ptrs)
self.assertAllEqual(a_csr_mat.indices, a_sm_val.col_inds)
self.assertAllClose(a_csr_mat.data, a_sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
a_st_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
a_sm, type=a_st.dtype)
a_st_rt_value = self.evaluate(a_st_rt)
self.assertAllEqual(a_indices, a_st_rt_value.indices)
self.assertAllClose(a_values, a_st_rt_value.values)
self.assertAllEqual(a_dense_shape, a_st_rt_value.dense_shape)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseTensorConversion(self):
# Test two sets of conversions to check behavior of the ops in a
# concurrent environment (parallel executions of the ST -> SM ops).
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
mats = [
sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for _ in range(2)
]
csr_mats = [list(map(sparse.csr_matrix, mat)) for mat in mats]
mats_t = [ops.convert_to_tensor(mat) for mat in mats]
mats_locs = [array_ops.where(mat_t > 0) for mat_t in mats_t]
sparse_tensors = list()
for mat_t, mat_loc in zip(mats_t, mats_locs):
sparse_tensors.append(
sparse_tensor.SparseTensor(mat_loc,
array_ops.gather_nd(mat_t,
mat_loc), dense_shape))
sparse_matrices = [
sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
st.indices, st.values, st.dense_shape) for st in sparse_tensors
]
sm_nnz = [
sparse_csr_matrix_ops.sparse_matrix_nnz(sm) for sm in sparse_matrices
]
# Get row indices and columns for batches.
sm_components = list()
for sm in sparse_matrices:
sm_components.append([
sparse_csr_matrix_ops.csr_sparse_matrix_components(
sm, i, type=dtypes.float32) for i in range(dense_shape[0])
])
sm_nnz_values, sm_values = self.evaluate((sm_nnz, sm_components))
for i, (sm_values_i, csr_mats_i) in enumerate(zip(sm_values, csr_mats)):
for b, (sm_val, csr_mat) in enumerate(zip(sm_values_i, csr_mats_i)):
tf_logging.info("Comparing matrix %d batch %d" % (i, b))
self.assertEqual(csr_mat.nnz, sm_nnz_values[i][b])
self.assertAllEqual(csr_mat.indptr, sm_val.row_ptrs)
self.assertAllEqual(csr_mat.indices, sm_val.col_inds)
self.assertAllClose(csr_mat.data, sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
st_rt = [
sparse_csr_matrix_ops.csr_sparse_matrix_to_sparse_tensor(
sm, type=dtypes.float32) for sm in sparse_matrices
]
st_values, st_rt_values = self.evaluate((sparse_tensors, st_rt))
for (st_value, st_rt_value) in zip(st_values, st_rt_values):
self.assertAllEqual(st_value.indices, st_rt_value.indices)
self.assertAllClose(st_value.values, st_rt_value.values)
self.assertAllEqual(dense_shape, st_rt_value.dense_shape)
@test_util.run_in_graph_and_eager_modes
def testDenseConversion(self):
a_indices = np.array([[0, 0], [2, 3], [2, 4], [3, 0]])
a_values = np.array([1.0, 5.0, -1.0, -2.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_csr_mat = a_sparse_mat.tocsr()
a_dense = a_sparse_mat.todense()
# Convert 2D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
# Get row indices and columns for batch 0.
a_sm_row_ptrs, a_sm_col_inds, a_sm_values = (
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, 0, type=dtypes.float32))
a_sm_row_ptrs_values, a_sm_col_inds_values, a_sm_values_values = (
self.evaluate((a_sm_row_ptrs, a_sm_col_inds, a_sm_values)))
self.assertAllEqual(a_csr_mat.indices, a_sm_col_inds_values)
self.assertAllEqual(a_csr_mat.indptr, a_sm_row_ptrs_values)
self.assertAllClose(a_values, a_sm_values_values)
# Convert CSR Matrix to 2D dense matrix
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, dtypes.float32)
a_rt_value = self.evaluate(a_rt)
self.assertAllEqual(a_dense, a_rt_value)
@test_util.run_in_graph_and_eager_modes
def testBatchDenseConversion(self):
a_dense_shape = [4, 5, 6]
a_sparse_mats = [
sparse.coo_matrix(([1.0, 5.0], ([0, 2], [0, 3])),
shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([6.0], ([0], [1])), shape=a_dense_shape[1:]),
sparse.coo_matrix(([], ([], [])), shape=a_dense_shape[1:]),
]
a_csr_mats = [m.tocsr() for m in a_sparse_mats]
a_dense = np.asarray([m.todense() for m in a_sparse_mats], dtype=np.float32)
# Convert 3D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
# Get row indices and columns for batches.
a_sm_components = [
sparse_csr_matrix_ops.csr_sparse_matrix_components(
a_sm, i, type=dtypes.float32) for i in range(3)
]
a_sm_values = self.evaluate(a_sm_components)
for i, (a_sm_val, a_csr_mat) in enumerate(zip(a_sm_values, a_csr_mats)):
tf_logging.info("Comparing batch %d" % i)
self.assertAllEqual(a_csr_mat.indptr, a_sm_val.row_ptrs)
self.assertAllEqual(a_csr_mat.indices, a_sm_val.col_inds)
self.assertAllClose(a_csr_mat.data, a_sm_val.values)
# Convert CSR batched Matrix to 3D SparseTensor
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
a_sm, type=dtypes.float32)
a_rt_value = self.evaluate(a_rt)
self.assertAllEqual(a_dense, a_rt_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchDenseConversion(self):
# Test two sets of conversions to check behavior of the ops in a
# concurrent environment (parallel executions of the ST -> SM
# ops).
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
mats = [
sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for _ in range(2)
]
csr_mats = [[sparse.csr_matrix(m) for m in mat] for mat in mats]
mats_t = [ops.convert_to_tensor(mat) for mat in mats]
mats_locs = [array_ops.where(mat_t > 0) for mat_t in mats_t]
sparse_matrices = [
sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(mat, mat_loc)
for (mat, mat_loc) in zip(mats_t, mats_locs)
]
sm_nnz = [
sparse_csr_matrix_ops.sparse_matrix_nnz(sm) for sm in sparse_matrices
]
# Get row indices and columns for batches.
sm_components = []
for sm in sparse_matrices:
sm_components.append([
sparse_csr_matrix_ops.csr_sparse_matrix_components(
sm, i, type=dtypes.float32) for i in range(dense_shape[0])
])
sm_nnz_values, sm_values = self.evaluate((sm_nnz, sm_components))
for i, (sm_values_i, csr_mats_i) in enumerate(zip(sm_values, csr_mats)):
for b, (sm_val, csr_mat) in enumerate(zip(sm_values_i, csr_mats_i)):
tf_logging.info("Comparing matrix %d batch %d" % (i, b))
self.assertEqual(csr_mat.nnz, sm_nnz_values[i][b])
self.assertAllEqual(csr_mat.indptr, sm_val.row_ptrs)
self.assertAllEqual(csr_mat.indices, sm_val.col_inds)
self.assertAllClose(csr_mat.data, sm_val.values)
# Convert CSR batched Matrix to 3D dense tensor
sm_rt = [
sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
sm, type=dtypes.float32) for sm in sparse_matrices
]
sm_rt_values = self.evaluate(sm_rt)
for (mat, sm_rt_value) in zip(mats, sm_rt_values):
self.assertAllEqual(mat, sm_rt_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixAdd(self):
if not self._gpu_available:
return
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
b_indices = np.array([[1, 0], [1, 4], [2, 3], [4, 1]])
b_values = np.array([1.0, 0.5, -5.0, 2.0]).astype(np.float32)
b_dense_shape = [5, 6]
b_sparse_mat = sparse.coo_matrix(
(b_values, (b_indices[:, 0], b_indices[:, 1])), shape=b_dense_shape)
b_dense = b_sparse_mat.todense()
for (alpha, beta) in [(1.0, 1.0), (1.0, -1.0), (0.25, 0.5)]:
a_sum_b_sparse_mat = alpha * a_sparse_mat + beta * b_sparse_mat
# Convert 2D SparseTensor to CSR Matrix
a_sm = dense_to_csr_sparse_matrix(a_dense)
b_sm = dense_to_csr_sparse_matrix(b_dense)
alpha = np.float32(alpha)
beta = np.float32(beta)
c_sm = sparse_csr_matrix_ops.sparse_matrix_add(
a_sm, b_sm, alpha=alpha, beta=beta)
c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_dense_value = self.evaluate(c_dense)
self.assertAllClose(a_sum_b_sparse_mat.todense(), c_dense_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixAdd(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
b_mats = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for (alpha, beta) in [(1.0, 1.0), (1.0, -1.0), (0.25, 0.5)]:
tf_logging.info("testLargeBatchSparseMatrixAdd, comparing "
"alpha, beta (%d, %d)" % (alpha, beta))
a_sm = dense_to_csr_sparse_matrix(a_mats)
b_sm = dense_to_csr_sparse_matrix(b_mats)
alpha = np.float32(alpha)
beta = np.float32(beta)
c_sm = sparse_csr_matrix_ops.sparse_matrix_add(
a_sm, b_sm, alpha=alpha, beta=beta)
c_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_dense_value = self.evaluate(c_dense)
self.assertAllClose(c_dense_value, alpha * a_mats + beta * b_mats)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixMatMul(self):
for shapes in [[(5, 6), (6, 1)], [(5, 6), (6, 2)]]:
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = shapes[0]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
# Will multiply sparse a (shape=shapes[0]) by dense b (shape=shapes[1]).
b = np.random.randn(*shapes[1]).astype(np.float32)
a_sm = dense_to_csr_sparse_matrix(a_dense)
c = sparse_csr_matrix_ops.sparse_matrix_mat_mul(a=a_sm, b=b)
c_value = self.evaluate(c)
expected_c_value = a_sparse_mat.dot(b)
self.assertAllClose(expected_c_value, c_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixMatMulConjugateOutput(self):
for shapes in [[(5, 6), (6, 1)], [(5, 6), (6, 2)]]:
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0 + 1.j, 5.0 - 2.j]).astype(np.complex64)
a_dense_shape = shapes[0]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
# Will multiply sparse a (shape=shapes[0]) by dense b (shape=shapes[1]).
b = np.random.randn(*shapes[1]).astype(np.complex64)
a_sm = dense_to_csr_sparse_matrix(a_dense)
c = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a=a_sm, b=b, conjugate_output=True)
c_value = self.evaluate(c)
expected_c_value = self.evaluate(
math_ops.conj(test_util.matmul_without_tf32(a_dense, b)))
self.assertAllClose(expected_c_value, c_value)
@parameterized.product(
dtype=[np.float32, np.complex64],
transpose=[(False, False), (False, True), (True, False), (True, True)],
adjoint=[(False, False), (False, True), (True, False), (True, True)],
shapes=[([53, 127, 65], [53, 65, 1]), ([53, 127, 1], [53, 1, 65]),
([53, 127, 65], [53, 65, 127])])
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMul(self, dtype, transpose, adjoint, shapes):
sparsify = lambda m: m * (m > 0)
transpose_a, transpose_b = transpose
adjoint_a, adjoint_b = adjoint
if (transpose_a and adjoint_a) or (transpose_b and adjoint_b):
return
# Make copies so we don't update the lists inside the decorator arguments.
a_dense_shape = shapes[0][:]
b_dense_shape = shapes[1][:]
if transpose_a or adjoint_a:
_swap(a_dense_shape, -2, -1)
if transpose_b or adjoint_b:
_swap(b_dense_shape, -2, -1)
a_mats = sparsify((np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(dtype)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(dtype)
tf_logging.info(
"testLargeBatchSparseMatrixMatMul transpose_a %s transpose_b "
"%s adjoint_a %s adjoint_b %s" %
(transpose_a, transpose_b, adjoint_a, adjoint_b))
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm,
b_mats,
transpose_output=False,
conjugate_output=False,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
c_dense_t = test_util.matmul_without_tf32(
a_mats,
b_mats,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
self.assertAllEqual(c_dense_t.shape, c_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(c_t_value, c_dense_t_value, rtol=1e-6, atol=2e-5)
@parameterized.product(
dtype=[np.float32, np.complex64],
transpose=[(False, False), (False, True), (True, False), (True, True)],
adjoint=[(False, False), (False, True), (True, False), (True, True)],
shapes=[[[53, 127, 65], [53, 65, 1]], [[53, 127, 1], [53, 1, 65]],
[[53, 127, 65], [53, 65, 127]]])
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMulTransposed(self, dtype, transpose,
adjoint, shapes):
sparsify = lambda m: m * (m > 0)
(transpose_a, transpose_b) = transpose
(adjoint_a, adjoint_b) = adjoint
if (transpose_a and adjoint_a) or (transpose_b and adjoint_b):
return
# Make copies so we don't update the lists inside the decorator arguments.
a_dense_shape = shapes[0][:]
b_dense_shape = shapes[1][:]
if transpose_a or adjoint_a:
_swap(a_dense_shape, -2, -1)
if transpose_b or adjoint_b:
_swap(b_dense_shape, -2, -1)
a_mats = sparsify((np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(dtype)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(dtype)
tf_logging.info(
"testLargeBatchSparseMatrixMatMul transpose_a %s transpose_b "
"%s adjoint_a %s adjoint_b %s" %
(transpose_a, transpose_b, adjoint_a, adjoint_b))
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm,
b_mats,
transpose_output=True,
conjugate_output=False,
transpose_a=transpose_a,
transpose_b=transpose_b,
adjoint_a=adjoint_a,
adjoint_b=adjoint_b)
# Example: t(adj(a) . b) = t(b) . conj(a)
c_dense_t = test_util.matmul_without_tf32(
math_ops.conj(b_mats) if adjoint_b else b_mats,
math_ops.conj(a_mats) if adjoint_a else a_mats,
transpose_a=not (transpose_b or adjoint_b),
transpose_b=not (transpose_a or adjoint_a),
adjoint_a=False,
adjoint_b=False)
self.assertAllEqual(c_t.shape, c_dense_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(c_t_value, c_dense_t_value, rtol=1e-6, atol=2e-5)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMatMulConjugate(self):
sparsify = lambda m: m * (m > 0)
a_dense_shape = [53, 65, 127]
b_dense_shape = [53, 127, 67]
a_mats = sparsify(
(np.random.randn(*a_dense_shape) +
1.j * np.random.randn(*a_dense_shape))).astype(np.complex64)
b_mats = (np.random.randn(*b_dense_shape) +
1.j * np.random.randn(*b_dense_shape)).astype(np.complex64)
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mat_mul(
a_sm, b_mats, conjugate_output=True)
c_dense_t = math_ops.conj(test_util.matmul_without_tf32(a_mats, b_mats))
self.assertAllEqual(c_t.shape, c_dense_t.shape)
c_t_value, c_dense_t_value = self.evaluate((c_t, c_dense_t))
self.assertAllClose(c_t_value, c_dense_t_value, atol=1e-5, rtol=1e-5)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixSparseMatMul(self):
a_indices = np.array([[0, 0], [2, 3]])
a_values = np.array([1.0, 5.0]).astype(np.float32)
a_dense_shape = [5, 6]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
b_indices = np.array([[0, 0], [3, 0], [3, 1]])
b_values = np.array([2.0, 7.0, 8.0]).astype(np.float32)
b_dense_shape = [6, 7]
b_sparse_mat = sparse.coo_matrix(
(b_values, (b_indices[:, 0], b_indices[:, 1])), shape=b_dense_shape)
b_dense = b_sparse_mat.todense()
a_sm = dense_to_csr_sparse_matrix(a_dense)
b_sm = dense_to_csr_sparse_matrix(b_dense)
c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(
a=a_sm, b=b_sm, type=dtypes.float32)
c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32)
c_sm_dense_value = self.evaluate(c_sm_dense)
expected_c_value = a_sparse_mat.dot(b_sparse_mat).todense()
self.assertAllClose(expected_c_value, c_sm_dense_value)
@test_util.run_in_graph_and_eager_modes
def testSparseMatrixSparseMatMul_NumericZerosNotPruned(self):
# Tests that numeric zeros appearing from the sparse-sparse matrix
# multiplication are not pruned from the sparse structural
a_indices = np.array([[0, 0], [0, 2]])
a_values = np.array([2.0, -1.0]).astype(np.float32)
a_dense_shape = [2, 3]
a_sparse_mat = sparse.coo_matrix(
(a_values, (a_indices[:, 0], a_indices[:, 1])), shape=a_dense_shape)
a_dense = a_sparse_mat.todense()
b_indices = np.array([[0, 1], [2, 1]])
b_values = np.array([3.0, 6.0]).astype(np.float32)
b_dense_shape = [3, 2]
b_sparse_mat = sparse.coo_matrix(
(b_values, (b_indices[:, 0], b_indices[:, 1])), shape=b_dense_shape)
b_dense = b_sparse_mat.todense()
# Convert to CSRSparseMatrix while removing numeric zeros from the
# structural representation.
a_sm = dense_to_csr_sparse_matrix(a_dense)
b_sm = dense_to_csr_sparse_matrix(b_dense)
# Compute the matmul.
c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(
a=a_sm, b=b_sm, type=dtypes.float32)
c_nnz = sparse_csr_matrix_ops.sparse_matrix_nnz(c_sm)
c_nnz_value = self.evaluate(c_nnz)
# Expect that there is a single numeric zero at index (0, 1) if zeros are
# not pruned, since 2.0 * 3.0 + (-1.0) * 6.0 = 0.0.
self.assertAllClose(1, c_nnz_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixSparseMatMul(self):
sparsify = lambda m: m * (m > 0)
for (transpose_a, transpose_b) in ((False, False), (False, True),
(True, False), (True, True)):
for (adjoint_a, adjoint_b) in ((False, False), (False, True),
(True, False), (True, True)):
if (transpose_a and adjoint_a) or (transpose_b and adjoint_b):
continue
for a_batch_size in (1, 53):
for b_batch_size in (1, 53):
a_dense_shape = (
[a_batch_size, 127, 65]
if transpose_a or adjoint_a
else [a_batch_size, 65, 127]
)
b_dense_shape = (
[b_batch_size, 67, 127]
if transpose_b or adjoint_b
else [b_batch_size, 127, 67]
)
a_mats = sparsify(np.random.randn(*a_dense_shape)).astype(
np.float32
)
b_mats = sparsify(
np.random.randn(*b_dense_shape).astype(np.float32)
)
a_sm = dense_to_csr_sparse_matrix(a_mats)
b_sm = dense_to_csr_sparse_matrix(b_mats)
c_sm = sparse_csr_matrix_ops.sparse_matrix_sparse_mat_mul(
a_sm,
b_sm,
type=dtypes.float32,
transpose_a=transpose_a,
adjoint_a=adjoint_a,
transpose_b=transpose_b,
adjoint_b=adjoint_b,
)
c_sm_dense = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_sm, dtypes.float32
)
c_dense_t = test_util.matmul_without_tf32(
a_mats,
b_mats,
transpose_a=transpose_a,
adjoint_a=adjoint_a,
transpose_b=transpose_b,
adjoint_b=adjoint_b,
)
c_dense_t_value, c_sm_dense_value = self.evaluate(
(c_dense_t, c_sm_dense)
)
self.assertAllClose(c_sm_dense_value, c_dense_t_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchRegisteredAddN(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
matrices = [
sparsify(np.random.randn(*dense_shape)).astype(np.float32)
for _ in range(16)
]
sparse_matrices = [dense_to_csr_sparse_matrix(mat) for mat in matrices]
sparse_matrices_sum = math_ops.add_n(sparse_matrices)
sparse_matrices_sum_dense = \
sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
sparse_matrices_sum, dtypes.float32)
sparse_matrices_sum_dense_value = self.evaluate(sparse_matrices_sum_dense)
# Ensure that the dense (numpy) sum across all batches matches the result
# of add_n converted back to dense.
expected_sum = np.sum(matrices, axis=0)
self.assertAllClose(expected_sum, sparse_matrices_sum_dense_value)
@test_util.run_in_graph_and_eager_modes
def testCSRZeros(self):
if not self._gpu_available:
return
a_dense_shape = [65, 127]
b_dense_shape = [53, 127, 67]
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
# Check both rank-2 and rank-3 tensors.
a_sm = sparse_csr_matrix_ops.sparse_matrix_zeros(
a_dense_shape, type=dtype)
b_sm = sparse_csr_matrix_ops.sparse_matrix_zeros(
b_dense_shape, type=dtype)
a_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(a_sm, type=dtype)
b_rt = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(b_sm, type=dtype)
a_rt_value, b_rt_value = self.evaluate((a_rt, b_rt))
self.assertAllEqual(a_rt_value, np.zeros(a_dense_shape))
self.assertAllEqual(b_rt_value, np.zeros(b_dense_shape))
@test_util.run_in_graph_and_eager_modes
def testLargeBatchZerosLike(self):
if not self._gpu_available:
return
batch_size = 53
rows = 128
cols = 67
dense_shape = [batch_size, rows, cols]
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
sparse_matrices = sparse_csr_matrix_ops.sparse_matrix_zeros(
dense_shape, type=dtype)
zeros_like_sparse_matrices = array_ops.zeros_like(sparse_matrices)
zeros_like_components = [
sparse_csr_matrix_ops.csr_sparse_matrix_components(
zeros_like_sparse_matrices, i, type=dtype)
for i in range(batch_size)
]
zeros_like_components_values = self.evaluate(zeros_like_components)
for component in zeros_like_components_values:
self.assertAllEqual(component.row_ptrs, np.zeros(rows + 1, np.int32))
self.assertAllEqual(component.col_inds, np.empty([0], np.int32))
self.assertAllEqual(component.values, np.empty([0],
dtype.as_numpy_dtype))
@test_util.run_in_graph_and_eager_modes
def testTranspose(self):
sparsify = lambda m: m * (m > 0)
dense_shape = [127, 65]
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
mats = sparsify(
(np.random.randn(*dense_shape) +
1.j * np.random.randn(*dense_shape))).astype(dtype.as_numpy_dtype)
for conjugate in False, True:
expected = np.transpose(mats)
if conjugate:
expected = np.conj(expected)
matrices = math_ops.cast(mats, dtype)
sparse_matrices = dense_to_csr_sparse_matrix(matrices)
transpose_sparse_matrices = \
sparse_csr_matrix_ops.sparse_matrix_transpose(
sparse_matrices, conjugate=conjugate, type=dtype)
dense_transposed = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
transpose_sparse_matrices, dtype)
dense_transposed_values = self.evaluate(dense_transposed)
self.assertAllClose(expected, dense_transposed_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchTranspose(self):
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
mats = sparsify(
(np.random.randn(*dense_shape) +
1.j * np.random.randn(*dense_shape))).astype(dtype.as_numpy_dtype)
expected = np.transpose(mats, (0, 2, 1))
for conjugate in False, True:
if conjugate:
expected = np.conj(expected)
matrices = math_ops.cast(mats, dtype)
sparse_matrices = dense_to_csr_sparse_matrix(matrices)
transpose_sparse_matrices = \
sparse_csr_matrix_ops.sparse_matrix_transpose(
sparse_matrices, conjugate=conjugate, type=dtype)
dense_transposed = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
transpose_sparse_matrices, dtype)
dense_transposed_values = self.evaluate(dense_transposed)
self.assertAllClose(expected, dense_transposed_values)
@test_util.run_in_graph_and_eager_modes
def testSoftmax(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [127, 65]
logits = sparsify(np.random.randn(*dense_shape))
logits_with_ninf = np.copy(logits)
logits_with_ninf[logits == 0] = -np.inf
data_types = [dtypes.float32, dtypes.float64]
for dtype in data_types:
logits_t = math_ops.cast(logits, dtype)
logits_t_with_ninf = math_ops.cast(logits_with_ninf, dtype)
expected = nn_ops.softmax(logits_t_with_ninf)
sparse_logits_t = dense_to_csr_sparse_matrix(logits_t)
softmax_sparse_logits_t = sparse_csr_matrix_ops.sparse_matrix_softmax(
sparse_logits_t, type=dtype)
dense_softmax = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
softmax_sparse_logits_t, dtype)
dense_softmax_values, expected_values = self.evaluate(
(dense_softmax, expected))
self.assertAllClose(expected_values, dense_softmax_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSoftmax(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
logits = sparsify(np.random.randn(*dense_shape))
logits_with_ninf = np.copy(logits)
logits_with_ninf[logits == 0] = -np.inf
data_types = [dtypes.float32, dtypes.float64]
for dtype in data_types:
logits_t = math_ops.cast(logits, dtype)
logits_t_with_ninf = math_ops.cast(logits_with_ninf, dtype)
expected = nn_ops.softmax(logits_t_with_ninf)
sparse_logits_t = dense_to_csr_sparse_matrix(logits_t)
softmax_sparse_logits_t = sparse_csr_matrix_ops.sparse_matrix_softmax(
sparse_logits_t, type=dtype)
dense_softmax = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
softmax_sparse_logits_t, dtype)
dense_softmax_values, expected_values = self.evaluate(
(dense_softmax, expected))
self.assertAllClose(expected_values, dense_softmax_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSoftmaxEmpty(self):
if not self._gpu_available:
return
dense_shape = [53, 65, 127]
sparse_logits_t = sparse_csr_matrix_ops.sparse_matrix_zeros(
dense_shape, type=dtypes.float32)
softmax_sparse_logits_t = sparse_csr_matrix_ops.sparse_matrix_softmax(
sparse_logits_t, type=dtypes.float32)
dense_softmax = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
softmax_sparse_logits_t, dtypes.float32)
dense_softmax_values = self.evaluate(dense_softmax)
self.assertAllEqual(
np.zeros_like(dense_softmax_values), dense_softmax_values)
@test_util.run_in_graph_and_eager_modes
def testSoftmaxGrad(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [127, 65]
softmax = sparsify(np.random.randn(*dense_shape))
grad_softmax = sparsify(np.random.randn(*dense_shape))
expected = (
(grad_softmax - np.sum(grad_softmax * softmax, -1, keepdims=True)) *
softmax)
data_types = [dtypes.float32, dtypes.float64]
for dtype in data_types:
softmax_t = math_ops.cast(softmax, dtype)
grad_softmax_t = math_ops.cast(grad_softmax, dtype)
softmax_sparse = dense_to_csr_sparse_matrix(softmax_t)
grad_softmax_sparse = dense_to_csr_sparse_matrix(grad_softmax_t)
gradients_sparse = sparse_csr_matrix_ops.sparse_matrix_softmax_grad(
softmax_sparse, grad_softmax_sparse, dtype)
dense_gradients = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
gradients_sparse, dtype)
dense_gradients_values = self.evaluate((dense_gradients))
self.assertAllClose(expected, dense_gradients_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSoftmaxGrad(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
softmax = sparsify(np.random.randn(*dense_shape))
grad_softmax = sparsify(np.random.randn(*dense_shape))
expected = (
(grad_softmax - np.sum(grad_softmax * softmax, -1, keepdims=True)) *
softmax)
data_types = [dtypes.float32, dtypes.float64]
for dtype in data_types:
softmax_t = math_ops.cast(softmax, dtype)
grad_softmax_t = math_ops.cast(grad_softmax, dtype)
softmax_sparse = dense_to_csr_sparse_matrix(softmax_t)
grad_softmax_sparse = dense_to_csr_sparse_matrix(grad_softmax_t)
gradients_sparse = sparse_csr_matrix_ops.sparse_matrix_softmax_grad(
softmax_sparse, grad_softmax_sparse, dtype)
dense_gradients = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
gradients_sparse, dtype)
dense_gradients_values = self.evaluate((dense_gradients))
self.assertAllClose(expected, dense_gradients_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSoftmaxGradEmpty(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
dense_shape = [53, 65, 127]
not_empty = sparsify(np.random.randn(*dense_shape)).astype(np.float32)
sparse_empty = sparse_csr_matrix_ops.sparse_matrix_zeros(
dense_shape, type=dtypes.float32)
sparse_not_empty = dense_to_csr_sparse_matrix(not_empty)
gradients_empty_softmax = sparse_csr_matrix_ops.sparse_matrix_softmax_grad(
sparse_empty, sparse_not_empty, dtypes.float32)
gradients_empty_grad_softmax = (
sparse_csr_matrix_ops.sparse_matrix_softmax_grad(
sparse_not_empty, sparse_empty, dtypes.float32))
gradients_empty_both = sparse_csr_matrix_ops.sparse_matrix_softmax_grad(
sparse_empty, sparse_empty, dtypes.float32)
ges = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
gradients_empty_softmax, dtypes.float32)
gegs = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
gradients_empty_grad_softmax, dtypes.float32)
geb = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
gradients_empty_both, dtypes.float32)
ges_v, gegs_v, geb_v = self.evaluate((ges, gegs, geb))
for v in (ges_v, gegs_v, geb_v):
self.assertAllEqual(np.zeros(dense_shape), v)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchConj(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (np.real(m) > 0)
dense_shape = [53, 65, 127]
matrices = (
sparsify(np.random.randn(*dense_shape)) +
1j * np.random.randn(*dense_shape))
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
matrices_t = matrices.astype(dtype.as_numpy_dtype)
expected = np.conj(matrices_t)
sparse_matrices = dense_to_csr_sparse_matrix(matrices_t)
conj_sparse_matrices = math_ops.conj(sparse_matrices)
dense_conj_matrices = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
conj_sparse_matrices, dtype)
conj_values = self.evaluate(dense_conj_matrices)
self.assertAllClose(expected, conj_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMulScalar(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
a_dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*a_dense_shape)).astype(np.float32)
b = np.float32(3.5)
expected = a_mats * b
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mul(a_sm, b)
c_dense_t = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_t, dtypes.float32)
c_dense_t_value = self.evaluate(c_dense_t)
self.assertAllClose(expected, c_dense_t_value)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseMatrixMulVec(self):
if not self._gpu_available:
return
sparsify = lambda m: m * (m > 0)
a_dense_shape = [53, 65, 127]
a_mats = sparsify(np.random.randn(*a_dense_shape)).astype(np.float32)
b = np.random.randn(53, 1, 1).astype(np.float32)
expected = a_mats * b
a_sm = dense_to_csr_sparse_matrix(a_mats)
c_t = sparse_csr_matrix_ops.sparse_matrix_mul(a_sm, b)
c_dense_t = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
c_t, dtypes.float32)
c_dense_t_value = self.evaluate(c_dense_t)
self.assertAllClose(expected, c_dense_t_value)
@test_util.run_in_graph_and_eager_modes
def testSparseCholesky(self):
dense_matrix = np.array([
[2, 0, 0, 0, 0, 0],
[0, 3, 0, 0, 0, 0],
[1, 1, 7, 0, 0, 0],
[0, 0, 0, 4, 0, 0],
[0, 0, 1, 0, 5, 0],
[0, 0, 2, 0, 1, 6],
]).astype(np.complex128)
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
with test_util.force_cpu():
if dtype.is_complex:
dense_matrix += 0.5j * np.tril(dense_matrix, -1)
sparse_matrix = dense_to_csr_sparse_matrix(
math_ops.cast(dense_matrix, dtype))
# Obtain the Sparse Cholesky factor using AMD Ordering for reducing
# fill-in.
ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(
sparse_matrix)
cholesky_sparse_matrices = (
sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, ordering_amd, type=dtype))
dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
cholesky_sparse_matrices, dtype)
# Compute L * Lh where L is the Sparse Cholesky factor.
verification = test_util.matmul_without_tf32(
dense_cholesky, array_ops.transpose(dense_cholesky, conjugate=True))
verification = twist_matrix(verification, ordering_amd)
# Assert that input matrix A satisfies A = L * Lh.
verification_values = self.evaluate(verification)
full_dense_matrix = (
dense_matrix +
np.conjugate(np.transpose(np.tril(dense_matrix, -1))))
self.assertAllClose(full_dense_matrix, verification_values)
@test_util.run_in_graph_and_eager_modes
def testBatchSparseCholesky(self):
dense_mat = np.array([
# A diagonal matrix.
[
[1, 0, 0, 0], #
[0, 2, 0, 0], #
[0, 0, 3, 0], #
[0, 0, 0, 4],
], #
# A tridiagonal hermitian matrix.
[
[5 + 0j, 1 + 0j, 0 + 0j, 0 + 0j], #
[1 + 0j, 4 + 0j, 1 + 2j, 0 + 0j], #
[0 + 0j, 1 - 2j, 9 + 0j, 3 - 3j], #
[0 + 0j, 0 + 0j, 3 + 3j, 7 + 0j],
], #
# A diagonal matrix with a corner element; for which
# OrderingAMD returns a non-identity permutation.
[
[1, 0, 0, 1.], #
[0, 2, 0, 0.], #
[0, 0, 3, 0.], #
[1, 0, 0, 4.],
] #
]).astype(np.complex128)
data_types = [
dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128
]
for dtype in data_types:
sparse_matrix = dense_to_csr_sparse_matrix(
math_ops.cast(dense_mat, dtype))
ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(
sparse_matrix)
cholesky_sparse_matrix = (
sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, ordering_amd, type=dtype))
dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
cholesky_sparse_matrix, dtype)
# Compute L * Lh.
verification = test_util.matmul_without_tf32(
dense_cholesky,
array_ops.transpose(dense_cholesky, perm=[0, 2, 1], conjugate=True))
verification = twist_matrix(verification, ordering_amd)
verification_values = self.evaluate(verification)
self.assertAllClose(
dense_mat.astype(dtype.as_numpy_dtype), verification_values)
@test_util.run_in_graph_and_eager_modes
def testLargeBatchSparseCholesky(self):
sparsity = 0.1
sparsify = lambda m: m * (m > 1 - sparsity)
batch_size = 53
num_rows = 147
dense_shape = [batch_size, num_rows, num_rows]
dense_matrix = sparsify(np.random.uniform(size=dense_shape)).astype(
np.float32)
# Create a "random" SPD matrix, by choosing each entry of A between
# 0 and 1 at the specified density, and computing 0.5(A + At) + n*I.
# This ensures diagonal dominance which implies positive-definiteness.
dense_matrix = (
0.5 *
(dense_matrix + array_ops.transpose(dense_matrix, perm=[0, 2, 1])) +
num_rows * linalg_ops.eye(dense_shape[-1], batch_shape=[batch_size]))
# Compute the fill-in reducing permutation and use it to perform
# the Sparse Cholesky factorization.
sparse_matrix = dense_to_csr_sparse_matrix(dense_matrix)
ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(
sparse_matrix)
cholesky_sparse_matrix = \
sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, ordering_amd, type=dtypes.float32)
dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
cholesky_sparse_matrix, dtypes.float32)
# Compute L * Lh.
verification = test_util.matmul_without_tf32(
dense_cholesky, array_ops.transpose(dense_cholesky, perm=[0, 2, 1]))
verification = twist_matrix(verification, ordering_amd)
verification_values = self.evaluate(verification)
self.assertAllClose(dense_matrix, verification_values, atol=1e-5, rtol=1e-5)
@test_util.run_in_graph_and_eager_modes
def testSparseCholesky_InvalidMatrix(self):
# Verify that non-SPD matrices result in an Invalid Argument error.
invalid_matrices = [
# zero matrix.
np.array([
[0., 0., 0., 0.], #
[0., 0., 0., 0.], #
[0., 0., 0., 0.], #
[0., 0., 0., 0.] #
]),
# zero diagonal entry.
np.array([
[9., 0., 5., 0.], #
[0., 0., 0., 1.], #
[5., 0., 8., 0.], #
[0., 1., 0., 7.] #
]),
# not positive definite.
np.array([
[2., -2., 0., 0.], #
[-2., 2., 0., 0.], #
[0., 0., 3., -3.], #
[0., 0., -3., 3.] #
]),
]
with test_util.force_cpu():
for invalid_matrix in invalid_matrices:
with self.assertRaises(errors.InvalidArgumentError):
sparse_matrix = dense_to_csr_sparse_matrix(
invalid_matrix.astype(np.float32))
# Compute the fill-in reducing permutation and use it to perform
# the Sparse Cholesky factorization.
ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(
sparse_matrix)
cholesky_sparse_matrices = (
sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, ordering_amd, type=dtypes.float32))
# Convert the Cholesky factor to a dense matrix to be evaluated.
dense_cholesky = sparse_csr_matrix_ops.csr_sparse_matrix_to_dense(
cholesky_sparse_matrices, type=dtypes.float32)
self.evaluate(dense_cholesky)
@test_util.run_in_graph_and_eager_modes
def testOrderingAMD(self):
num_rows = 6
# An SPD matrix where AMD ordering can reduce fill-in for Cholesky factor.
dense_matrix = np.array([
[7, 0, 0, 0, 0, 0],
[1, 4, 0, 0, 0, 0],
[1, 1, 3, 0, 0, 0],
[0, 0, 0, 4, 0, 0],
[2, 0, 0, 0, 5, 0],
[1, 2, 2, 0, 0, 6],
]).astype(np.float32)
with test_util.force_cpu():
sparse_matrix = dense_to_csr_sparse_matrix(dense_matrix)
# Obtain the Sparse Cholesky factor with the identity permutation as the
# fill-in reducing ordering.
cholesky_without_ordering = (
sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, math_ops.range(num_rows), type=dtypes.float32))
cholesky_without_ordering_nnz = sparse_csr_matrix_ops.sparse_matrix_nnz(
cholesky_without_ordering)
# Obtain the Sparse Cholesky factor using AMD Ordering for reducing
# fill-in.
ordering_amd = sparse_csr_matrix_ops.sparse_matrix_ordering_amd(
sparse_matrix)
cholesky_with_amd = sparse_csr_matrix_ops.sparse_matrix_sparse_cholesky(
sparse_matrix, ordering_amd, type=dtypes.float32)
cholesky_with_amd_nnz = sparse_csr_matrix_ops.sparse_matrix_nnz(
cholesky_with_amd)
(ordering_amd_value, cholesky_with_amd_nnz_value,
cholesky_without_ordering_nnz_value) = self.evaluate(
[ordering_amd, cholesky_with_amd_nnz, cholesky_without_ordering_nnz])
# AMD ordering should return a valid permutation.
self.assertAllClose(np.arange(num_rows), np.sort(ordering_amd_value))
# Check that cholesky with AMD ordering has a strictly lower nonzero count
# for this matrix.
self.assertLess(cholesky_with_amd_nnz_value,
cholesky_without_ordering_nnz_value)
@test_util.run_in_graph_and_eager_modes
def testNoMatrixNoCrash(self):
# Round-about way of creating an empty variant tensor that works in both
# graph and eager modes.
no_matrix = array_ops.reshape(dense_to_csr_sparse_matrix([[0.0]]), [1])[0:0]
with self.assertRaisesRegex(
(ValueError, errors.InvalidArgumentError),
"(Invalid input matrix)|(Shape must be rank 0)"):
sparse_csr_matrix_ops.sparse_matrix_nnz(no_matrix)
|
CSRSparseMatrixOpsTest
|
python
|
pytorch__pytorch
|
torch/_inductor/codegen/memory_planning.py
|
{
"start": 1398,
"end": 2736
}
|
class ____:
"""
A collection of LiveRange regions, allowing for non-contiguous
live regions.
Invariant: LiveRanges.ranges is in sorted order and non-overlapping
"""
def __init__(self, ranges: Iterable[LiveRange]):
ranges = [*sorted(ranges, key=lambda x: x.begin)]
self.ranges = ranges[:1]
for r in ranges[1:]:
assert self.ranges[-1].begin <= r.begin
if self.ranges[-1].end >= r.begin:
self.ranges[-1] = LiveRange.join(self.ranges[-1], r)
else:
self.ranges.append(r)
def overlaps(self, other: LiveRanges):
"""Check if any pair of ranges in self and other overlap"""
left = collections.deque(self.ranges)
right = collections.deque(other.ranges)
while left and right:
if left[0].begin > right[0].begin:
left, right = right, left
assert left[0].begin <= right[0].begin
if left[0].end > right[0].begin:
return True
left.popleft()
return False
@property
def begin(self):
return self.ranges[0].begin
@property
def end(self):
return self.ranges[-1].end
def __repr__(self):
return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])"
|
LiveRanges
|
python
|
pypa__pipenv
|
pipenv/vendor/importlib_metadata/_itertools.py
|
{
"start": 2147,
"end": 5351
}
|
class ____:
"""Wrap *iterable* and return an object that buckets the iterable into
child iterables based on a *key* function.
>>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']
>>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character
>>> sorted(list(s)) # Get the keys
['a', 'b', 'c']
>>> a_iterable = s['a']
>>> next(a_iterable)
'a1'
>>> next(a_iterable)
'a2'
>>> list(s['b'])
['b1', 'b2', 'b3']
The original iterable will be advanced and its items will be cached until
they are used by the child iterables. This may require significant storage.
By default, attempting to select a bucket to which no items belong will
exhaust the iterable and cache all values.
If you specify a *validator* function, selected buckets will instead be
checked against it.
>>> from itertools import count
>>> it = count(1, 2) # Infinite sequence of odd numbers
>>> key = lambda x: x % 10 # Bucket by last digit
>>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only
>>> s = bucket(it, key=key, validator=validator)
>>> 2 in s
False
>>> list(s[2])
[]
"""
def __init__(self, iterable, key, validator=None):
self._it = iter(iterable)
self._key = key
self._cache = defaultdict(deque)
self._validator = validator or (lambda x: True)
def __contains__(self, value):
if not self._validator(value):
return False
try:
item = next(self[value])
except StopIteration:
return False
else:
self._cache[value].appendleft(item)
return True
def _get_values(self, value):
"""
Helper to yield items from the parent iterator that match *value*.
Items that don't match are stored in the local cache as they
are encountered.
"""
while True:
# If we've cached some items that match the target value, emit
# the first one and evict it from the cache.
if self._cache[value]:
yield self._cache[value].popleft()
# Otherwise we need to advance the parent iterator to search for
# a matching item, caching the rest.
else:
while True:
try:
item = next(self._it)
except StopIteration:
return
item_value = self._key(item)
if item_value == value:
yield item
break
elif self._validator(item_value):
self._cache[item_value].append(item)
def __iter__(self):
for item in self._it:
item_value = self._key(item)
if self._validator(item_value):
self._cache[item_value].append(item)
yield from self._cache.keys()
def __getitem__(self, value):
if not self._validator(value):
return iter(())
return self._get_values(value)
|
bucket
|
python
|
pypa__pipenv
|
pipenv/vendor/click/shell_completion.py
|
{
"start": 9048,
"end": 10520
}
|
class ____(ShellComplete):
"""Shell completion for Bash."""
name = "bash"
source_template = _SOURCE_BASH
@staticmethod
def _check_version() -> None:
import subprocess
output = subprocess.run(
["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE
)
match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())
if match is not None:
major, minor = match.groups()
if major < "4" or major == "4" and minor < "4":
echo(
_(
"Shell completion is not supported for Bash"
" versions older than 4.4."
),
err=True,
)
else:
echo(
_("Couldn't detect Bash version, shell completion is not supported."),
err=True,
)
def source(self) -> str:
self._check_version()
return super().source()
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
cwords = split_arg_string(os.environ["COMP_WORDS"])
cword = int(os.environ["COMP_CWORD"])
args = cwords[1:cword]
try:
incomplete = cwords[cword]
except IndexError:
incomplete = ""
return args, incomplete
def format_completion(self, item: CompletionItem) -> str:
return f"{item.type},{item.value}"
|
BashComplete
|
python
|
openai__openai-python
|
src/openai/types/realtime/realtime_session_create_response.py
|
{
"start": 10334,
"end": 12589
}
|
class ____(BaseModel):
server_label: str
"""A label for this MCP server, used to identify it in tool calls."""
type: Literal["mcp"]
"""The type of the MCP tool. Always `mcp`."""
allowed_tools: Optional[ToolMcpToolAllowedTools] = None
"""List of allowed tool names or a filter object."""
authorization: Optional[str] = None
"""
An OAuth access token that can be used with a remote MCP server, either with a
custom MCP server URL or a service connector. Your application must handle the
OAuth authorization flow and provide the token here.
"""
connector_id: Optional[
Literal[
"connector_dropbox",
"connector_gmail",
"connector_googlecalendar",
"connector_googledrive",
"connector_microsoftteams",
"connector_outlookcalendar",
"connector_outlookemail",
"connector_sharepoint",
]
] = None
"""Identifier for service connectors, like those available in ChatGPT.
One of `server_url` or `connector_id` must be provided. Learn more about service
connectors
[here](https://platform.openai.com/docs/guides/tools-remote-mcp#connectors).
Currently supported `connector_id` values are:
- Dropbox: `connector_dropbox`
- Gmail: `connector_gmail`
- Google Calendar: `connector_googlecalendar`
- Google Drive: `connector_googledrive`
- Microsoft Teams: `connector_microsoftteams`
- Outlook Calendar: `connector_outlookcalendar`
- Outlook Email: `connector_outlookemail`
- SharePoint: `connector_sharepoint`
"""
headers: Optional[Dict[str, str]] = None
"""Optional HTTP headers to send to the MCP server.
Use for authentication or other purposes.
"""
require_approval: Optional[ToolMcpToolRequireApproval] = None
"""Specify which of the MCP server's tools require approval."""
server_description: Optional[str] = None
"""Optional description of the MCP server, used to provide more context."""
server_url: Optional[str] = None
"""The URL for the MCP server.
One of `server_url` or `connector_id` must be provided.
"""
Tool: TypeAlias = Union[RealtimeFunctionTool, ToolMcpTool]
|
ToolMcpTool
|
python
|
tiangolo__fastapi
|
docs_src/dependencies/tutorial008c_an.py
|
{
"start": 111,
"end": 707
}
|
class ____(Exception):
pass
def get_username():
try:
yield "Rick"
except InternalError:
print("Oops, we didn't raise again, Britney 😱")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: Annotated[str, Depends(get_username)]):
if item_id == "portal-gun":
raise InternalError(
f"The portal gun is too dangerous to be owned by {username}"
)
if item_id != "plumbus":
raise HTTPException(
status_code=404, detail="Item not found, there's only a plumbus here"
)
return item_id
|
InternalError
|
python
|
django__django
|
django/db/models/expressions.py
|
{
"start": 52303,
"end": 54478
}
|
class ____(ExpressionWrapper):
"""The logical negation of a conditional expression."""
def __init__(self, expression):
super().__init__(expression, output_field=fields.BooleanField())
def __invert__(self):
return self.expression.copy()
def as_sql(self, compiler, connection):
try:
sql, params = super().as_sql(compiler, connection)
except EmptyResultSet:
features = compiler.connection.features
if not features.supports_boolean_expr_in_select_clause:
return "1=1", ()
return compiler.compile(Value(True))
ops = compiler.connection.ops
# Some database backends (e.g. Oracle) don't allow EXISTS() and filters
# to be compared to another expression unless they're wrapped in a CASE
# WHEN.
if not ops.conditional_expression_supported_in_where_clause(self.expression):
return f"CASE WHEN {sql} = 0 THEN 1 ELSE 0 END", params
return f"NOT {sql}", params
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
resolved = super().resolve_expression(
query, allow_joins, reuse, summarize, for_save
)
if not getattr(resolved.expression, "conditional", False):
raise TypeError("Cannot negate non-conditional expressions.")
return resolved
def select_format(self, compiler, sql, params):
# Wrap boolean expressions with a CASE WHEN expression if a database
# backend (e.g. Oracle) doesn't support boolean expression in SELECT or
# GROUP BY list.
expression_supported_in_where_clause = (
compiler.connection.ops.conditional_expression_supported_in_where_clause
)
if (
not compiler.connection.features.supports_boolean_expr_in_select_clause
# Avoid double wrapping.
and expression_supported_in_where_clause(self.expression)
):
sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
return sql, params
@deconstructible(path="django.db.models.When")
|
NegatedExpression
|
python
|
run-llama__llama_index
|
llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/llama_index/embeddings/vertex_endpoint/utils.py
|
{
"start": 48,
"end": 681
}
|
class ____(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass: type) -> bool:
return (
hasattr(subclass, "serialize_input")
and callable(subclass.serialize_input)
and hasattr(subclass, "deserialize_output")
and callable(subclass.deserialize_output)
or NotImplemented
)
@abc.abstractmethod
def serialize_input(self, request: List[str]) -> bytes:
raise NotImplementedError
@abc.abstractmethod
def deserialize_output(self, response: Any) -> List[List[float]]:
raise NotImplementedError
|
BaseIOHandler
|
python
|
pennersr__django-allauth
|
allauth/socialaccount/providers/vimeo_oauth2/provider.py
|
{
"start": 308,
"end": 786
}
|
class ____(OAuth2Provider):
id = "vimeo_oauth2"
name = "Vimeo"
account_class = VimeoOAuth2Account
oauth2_adapter_class = VimeoOAuth2Adapter
def get_default_scope(self):
return ["public", "private"]
def extract_uid(self, data):
return data.get("uri").split("/")[-1]
def extract_common_fields(self, data):
return {
"fullname": data.get("name"),
}
provider_classes = [VimeoOAuth2Provider]
|
VimeoOAuth2Provider
|
python
|
pypa__pipenv
|
pipenv/patched/pip/_internal/operations/install/wheel.py
|
{
"start": 14127,
"end": 14457
}
|
class ____:
def __init__(self, file: "File") -> None:
self._file = file
self.src_record_path = self._file.src_record_path
self.dest_path = self._file.dest_path
self.changed = False
def save(self) -> None:
self._file.save()
self.changed = fix_script(self.dest_path)
|
ScriptFile
|
python
|
astropy__astropy
|
astropy/table/tests/conftest.py
|
{
"start": 1138,
"end": 1179
}
|
class ____(table.Column):
pass
|
MyColumn
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_data_labels26.py
|
{
"start": 315,
"end": 1561
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels26.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [48514944, 48516480]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
[10, 20, 30, 40, 50],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
worksheet.write_column("D1", data[3])
chart.add_series(
{
"values": "=Sheet1!$A$1:$A$5",
"data_labels": {"value": True, "custom": [{"value": 33}]},
}
)
chart.add_series({"values": "=Sheet1!$B$1:$B$5"})
chart.add_series({"values": "=Sheet1!$C$1:$C$5"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
django-guardian__django-guardian
|
guardian/testapp/tests/urls.py
|
{
"start": 225,
"end": 536
}
|
class ____(PermissionRequiredMixin, View):
permission_required = "testapp.change_project"
urlpatterns = [
path("admin/", admin.site.urls),
path("accounts/login/", LoginView.as_view(template_name="blank.html")),
path("permission_required/", TestClassRedirectView.as_view()),
]
|
TestClassRedirectView
|
python
|
prompt-toolkit__python-prompt-toolkit
|
src/prompt_toolkit/shortcuts/progress_bar/formatters.py
|
{
"start": 8458,
"end": 9268
}
|
class ____(Formatter):
"""
Display the iterations per second.
"""
template = HTML(
"<iterations-per-second>{iterations_per_second:.2f}</iterations-per-second>"
)
def format(
self,
progress_bar: ProgressBar,
progress: ProgressBarCounter[object],
width: int,
) -> AnyFormattedText:
value = progress.items_completed / progress.time_elapsed.total_seconds()
return self.template.format(iterations_per_second=value)
def get_width(self, progress_bar: ProgressBar) -> AnyDimension:
all_values = [
len(f"{c.items_completed / c.time_elapsed.total_seconds():.2f}")
for c in progress_bar.counters
]
if all_values:
return max(all_values)
return 0
|
IterationsPerSecond
|
python
|
huggingface__transformers
|
src/transformers/models/vaultgemma/configuration_vaultgemma.py
|
{
"start": 1319,
"end": 10161
}
|
class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VaultGemmaModel`]. It is used to instantiate an VaultGemma
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 VaultGemma-7B.
e.g. [google/vaultgemma-7b](https://huggingface.co/google/vaultgemma-7b)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 256000):
Vocabulary size of the VaultGemma model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`VaultGemmaModel`]
hidden_size (`int`, *optional*, defaults to 2304):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 9216):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 26):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*, defaults to 4):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
head_dim (`int`, *optional*, defaults to 256):
The attention head dimension.
hidden_activation (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
The non-linear activation function (function or string) in the decoder. Will default to `"gelu_pytorch_tanh"`
if not specified. `"gelu_pytorch_tanh"` uses an approximation of the `"gelu"` activation function.
max_position_embeddings (`int`, *optional*, defaults to 8192):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*, defaults to 0):
Padding token id.
eos_token_id (`int`, *optional*, defaults to 1):
End of stream token id.
bos_token_id (`int`, *optional*, defaults to 2):
Beginning of stream token id.
tie_word_embeddings (`bool`, *optional*, defaults to `True`):
Whether to tie weight embeddings
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
query_pre_attn_scalar (`float`, *optional*, defaults to 256):
scaling factor used on the attention scores
sliding_window (`int`, *optional*, defaults to 4096):
in VaultGemma, every other layer uses sliding window attention. This is the size of the sliding window.
layer_types (`list`, *optional*):
Attention pattern for each layer.
final_logit_softcapping (`float`, *optional*, defaults to 30.0):
scaling factor when applying tanh softcapping on the logits.
attn_logit_softcapping (`float`, *optional*, defaults to 50.0):
scaling factor when applying tanh softcapping on the attention scores.
```python
>>> from transformers import VaultGemmaModel, VaultGemmaConfig
>>> # Initializing a VaultGemma vaultgemma-7b style configuration
>>> configuration = VaultGemmaConfig()
>>> # Initializing a model from the vaultgemma-7b style configuration
>>> model = VaultGemmaModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "vaultgemma"
keys_to_ignore_at_inference = ["past_key_values"]
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 256000,
hidden_size: Optional[int] = 2304,
intermediate_size: Optional[int] = 9216,
num_hidden_layers: Optional[int] = 26,
num_attention_heads: Optional[int] = 8,
num_key_value_heads: Optional[int] = 4,
head_dim: Optional[int] = 256,
hidden_activation: Optional[str] = "gelu_pytorch_tanh",
max_position_embeddings: Optional[int] = 8192,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-6,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = 0,
eos_token_id: Optional[int] = 1,
bos_token_id: Optional[int] = 2,
tie_word_embeddings: Optional[bool] = True,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
query_pre_attn_scalar: Optional[int] = 256,
sliding_window: Optional[int] = 4096,
layer_types: Optional[list[str]] = None,
final_logit_softcapping: Optional[float] = 30.0,
attn_logit_softcapping: Optional[float] = 50.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.head_dim = head_dim
self.num_key_value_heads = num_key_value_heads
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.hidden_activation = hidden_activation
self.query_pre_attn_scalar = query_pre_attn_scalar
self.sliding_window = sliding_window
self.final_logit_softcapping = final_logit_softcapping
self.attn_logit_softcapping = attn_logit_softcapping
self.layer_types = layer_types
if self.layer_types is None:
self.layer_types = [
"sliding_attention" if bool((i + 1) % 2) else "full_attention" for i in range(self.num_hidden_layers)
]
layer_type_validation(self.layer_types, self.num_hidden_layers)
self.rope_parameters = rope_parameters
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["VaultGemmaConfig"]
|
VaultGemmaConfig
|
python
|
google__jax
|
docs/autodidax2_part1.py
|
{
"start": 2931,
"end": 7205
}
|
class ____:
def interpret_op(self, op, args):
assert all(isinstance(arg, float) for arg in args)
match op:
case Op.add:
x, y = args
return x + y
case Op.mul:
x, y = args
return x * y
case _:
raise ValueError(f"Unrecognized primitive op: {op}")
# The current interpreter is initially the evaluating interpreter.
current_interpreter = EvalInterpreter()
# A context manager for temporarily changing the current interpreter
@contextmanager
def set_interpreter(new_interpreter):
global current_interpreter
prev_interpreter = current_interpreter
try:
current_interpreter = new_interpreter
yield
finally:
current_interpreter = prev_interpreter
# The user-facing functions `mul` and `add` dispatch to the current interpreter.
def add(x, y): return current_interpreter.interpret_op(Op.add, (x, y))
def mul(x, y): return current_interpreter.interpret_op(Op.mul, (x, y))
# -
# At this point we can call `foo` with ordinary concrete inputs and see the
# results:
print(foo(2.0))
# ## Aside: forward-mode automatic differentiation
# For our second interpreter we're going to try forward-mode automatic
# differentiation (AD). Here's a quick introduction to forward-mode AD in case
# this is the first time you've come across it. Otherwise skip ahead to the
# "JVPInterprer" section.
# Suppose we're interested in the derivative of `foo(x)` evaluated at `x=2.0`.
# We could approximate it with finite differences:
print((foo(2.00001) - foo(2.0)) / 0.00001)
# The answer is close to 7.0 as expected. But computing it this way required two
# evaluations of the function (not to mention the roundoff error and truncation
# error). Here's a funny thing though. We can almost get the answer with a
# single evaluation:
print(foo(2.00001))
# The answer we're looking for, 7.0, is right there in the insignificant digits!
# Here's one way to think about what's happening. The initial argument to `foo`,
# `2.00001`, carries two pieces of data: a "primal" value, 2.0, and a "tangent"
# value, `1.0`. The representation of this primal-tangent pair, `2.00001`, is
# the sum of the two, with the tangent scaled by a small fixed epsilon, `1e-5`.
# Ordinary evaluation of `foo(2.00001)` propagates this primal-tangent pair,
# producing `10.0000700001` as the result. The primal and tangent components are
# well separated in scale so we can visually interpret the result as the
# primal-tangent pair (10.0, 7.0), ignoring the the ~1e-10 truncation error at
# the end.
# The idea with forward-mode differentiation is to do the same thing but exactly
# and explicitly (eyeballing floats doesn't really scale). We'll represent the
# primal-tangent pair as an actual pair instead of folding them both into a
# single floating point number. For each primitive operation we'll have a rule
# that describes how to propagate these primal tangent pairs. Let's work out the
# rules for our two primitives.
# Addition is easy. Consider `x + y` where `x = xp + xt * eps` and `y = yp + yt * eps`
# ("p" for "primal", "t" for "tangent"):
#
# x + y = (xp + xt * eps) + (yp + yt * eps)
# = (xp + yp) # primal component
# + (xt + yt) * eps # tangent component
#
# The result is a first-order polynomial in `eps` and we can read off the
# primal-tangent pair as (xp + yp, xt + yt).
# Multiplication is more interesting:
#
# x * y = (xp + xt * eps) * (yp + yt * eps)
# = (xp * yp) # primal component
# + (xp * yt + xt * yp) * eps # tangent component
# + (xt * yt) * eps * eps # quadratic component, vanishes in the eps->0 limit
#
# Now we have a second order polynomial. But as epsilon goes to zero the
# quadratic term vanishes and our primal-tangent pair
# is just `(xp * yp, xp * yt + xt * yp)`
# (In our earlier example with finite `eps` this term not vanishing is
# why we had the 1e-10 "truncation error").
# Putting this into code, we can write down the forward-AD rules for addition
# and multiplication and express `foo` in terms of these:
# +
from dataclasses import dataclass
# A primal-tangent pair is conventionally called a "dual number"
@dataclass
|
EvalInterpreter
|
python
|
ethereum__web3.py
|
web3/exceptions.py
|
{
"start": 7815,
"end": 7972
}
|
class ____(PersistentConnectionError):
"""
Raised when a persistent connection is closed gracefully by the server.
"""
|
PersistentConnectionClosedOK
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/nocover/test_type_lookup_future_annotations.py
|
{
"start": 671,
"end": 704
}
|
class ____(TypedDict):
a: int
|
A
|
python
|
Textualize__rich
|
rich/table.py
|
{
"start": 6133,
"end": 40025
}
|
class ____(JupyterMixin):
"""A console renderable to draw a table.
Args:
*headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.
title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.
caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.
width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.
min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.
box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.
safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.
padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).
collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.
pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.
expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.
show_header (bool, optional): Show a header row. Defaults to True.
show_footer (bool, optional): Show a footer row. Defaults to False.
show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.
show_lines (bool, optional): Draw lines between every row. Defaults to False.
leading (int, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.
style (Union[str, Style], optional): Default style for the table. Defaults to "none".
row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.
header_style (Union[str, Style], optional): Style of the header. Defaults to "table.header".
footer_style (Union[str, Style], optional): Style of the footer. Defaults to "table.footer".
border_style (Union[str, Style], optional): Style of the border. Defaults to None.
title_style (Union[str, Style], optional): Style of the title. Defaults to None.
caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.
title_justify (str, optional): Justify method for title. Defaults to "center".
caption_justify (str, optional): Justify method for caption. Defaults to "center".
highlight (bool, optional): Highlight cell contents (if str). Defaults to False.
"""
columns: List[Column]
rows: List[Row]
def __init__(
self,
*headers: Union[Column, str],
title: Optional[TextType] = None,
caption: Optional[TextType] = None,
width: Optional[int] = None,
min_width: Optional[int] = None,
box: Optional[box.Box] = box.HEAVY_HEAD,
safe_box: Optional[bool] = None,
padding: PaddingDimensions = (0, 1),
collapse_padding: bool = False,
pad_edge: bool = True,
expand: bool = False,
show_header: bool = True,
show_footer: bool = False,
show_edge: bool = True,
show_lines: bool = False,
leading: int = 0,
style: StyleType = "none",
row_styles: Optional[Iterable[StyleType]] = None,
header_style: Optional[StyleType] = "table.header",
footer_style: Optional[StyleType] = "table.footer",
border_style: Optional[StyleType] = None,
title_style: Optional[StyleType] = None,
caption_style: Optional[StyleType] = None,
title_justify: "JustifyMethod" = "center",
caption_justify: "JustifyMethod" = "center",
highlight: bool = False,
) -> None:
self.columns: List[Column] = []
self.rows: List[Row] = []
self.title = title
self.caption = caption
self.width = width
self.min_width = min_width
self.box = box
self.safe_box = safe_box
self._padding = Padding.unpack(padding)
self.pad_edge = pad_edge
self._expand = expand
self.show_header = show_header
self.show_footer = show_footer
self.show_edge = show_edge
self.show_lines = show_lines
self.leading = leading
self.collapse_padding = collapse_padding
self.style = style
self.header_style = header_style or ""
self.footer_style = footer_style or ""
self.border_style = border_style
self.title_style = title_style
self.caption_style = caption_style
self.title_justify: "JustifyMethod" = title_justify
self.caption_justify: "JustifyMethod" = caption_justify
self.highlight = highlight
self.row_styles: Sequence[StyleType] = list(row_styles or [])
append_column = self.columns.append
for header in headers:
if isinstance(header, str):
self.add_column(header=header)
else:
header._index = len(self.columns)
append_column(header)
@classmethod
def grid(
cls,
*headers: Union[Column, str],
padding: PaddingDimensions = 0,
collapse_padding: bool = True,
pad_edge: bool = False,
expand: bool = False,
) -> "Table":
"""Get a table with no lines, headers, or footer.
Args:
*headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.
padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0.
collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True.
pad_edge (bool, optional): Enable padding around edges of table. Defaults to False.
expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.
Returns:
Table: A table instance.
"""
return cls(
*headers,
box=None,
padding=padding,
collapse_padding=collapse_padding,
show_header=False,
show_footer=False,
show_edge=False,
pad_edge=pad_edge,
expand=expand,
)
@property
def expand(self) -> bool:
"""Setting a non-None self.width implies expand."""
return self._expand or self.width is not None
@expand.setter
def expand(self, expand: bool) -> None:
"""Set expand."""
self._expand = expand
@property
def _extra_width(self) -> int:
"""Get extra width to add to cell content."""
width = 0
if self.box and self.show_edge:
width += 2
if self.box:
width += len(self.columns) - 1
return width
@property
def row_count(self) -> int:
"""Get the current number of rows."""
return len(self.rows)
def get_row_style(self, console: "Console", index: int) -> StyleType:
"""Get the current row style."""
style = Style.null()
if self.row_styles:
style += console.get_style(self.row_styles[index % len(self.row_styles)])
row_style = self.rows[index].style
if row_style is not None:
style += console.get_style(row_style)
return style
def __rich_measure__(
self, console: "Console", options: "ConsoleOptions"
) -> Measurement:
max_width = options.max_width
if self.width is not None:
max_width = self.width
if max_width < 0:
return Measurement(0, 0)
extra_width = self._extra_width
max_width = sum(
self._calculate_column_widths(
console, options.update_width(max_width - extra_width)
)
)
_measure_column = self._measure_column
measurements = [
_measure_column(console, options.update_width(max_width), column)
for column in self.columns
]
minimum_width = (
sum(measurement.minimum for measurement in measurements) + extra_width
)
maximum_width = (
sum(measurement.maximum for measurement in measurements) + extra_width
if (self.width is None)
else self.width
)
measurement = Measurement(minimum_width, maximum_width)
measurement = measurement.clamp(self.min_width)
return measurement
@property
def padding(self) -> Tuple[int, int, int, int]:
"""Get cell padding."""
return self._padding
@padding.setter
def padding(self, padding: PaddingDimensions) -> "Table":
"""Set cell padding."""
self._padding = Padding.unpack(padding)
return self
def add_column(
self,
header: "RenderableType" = "",
footer: "RenderableType" = "",
*,
header_style: Optional[StyleType] = None,
highlight: Optional[bool] = None,
footer_style: Optional[StyleType] = None,
style: Optional[StyleType] = None,
justify: "JustifyMethod" = "left",
vertical: "VerticalAlignMethod" = "top",
overflow: "OverflowMethod" = "ellipsis",
width: Optional[int] = None,
min_width: Optional[int] = None,
max_width: Optional[int] = None,
ratio: Optional[int] = None,
no_wrap: bool = False,
) -> None:
"""Add a column to the table.
Args:
header (RenderableType, optional): Text or renderable for the header.
Defaults to "".
footer (RenderableType, optional): Text or renderable for the footer.
Defaults to "".
header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None.
highlight (bool, optional): Whether to highlight the text. The default of None uses the value of the table (self) object.
footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None.
style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None.
justify (JustifyMethod, optional): Alignment for cells. Defaults to "left".
vertical (VerticalAlignMethod, optional): Vertical alignment, one of "top", "middle", or "bottom". Defaults to "top".
overflow (OverflowMethod): Overflow method: "crop", "fold", "ellipsis". Defaults to "ellipsis".
width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None.
min_width (Optional[int], optional): Minimum width of column, or ``None`` for no minimum. Defaults to None.
max_width (Optional[int], optional): Maximum width of column, or ``None`` for no maximum. Defaults to None.
ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None.
no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column.
"""
column = Column(
_index=len(self.columns),
header=header,
footer=footer,
header_style=header_style or "",
highlight=highlight if highlight is not None else self.highlight,
footer_style=footer_style or "",
style=style or "",
justify=justify,
vertical=vertical,
overflow=overflow,
width=width,
min_width=min_width,
max_width=max_width,
ratio=ratio,
no_wrap=no_wrap,
)
self.columns.append(column)
def add_row(
self,
*renderables: Optional["RenderableType"],
style: Optional[StyleType] = None,
end_section: bool = False,
) -> None:
"""Add a row of renderables.
Args:
*renderables (None or renderable): Each cell in a row must be a renderable object (including str),
or ``None`` for a blank cell.
style (StyleType, optional): An optional style to apply to the entire row. Defaults to None.
end_section (bool, optional): End a section and draw a line. Defaults to False.
Raises:
errors.NotRenderableError: If you add something that can't be rendered.
"""
def add_cell(column: Column, renderable: "RenderableType") -> None:
column._cells.append(renderable)
cell_renderables: List[Optional["RenderableType"]] = list(renderables)
columns = self.columns
if len(cell_renderables) < len(columns):
cell_renderables = [
*cell_renderables,
*[None] * (len(columns) - len(cell_renderables)),
]
for index, renderable in enumerate(cell_renderables):
if index == len(columns):
column = Column(_index=index, highlight=self.highlight)
for _ in self.rows:
add_cell(column, Text(""))
self.columns.append(column)
else:
column = columns[index]
if renderable is None:
add_cell(column, "")
elif is_renderable(renderable):
add_cell(column, renderable)
else:
raise errors.NotRenderableError(
f"unable to render {type(renderable).__name__}; a string or other renderable object is required"
)
self.rows.append(Row(style=style, end_section=end_section))
def add_section(self) -> None:
"""Add a new section (draw a line after current row)."""
if self.rows:
self.rows[-1].end_section = True
def __rich_console__(
self, console: "Console", options: "ConsoleOptions"
) -> "RenderResult":
if not self.columns:
yield Segment("\n")
return
max_width = options.max_width
if self.width is not None:
max_width = self.width
extra_width = self._extra_width
widths = self._calculate_column_widths(
console, options.update_width(max_width - extra_width)
)
table_width = sum(widths) + extra_width
render_options = options.update(
width=table_width, highlight=self.highlight, height=None
)
def render_annotation(
text: TextType, style: StyleType, justify: "JustifyMethod" = "center"
) -> "RenderResult":
render_text = (
console.render_str(text, style=style, highlight=False)
if isinstance(text, str)
else text
)
return console.render(
render_text, options=render_options.update(justify=justify)
)
if self.title:
yield from render_annotation(
self.title,
style=Style.pick_first(self.title_style, "table.title"),
justify=self.title_justify,
)
yield from self._render(console, render_options, widths)
if self.caption:
yield from render_annotation(
self.caption,
style=Style.pick_first(self.caption_style, "table.caption"),
justify=self.caption_justify,
)
def _calculate_column_widths(
self, console: "Console", options: "ConsoleOptions"
) -> List[int]:
"""Calculate the widths of each column, including padding, not including borders."""
max_width = options.max_width
columns = self.columns
width_ranges = [
self._measure_column(console, options, column) for column in columns
]
widths = [_range.maximum or 1 for _range in width_ranges]
get_padding_width = self._get_padding_width
extra_width = self._extra_width
if self.expand:
ratios = [col.ratio or 0 for col in columns if col.flexible]
if any(ratios):
fixed_widths = [
0 if column.flexible else _range.maximum
for _range, column in zip(width_ranges, columns)
]
flex_minimum = [
(column.width or 1) + get_padding_width(column._index)
for column in columns
if column.flexible
]
flexible_width = max_width - sum(fixed_widths)
flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum)
iter_flex_widths = iter(flex_widths)
for index, column in enumerate(columns):
if column.flexible:
widths[index] = fixed_widths[index] + next(iter_flex_widths)
table_width = sum(widths)
if table_width > max_width:
widths = self._collapse_widths(
widths,
[(column.width is None and not column.no_wrap) for column in columns],
max_width,
)
table_width = sum(widths)
# last resort, reduce columns evenly
if table_width > max_width:
excess_width = table_width - max_width
widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths)
table_width = sum(widths)
width_ranges = [
self._measure_column(console, options.update_width(width), column)
for width, column in zip(widths, columns)
]
widths = [_range.maximum or 0 for _range in width_ranges]
if (table_width < max_width and self.expand) or (
self.min_width is not None and table_width < (self.min_width - extra_width)
):
_max_width = (
max_width
if self.min_width is None
else min(self.min_width - extra_width, max_width)
)
pad_widths = ratio_distribute(_max_width - table_width, widths)
widths = [_width + pad for _width, pad in zip(widths, pad_widths)]
return widths
@classmethod
def _collapse_widths(
cls, widths: List[int], wrapable: List[bool], max_width: int
) -> List[int]:
"""Reduce widths so that the total is under max_width.
Args:
widths (List[int]): List of widths.
wrapable (List[bool]): List of booleans that indicate if a column may shrink.
max_width (int): Maximum width to reduce to.
Returns:
List[int]: A new list of widths.
"""
total_width = sum(widths)
excess_width = total_width - max_width
if any(wrapable):
while total_width and excess_width > 0:
max_column = max(
width for width, allow_wrap in zip(widths, wrapable) if allow_wrap
)
second_max_column = max(
width if allow_wrap and width != max_column else 0
for width, allow_wrap in zip(widths, wrapable)
)
column_difference = max_column - second_max_column
ratios = [
(1 if (width == max_column and allow_wrap) else 0)
for width, allow_wrap in zip(widths, wrapable)
]
if not any(ratios) or not column_difference:
break
max_reduce = [min(excess_width, column_difference)] * len(widths)
widths = ratio_reduce(excess_width, ratios, max_reduce, widths)
total_width = sum(widths)
excess_width = total_width - max_width
return widths
def _get_cells(
self, console: "Console", column_index: int, column: Column
) -> Iterable[_Cell]:
"""Get all the cells with padding and optional header."""
collapse_padding = self.collapse_padding
pad_edge = self.pad_edge
padding = self.padding
any_padding = any(padding)
first_column = column_index == 0
last_column = column_index == len(self.columns) - 1
_padding_cache: Dict[Tuple[bool, bool], Tuple[int, int, int, int]] = {}
def get_padding(first_row: bool, last_row: bool) -> Tuple[int, int, int, int]:
cached = _padding_cache.get((first_row, last_row))
if cached:
return cached
top, right, bottom, left = padding
if collapse_padding:
if not first_column:
left = max(0, left - right)
if not last_row:
bottom = max(0, top - bottom)
if not pad_edge:
if first_column:
left = 0
if last_column:
right = 0
if first_row:
top = 0
if last_row:
bottom = 0
_padding = (top, right, bottom, left)
_padding_cache[(first_row, last_row)] = _padding
return _padding
raw_cells: List[Tuple[StyleType, "RenderableType"]] = []
_append = raw_cells.append
get_style = console.get_style
if self.show_header:
header_style = get_style(self.header_style or "") + get_style(
column.header_style
)
_append((header_style, column.header))
cell_style = get_style(column.style or "")
for cell in column.cells:
_append((cell_style, cell))
if self.show_footer:
footer_style = get_style(self.footer_style or "") + get_style(
column.footer_style
)
_append((footer_style, column.footer))
if any_padding:
_Padding = Padding
for first, last, (style, renderable) in loop_first_last(raw_cells):
yield _Cell(
style,
_Padding(renderable, get_padding(first, last)),
getattr(renderable, "vertical", None) or column.vertical,
)
else:
for style, renderable in raw_cells:
yield _Cell(
style,
renderable,
getattr(renderable, "vertical", None) or column.vertical,
)
def _get_padding_width(self, column_index: int) -> int:
"""Get extra width from padding."""
_, pad_right, _, pad_left = self.padding
if self.collapse_padding:
if column_index > 0:
pad_left = max(0, pad_left - pad_right)
return pad_left + pad_right
def _measure_column(
self,
console: "Console",
options: "ConsoleOptions",
column: Column,
) -> Measurement:
"""Get the minimum and maximum width of the column."""
max_width = options.max_width
if max_width < 1:
return Measurement(0, 0)
padding_width = self._get_padding_width(column._index)
if column.width is not None:
# Fixed width column
return Measurement(
column.width + padding_width, column.width + padding_width
).with_maximum(max_width)
# Flexible column, we need to measure contents
min_widths: List[int] = []
max_widths: List[int] = []
append_min = min_widths.append
append_max = max_widths.append
get_render_width = Measurement.get
for cell in self._get_cells(console, column._index, column):
_min, _max = get_render_width(console, options, cell.renderable)
append_min(_min)
append_max(_max)
measurement = Measurement(
max(min_widths) if min_widths else 1,
max(max_widths) if max_widths else max_width,
).with_maximum(max_width)
measurement = measurement.clamp(
None if column.min_width is None else column.min_width + padding_width,
None if column.max_width is None else column.max_width + padding_width,
)
return measurement
def _render(
self, console: "Console", options: "ConsoleOptions", widths: List[int]
) -> "RenderResult":
table_style = console.get_style(self.style or "")
border_style = table_style + console.get_style(self.border_style or "")
_column_cells = (
self._get_cells(console, column_index, column)
for column_index, column in enumerate(self.columns)
)
row_cells: List[Tuple[_Cell, ...]] = list(zip(*_column_cells))
_box = (
self.box.substitute(
options, safe=pick_bool(self.safe_box, console.safe_box)
)
if self.box
else None
)
_box = _box.get_plain_headed_box() if _box and not self.show_header else _box
new_line = Segment.line()
columns = self.columns
show_header = self.show_header
show_footer = self.show_footer
show_edge = self.show_edge
show_lines = self.show_lines
leading = self.leading
_Segment = Segment
if _box:
box_segments = [
(
_Segment(_box.head_left, border_style),
_Segment(_box.head_right, border_style),
_Segment(_box.head_vertical, border_style),
),
(
_Segment(_box.mid_left, border_style),
_Segment(_box.mid_right, border_style),
_Segment(_box.mid_vertical, border_style),
),
(
_Segment(_box.foot_left, border_style),
_Segment(_box.foot_right, border_style),
_Segment(_box.foot_vertical, border_style),
),
]
if show_edge:
yield _Segment(_box.get_top(widths), border_style)
yield new_line
else:
box_segments = []
get_row_style = self.get_row_style
get_style = console.get_style
for index, (first, last, row_cell) in enumerate(loop_first_last(row_cells)):
header_row = first and show_header
footer_row = last and show_footer
row = (
self.rows[index - show_header]
if (not header_row and not footer_row)
else None
)
max_height = 1
cells: List[List[List[Segment]]] = []
if header_row or footer_row:
row_style = Style.null()
else:
row_style = get_style(
get_row_style(console, index - 1 if show_header else index)
)
for width, cell, column in zip(widths, row_cell, columns):
render_options = options.update(
width=width,
justify=column.justify,
no_wrap=column.no_wrap,
overflow=column.overflow,
height=None,
highlight=column.highlight,
)
lines = console.render_lines(
cell.renderable,
render_options,
style=get_style(cell.style) + row_style,
)
max_height = max(max_height, len(lines))
cells.append(lines)
row_height = max(len(cell) for cell in cells)
def align_cell(
cell: List[List[Segment]],
vertical: "VerticalAlignMethod",
width: int,
style: Style,
) -> List[List[Segment]]:
if header_row:
vertical = "bottom"
elif footer_row:
vertical = "top"
if vertical == "top":
return _Segment.align_top(cell, width, row_height, style)
elif vertical == "middle":
return _Segment.align_middle(cell, width, row_height, style)
return _Segment.align_bottom(cell, width, row_height, style)
cells[:] = [
_Segment.set_shape(
align_cell(
cell,
_cell.vertical,
width,
get_style(_cell.style) + row_style,
),
width,
max_height,
)
for width, _cell, cell, column in zip(widths, row_cell, cells, columns)
]
if _box:
if last and show_footer:
yield _Segment(
_box.get_row(widths, "foot", edge=show_edge), border_style
)
yield new_line
left, right, _divider = box_segments[0 if first else (2 if last else 1)]
# If the column divider is whitespace also style it with the row background
divider = (
_divider
if _divider.text.strip()
else _Segment(
_divider.text, row_style.background_style + _divider.style
)
)
for line_no in range(max_height):
if show_edge:
yield left
for last_cell, rendered_cell in loop_last(cells):
yield from rendered_cell[line_no]
if not last_cell:
yield divider
if show_edge:
yield right
yield new_line
else:
for line_no in range(max_height):
for rendered_cell in cells:
yield from rendered_cell[line_no]
yield new_line
if _box and first and show_header:
yield _Segment(
_box.get_row(widths, "head", edge=show_edge), border_style
)
yield new_line
end_section = row and row.end_section
if _box and (show_lines or leading or end_section):
if (
not last
and not (show_footer and index >= len(row_cells) - 2)
and not (show_header and header_row)
):
if leading:
yield _Segment(
_box.get_row(widths, "mid", edge=show_edge) * leading,
border_style,
)
else:
yield _Segment(
_box.get_row(widths, "row", edge=show_edge), border_style
)
yield new_line
if _box and show_edge:
yield _Segment(_box.get_bottom(widths), border_style)
yield new_line
if __name__ == "__main__": # pragma: no cover
from rich.console import Console
from rich.highlighter import ReprHighlighter
from ._timer import timer
with timer("Table render"):
table = Table(
title="Star Wars Movies",
caption="Rich example table",
caption_justify="right",
)
table.add_column(
"Released", header_style="bright_cyan", style="cyan", no_wrap=True
)
table.add_column("Title", style="magenta")
table.add_column("Box Office", justify="right", style="green")
table.add_row(
"Dec 20, 2019",
"Star Wars: The Rise of Skywalker",
"$952,110,690",
)
table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347")
table.add_row(
"Dec 15, 2017",
"Star Wars Ep. V111: The Last Jedi",
"$1,332,539,889",
style="on black",
end_section=True,
)
table.add_row(
"Dec 16, 2016",
"Rogue One: A Star Wars Story",
"$1,332,439,889",
)
def header(text: str) -> None:
console.print()
console.rule(highlight(text))
console.print()
console = Console()
highlight = ReprHighlighter()
header("Example Table")
console.print(table, justify="center")
table.expand = True
header("expand=True")
console.print(table)
table.width = 50
header("width=50")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
header("row_styles=['dim', 'none']")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
table.leading = 1
header("leading=1, row_styles=['dim', 'none']")
console.print(table, justify="center")
table.width = None
table.expand = False
table.row_styles = ["dim", "none"]
table.show_lines = True
table.leading = 0
header("show_lines=True, row_styles=['dim', 'none']")
console.print(table, justify="center")
|
Table
|
python
|
html5lib__html5lib-python
|
html5lib/tests/tokenizer.py
|
{
"start": 246,
"end": 6373
}
|
class ____(object):
def __init__(self, initialState, lastStartTag=None):
self.tokenizer = HTMLTokenizer
self._state = initialState
self._lastStartTag = lastStartTag
def parse(self, stream, encoding=None, innerHTML=False):
# pylint:disable=unused-argument
tokenizer = self.tokenizer(stream, encoding)
self.outputTokens = []
tokenizer.state = getattr(tokenizer, self._state)
if self._lastStartTag is not None:
tokenizer.currentToken = {"type": "startTag",
"name": self._lastStartTag}
types = {v: k for k, v in constants.tokenTypes.items()}
for token in tokenizer:
getattr(self, 'process%s' % types[token["type"]])(token)
return self.outputTokens
def processDoctype(self, token):
self.outputTokens.append(["DOCTYPE", token["name"], token["publicId"],
token["systemId"], token["correct"]])
def processStartTag(self, token):
self.outputTokens.append(["StartTag", token["name"],
token["data"], token["selfClosing"]])
def processEmptyTag(self, token):
if token["name"] not in constants.voidElements:
self.outputTokens.append("ParseError")
self.outputTokens.append(["StartTag", token["name"], dict(token["data"][::-1])])
def processEndTag(self, token):
self.outputTokens.append(["EndTag", token["name"],
token["selfClosing"]])
def processComment(self, token):
self.outputTokens.append(["Comment", token["data"]])
def processSpaceCharacters(self, token):
self.outputTokens.append(["Character", token["data"]])
self.processSpaceCharacters = self.processCharacters
def processCharacters(self, token):
self.outputTokens.append(["Character", token["data"]])
def processEOF(self, token):
pass
def processParseError(self, token):
self.outputTokens.append(["ParseError", token["data"]])
def concatenateCharacterTokens(tokens):
outputTokens = []
for token in tokens:
if "ParseError" not in token and token[0] == "Character":
if (outputTokens and "ParseError" not in outputTokens[-1] and
outputTokens[-1][0] == "Character"):
outputTokens[-1][1] += token[1]
else:
outputTokens.append(token)
else:
outputTokens.append(token)
return outputTokens
def normalizeTokens(tokens):
# TODO: convert tests to reflect arrays
for i, token in enumerate(tokens):
if token[0] == 'ParseError':
tokens[i] = token[0]
return tokens
def tokensMatch(expectedTokens, receivedTokens, ignoreErrorOrder,
ignoreErrors=False):
"""Test whether the test has passed or failed
If the ignoreErrorOrder flag is set to true we don't test the relative
positions of parse errors and non parse errors
"""
checkSelfClosing = False
for token in expectedTokens:
if (token[0] == "StartTag" and len(token) == 4 or
token[0] == "EndTag" and len(token) == 3):
checkSelfClosing = True
break
if not checkSelfClosing:
for token in receivedTokens:
if token[0] == "StartTag" or token[0] == "EndTag":
token.pop()
if not ignoreErrorOrder and not ignoreErrors:
expectedTokens = concatenateCharacterTokens(expectedTokens)
return expectedTokens == receivedTokens
else:
# Sort the tokens into two groups; non-parse errors and parse errors
tokens = {"expected": [[], []], "received": [[], []]}
for tokenType, tokenList in zip(list(tokens.keys()),
(expectedTokens, receivedTokens)):
for token in tokenList:
if token != "ParseError":
tokens[tokenType][0].append(token)
else:
if not ignoreErrors:
tokens[tokenType][1].append(token)
tokens[tokenType][0] = concatenateCharacterTokens(tokens[tokenType][0])
return tokens["expected"] == tokens["received"]
_surrogateRe = re.compile(r"\\u([0-9A-Fa-f]{4})(?:\\u([0-9A-Fa-f]{4}))?")
def unescape(test):
def decode(inp):
"""Decode \\uXXXX escapes
This decodes \\uXXXX escapes, possibly into non-BMP characters when
two surrogate character escapes are adjacent to each other.
"""
# This cannot be implemented using the unicode_escape codec
# because that requires its input be ISO-8859-1, and we need
# arbitrary unicode as input.
def repl(m):
if m.group(2) is not None:
high = int(m.group(1), 16)
low = int(m.group(2), 16)
if 0xD800 <= high <= 0xDBFF and 0xDC00 <= low <= 0xDFFF:
cp = ((high - 0xD800) << 10) + (low - 0xDC00) + 0x10000
return unichr(cp)
else:
return unichr(high) + unichr(low)
else:
return unichr(int(m.group(1), 16))
try:
return _surrogateRe.sub(repl, inp)
except ValueError:
# This occurs when unichr throws ValueError, which should
# only be for a lone-surrogate.
if _utils.supports_lone_surrogates:
raise
return None
test["input"] = decode(test["input"])
for token in test["output"]:
if token == "ParseError":
continue
else:
token[1] = decode(token[1])
if len(token) > 2:
for key, value in token[2]:
del token[2][key]
token[2][decode(key)] = decode(value)
return test
def _doCapitalize(match):
return match.group(1).upper()
_capitalizeRe = re.compile(r"\W+(\w)").sub
def capitalize(s):
s = s.lower()
s = _capitalizeRe(_doCapitalize, s)
return s
|
TokenizerTestParser
|
python
|
numba__numba
|
numba/cuda/tests/cudapy/test_cuda_array_interface.py
|
{
"start": 449,
"end": 15844
}
|
class ____(ContextResettingTestCase):
def assertPointersEqual(self, a, b):
if driver.USE_NV_BINDING:
self.assertEqual(int(a.device_ctypes_pointer),
int(b.device_ctypes_pointer))
def test_as_cuda_array(self):
h_arr = np.arange(10)
self.assertFalse(cuda.is_cuda_array(h_arr))
d_arr = cuda.to_device(h_arr)
self.assertTrue(cuda.is_cuda_array(d_arr))
my_arr = ForeignArray(d_arr)
self.assertTrue(cuda.is_cuda_array(my_arr))
wrapped = cuda.as_cuda_array(my_arr)
self.assertTrue(cuda.is_cuda_array(wrapped))
# Their values must equal the original array
np.testing.assert_array_equal(wrapped.copy_to_host(), h_arr)
np.testing.assert_array_equal(d_arr.copy_to_host(), h_arr)
# d_arr and wrapped must be the same buffer
self.assertPointersEqual(wrapped, d_arr)
def get_stream_value(self, stream):
if driver.USE_NV_BINDING:
return int(stream.handle)
else:
return stream.handle.value
@skip_if_external_memmgr('Ownership not relevant with external memmgr')
def test_ownership(self):
# Get the deallocation queue
ctx = cuda.current_context()
deallocs = ctx.memory_manager.deallocations
# Flush all deallocations
deallocs.clear()
self.assertEqual(len(deallocs), 0)
# Make new device array
d_arr = cuda.to_device(np.arange(100))
# Convert it
cvted = cuda.as_cuda_array(d_arr)
# Drop reference to the original object such that
# only `cvted` has a reference to it.
del d_arr
# There shouldn't be any new deallocations
self.assertEqual(len(deallocs), 0)
# Try to access the memory and verify its content
np.testing.assert_equal(cvted.copy_to_host(), np.arange(100))
# Drop last reference to the memory
del cvted
self.assertEqual(len(deallocs), 1)
# Flush
deallocs.clear()
def test_kernel_arg(self):
h_arr = np.arange(10)
d_arr = cuda.to_device(h_arr)
my_arr = ForeignArray(d_arr)
wrapped = cuda.as_cuda_array(my_arr)
@cuda.jit
def mutate(arr, val):
i = cuda.grid(1)
if i >= len(arr):
return
arr[i] += val
val = 7
mutate.forall(wrapped.size)(wrapped, val)
np.testing.assert_array_equal(wrapped.copy_to_host(), h_arr + val)
np.testing.assert_array_equal(d_arr.copy_to_host(), h_arr + val)
def test_ufunc_arg(self):
@vectorize(['f8(f8, f8)'], target='cuda')
def vadd(a, b):
return a + b
# Case 1: use custom array as argument
h_arr = np.random.random(10)
arr = ForeignArray(cuda.to_device(h_arr))
val = 6
out = vadd(arr, val)
np.testing.assert_array_equal(out.copy_to_host(), h_arr + val)
# Case 2: use custom array as return
out = ForeignArray(cuda.device_array(h_arr.shape))
returned = vadd(h_arr, val, out=out)
np.testing.assert_array_equal(returned.copy_to_host(), h_arr + val)
def test_gufunc_arg(self):
@guvectorize(['(f8, f8, f8[:])'], '(),()->()', target='cuda')
def vadd(inp, val, out):
out[0] = inp + val
# Case 1: use custom array as argument
h_arr = np.random.random(10)
arr = ForeignArray(cuda.to_device(h_arr))
val = np.float64(7)
out = vadd(arr, val)
np.testing.assert_array_equal(out.copy_to_host(), h_arr + val)
# Case 2: use custom array as return
out = ForeignArray(cuda.device_array(h_arr.shape))
returned = vadd(h_arr, val, out=out)
np.testing.assert_array_equal(returned.copy_to_host(), h_arr + val)
self.assertPointersEqual(returned, out._arr)
def test_array_views(self):
"""Views created via array interface support:
- Strided slices
- Strided slices
"""
h_arr = np.random.random(10)
c_arr = cuda.to_device(h_arr)
arr = cuda.as_cuda_array(c_arr)
# __getitem__ interface accesses expected data
# Direct views
np.testing.assert_array_equal(arr.copy_to_host(), h_arr)
np.testing.assert_array_equal(arr[:].copy_to_host(), h_arr)
# Slicing
np.testing.assert_array_equal(arr[:5].copy_to_host(), h_arr[:5])
# Strided view
np.testing.assert_array_equal(arr[::2].copy_to_host(), h_arr[::2])
# View of strided array
arr_strided = cuda.as_cuda_array(c_arr[::2])
np.testing.assert_array_equal(arr_strided.copy_to_host(), h_arr[::2])
# A strided-view-of-array and view-of-strided-array have the same
# shape, strides, itemsize, and alloc_size
self.assertEqual(arr[::2].shape, arr_strided.shape)
self.assertEqual(arr[::2].strides, arr_strided.strides)
self.assertEqual(arr[::2].dtype.itemsize, arr_strided.dtype.itemsize)
self.assertEqual(arr[::2].alloc_size, arr_strided.alloc_size)
self.assertEqual(arr[::2].nbytes,
arr_strided.size * arr_strided.dtype.itemsize)
# __setitem__ interface propagates into external array
# Writes to a slice
arr[:5] = np.pi
np.testing.assert_array_equal(
c_arr.copy_to_host(),
np.concatenate((np.full(5, np.pi), h_arr[5:]))
)
# Writes to a slice from a view
arr[:5] = arr[5:]
np.testing.assert_array_equal(
c_arr.copy_to_host(),
np.concatenate((h_arr[5:], h_arr[5:]))
)
# Writes through a view
arr[:] = cuda.to_device(h_arr)
np.testing.assert_array_equal(c_arr.copy_to_host(), h_arr)
# Writes to a strided slice
arr[::2] = np.pi
np.testing.assert_array_equal(
c_arr.copy_to_host()[::2],
np.full(5, np.pi),
)
np.testing.assert_array_equal(
c_arr.copy_to_host()[1::2],
h_arr[1::2]
)
def test_negative_strided_issue(self):
# issue #3705
h_arr = np.random.random(10)
c_arr = cuda.to_device(h_arr)
def base_offset(orig, sliced):
return sliced['data'][0] - orig['data'][0]
h_ai = h_arr.__array_interface__
c_ai = c_arr.__cuda_array_interface__
h_ai_sliced = h_arr[::-1].__array_interface__
c_ai_sliced = c_arr[::-1].__cuda_array_interface__
# Check data offset is correct
self.assertEqual(
base_offset(h_ai, h_ai_sliced),
base_offset(c_ai, c_ai_sliced),
)
# Check shape and strides are correct
self.assertEqual(h_ai_sliced['shape'], c_ai_sliced['shape'])
self.assertEqual(h_ai_sliced['strides'], c_ai_sliced['strides'])
def test_negative_strided_copy_to_host(self):
# issue #3705
h_arr = np.random.random(10)
c_arr = cuda.to_device(h_arr)
sliced = c_arr[::-1]
with self.assertRaises(NotImplementedError) as raises:
sliced.copy_to_host()
expected_msg = 'D->H copy not implemented for negative strides'
self.assertIn(expected_msg, str(raises.exception))
def test_masked_array(self):
h_arr = np.random.random(10)
h_mask = np.random.randint(2, size=10, dtype='bool')
c_arr = cuda.to_device(h_arr)
c_mask = cuda.to_device(h_mask)
# Manually create a masked CUDA Array Interface dictionary
masked_cuda_array_interface = c_arr.__cuda_array_interface__.copy()
masked_cuda_array_interface['mask'] = c_mask
with self.assertRaises(NotImplementedError) as raises:
cuda.from_cuda_array_interface(masked_cuda_array_interface)
expected_msg = 'Masked arrays are not supported'
self.assertIn(expected_msg, str(raises.exception))
def test_zero_size_array(self):
# for #4175
c_arr = cuda.device_array(0)
self.assertEqual(c_arr.__cuda_array_interface__['data'][0], 0)
@cuda.jit
def add_one(arr):
x = cuda.grid(1)
N = arr.shape[0]
if x < N:
arr[x] += 1
d_arr = ForeignArray(c_arr)
add_one[1, 10](d_arr) # this should pass
def test_strides(self):
# for #4175
# First, test C-contiguous array
c_arr = cuda.device_array((2, 3, 4))
self.assertEqual(c_arr.__cuda_array_interface__['strides'], None)
# Second, test non C-contiguous array
c_arr = c_arr[:, 1, :]
self.assertNotEqual(c_arr.__cuda_array_interface__['strides'], None)
def test_consuming_strides(self):
hostarray = np.arange(10).reshape(2, 5)
devarray = cuda.to_device(hostarray)
face = devarray.__cuda_array_interface__
self.assertIsNone(face['strides'])
got = cuda.from_cuda_array_interface(face).copy_to_host()
np.testing.assert_array_equal(got, hostarray)
self.assertTrue(got.flags['C_CONTIGUOUS'])
# Try non-NULL strides
face['strides'] = hostarray.strides
self.assertIsNotNone(face['strides'])
got = cuda.from_cuda_array_interface(face).copy_to_host()
np.testing.assert_array_equal(got, hostarray)
self.assertTrue(got.flags['C_CONTIGUOUS'])
def test_produce_no_stream(self):
c_arr = cuda.device_array(10)
self.assertIsNone(c_arr.__cuda_array_interface__['stream'])
mapped_arr = cuda.mapped_array(10)
self.assertIsNone(mapped_arr.__cuda_array_interface__['stream'])
@linux_only
def test_produce_managed_no_stream(self):
managed_arr = cuda.managed_array(10)
self.assertIsNone(managed_arr.__cuda_array_interface__['stream'])
def test_produce_stream(self):
s = cuda.stream()
c_arr = cuda.device_array(10, stream=s)
cai_stream = c_arr.__cuda_array_interface__['stream']
stream_value = self.get_stream_value(s)
self.assertEqual(stream_value, cai_stream)
s = cuda.stream()
mapped_arr = cuda.mapped_array(10, stream=s)
cai_stream = mapped_arr.__cuda_array_interface__['stream']
stream_value = self.get_stream_value(s)
self.assertEqual(stream_value, cai_stream)
@linux_only
def test_produce_managed_stream(self):
s = cuda.stream()
managed_arr = cuda.managed_array(10, stream=s)
cai_stream = managed_arr.__cuda_array_interface__['stream']
stream_value = self.get_stream_value(s)
self.assertEqual(stream_value, cai_stream)
def test_consume_no_stream(self):
# Create a foreign array with no stream
f_arr = ForeignArray(cuda.device_array(10))
# Ensure that the imported array has no default stream
c_arr = cuda.as_cuda_array(f_arr)
self.assertEqual(c_arr.stream, 0)
def test_consume_stream(self):
# Create a foreign array with a stream
s = cuda.stream()
f_arr = ForeignArray(cuda.device_array(10, stream=s))
# Ensure that an imported array has the stream as its default stream
c_arr = cuda.as_cuda_array(f_arr)
self.assertTrue(c_arr.stream.external)
stream_value = self.get_stream_value(s)
imported_stream_value = self.get_stream_value(c_arr.stream)
self.assertEqual(stream_value, imported_stream_value)
def test_consume_no_sync(self):
# Create a foreign array with no stream
f_arr = ForeignArray(cuda.device_array(10))
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
cuda.as_cuda_array(f_arr)
# Ensure the synchronize method of a stream was not called
mock_sync.assert_not_called()
def test_consume_sync(self):
# Create a foreign array with a stream
s = cuda.stream()
f_arr = ForeignArray(cuda.device_array(10, stream=s))
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
cuda.as_cuda_array(f_arr)
# Ensure the synchronize method of a stream was called
mock_sync.assert_called_once_with()
def test_consume_sync_disabled(self):
# Create a foreign array with a stream
s = cuda.stream()
f_arr = ForeignArray(cuda.device_array(10, stream=s))
# Set sync to false before testing. The test suite should generally be
# run with sync enabled, but stash the old value just in case it is
# not.
with override_config('CUDA_ARRAY_INTERFACE_SYNC', False):
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
cuda.as_cuda_array(f_arr)
# Ensure the synchronize method of a stream was not called
mock_sync.assert_not_called()
def test_launch_no_sync(self):
# Create a foreign array with no stream
f_arr = ForeignArray(cuda.device_array(10))
@cuda.jit
def f(x):
pass
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
f[1, 1](f_arr)
# Ensure the synchronize method of a stream was not called
mock_sync.assert_not_called()
def test_launch_sync(self):
# Create a foreign array with a stream
s = cuda.stream()
f_arr = ForeignArray(cuda.device_array(10, stream=s))
@cuda.jit
def f(x):
pass
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
f[1, 1](f_arr)
# Ensure the synchronize method of a stream was called
mock_sync.assert_called_once_with()
def test_launch_sync_two_streams(self):
# Create two foreign arrays with streams
s1 = cuda.stream()
s2 = cuda.stream()
f_arr1 = ForeignArray(cuda.device_array(10, stream=s1))
f_arr2 = ForeignArray(cuda.device_array(10, stream=s2))
@cuda.jit
def f(x, y):
pass
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
f[1, 1](f_arr1, f_arr2)
# Ensure that synchronize was called twice
mock_sync.assert_has_calls([call(), call()])
def test_launch_sync_disabled(self):
# Create two foreign arrays with streams
s1 = cuda.stream()
s2 = cuda.stream()
f_arr1 = ForeignArray(cuda.device_array(10, stream=s1))
f_arr2 = ForeignArray(cuda.device_array(10, stream=s2))
with override_config('CUDA_ARRAY_INTERFACE_SYNC', False):
@cuda.jit
def f(x, y):
pass
with patch.object(cuda.cudadrv.driver.Stream, 'synchronize',
return_value=None) as mock_sync:
f[1, 1](f_arr1, f_arr2)
# Ensure that synchronize was not called
mock_sync.assert_not_called()
if __name__ == "__main__":
unittest.main()
|
TestCudaArrayInterface
|
python
|
huggingface__transformers
|
src/transformers/models/lxmert/modeling_lxmert.py
|
{
"start": 23334,
"end": 26673
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
# Obj-level image embedding layer
self.visn_fc = LxmertVisualFeatureEncoder(config)
self.config = config
# Number of layers
self.num_l_layers = config.l_layers
self.num_x_layers = config.x_layers
self.num_r_layers = config.r_layers
# Layers
# Using self.layer instead of self.l_layer to support loading BERT weights.
self.layer = nn.ModuleList([LxmertLayer(config) for _ in range(self.num_l_layers)])
self.x_layers = nn.ModuleList([LxmertXLayer(config) for _ in range(self.num_x_layers)])
self.r_layers = nn.ModuleList([LxmertLayer(config) for _ in range(self.num_r_layers)])
def forward(
self,
lang_feats,
lang_attention_mask,
visual_feats,
visual_pos,
visual_attention_mask=None,
output_attentions=None,
):
vision_hidden_states = ()
language_hidden_states = ()
vision_attentions = () if output_attentions or self.config.output_attentions else None
language_attentions = () if output_attentions or self.config.output_attentions else None
cross_encoder_attentions = () if output_attentions or self.config.output_attentions else None
visual_feats = self.visn_fc(visual_feats, visual_pos)
# Run language layers
for layer_module in self.layer:
l_outputs = layer_module(lang_feats, lang_attention_mask, output_attentions=output_attentions)
lang_feats = l_outputs[0]
language_hidden_states = language_hidden_states + (lang_feats,)
if language_attentions is not None:
language_attentions = language_attentions + (l_outputs[1],)
# Run relational layers
for layer_module in self.r_layers:
v_outputs = layer_module(visual_feats, visual_attention_mask, output_attentions=output_attentions)
visual_feats = v_outputs[0]
vision_hidden_states = vision_hidden_states + (visual_feats,)
if vision_attentions is not None:
vision_attentions = vision_attentions + (v_outputs[1],)
# Run cross-modality layers
for layer_module in self.x_layers:
x_outputs = layer_module(
lang_feats,
lang_attention_mask,
visual_feats,
visual_attention_mask,
output_attentions=output_attentions,
)
lang_feats, visual_feats = x_outputs[:2]
vision_hidden_states = vision_hidden_states + (visual_feats,)
language_hidden_states = language_hidden_states + (lang_feats,)
if cross_encoder_attentions is not None:
cross_encoder_attentions = cross_encoder_attentions + (x_outputs[2],)
visual_encoder_outputs = (
vision_hidden_states,
vision_attentions if output_attentions else None,
)
lang_encoder_outputs = (
language_hidden_states,
language_attentions if output_attentions else None,
)
return (
visual_encoder_outputs,
lang_encoder_outputs,
cross_encoder_attentions if output_attentions else None,
)
|
LxmertEncoder
|
python
|
plotly__plotly.py
|
plotly/graph_objs/surface/contours/_x.py
|
{
"start": 233,
"end": 9979
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "surface.contours"
_path_str = "surface.contours.x"
_valid_props = {
"color",
"end",
"highlight",
"highlightcolor",
"highlightwidth",
"project",
"show",
"size",
"start",
"usecolormap",
"width",
}
@property
def color(self):
"""
Sets the color of the contour lines.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def end(self):
"""
Sets the end contour level value. Must be more than
`contours.start`
The 'end' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["end"]
@end.setter
def end(self, val):
self["end"] = val
@property
def highlight(self):
"""
Determines whether or not contour lines about the x dimension
are highlighted on hover.
The 'highlight' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["highlight"]
@highlight.setter
def highlight(self, val):
self["highlight"] = val
@property
def highlightcolor(self):
"""
Sets the color of the highlighted contour lines.
The 'highlightcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["highlightcolor"]
@highlightcolor.setter
def highlightcolor(self, val):
self["highlightcolor"] = val
@property
def highlightwidth(self):
"""
Sets the width of the highlighted contour lines.
The 'highlightwidth' property is a number and may be specified as:
- An int or float in the interval [1, 16]
Returns
-------
int|float
"""
return self["highlightwidth"]
@highlightwidth.setter
def highlightwidth(self, val):
self["highlightwidth"] = val
@property
def project(self):
"""
The 'project' property is an instance of Project
that may be specified as:
- An instance of :class:`plotly.graph_objs.surface.contours.x.Project`
- A dict of string/value properties that will be passed
to the Project constructor
Returns
-------
plotly.graph_objs.surface.contours.x.Project
"""
return self["project"]
@project.setter
def project(self, val):
self["project"] = val
@property
def show(self):
"""
Determines whether or not contour lines about the x dimension
are drawn.
The 'show' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["show"]
@show.setter
def show(self, val):
self["show"] = val
@property
def size(self):
"""
Sets the step between each contour level. Must be positive.
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def start(self):
"""
Sets the starting contour level value. Must be less than
`contours.end`
The 'start' property is a number and may be specified as:
- An int or float
Returns
-------
int|float
"""
return self["start"]
@start.setter
def start(self, val):
self["start"] = val
@property
def usecolormap(self):
"""
An alternate to "color". Determines whether or not the contour
lines are colored using the trace "colorscale".
The 'usecolormap' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["usecolormap"]
@usecolormap.setter
def usecolormap(self, val):
self["usecolormap"] = val
@property
def width(self):
"""
Sets the width of the contour lines.
The 'width' property is a number and may be specified as:
- An int or float in the interval [1, 16]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the color of the contour lines.
end
Sets the end contour level value. Must be more than
`contours.start`
highlight
Determines whether or not contour lines about the x
dimension are highlighted on hover.
highlightcolor
Sets the color of the highlighted contour lines.
highlightwidth
Sets the width of the highlighted contour lines.
project
:class:`plotly.graph_objects.surface.contours.x.Project
` instance or dict with compatible properties
show
Determines whether or not contour lines about the x
dimension are drawn.
size
Sets the step between each contour level. Must be
positive.
start
Sets the starting contour level value. Must be less
than `contours.end`
usecolormap
An alternate to "color". Determines whether or not the
contour lines are colored using the trace "colorscale".
width
Sets the width of the contour lines.
"""
def __init__(
self,
arg=None,
color=None,
end=None,
highlight=None,
highlightcolor=None,
highlightwidth=None,
project=None,
show=None,
size=None,
start=None,
usecolormap=None,
width=None,
**kwargs,
):
"""
Construct a new X object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.surface.contours.X`
color
Sets the color of the contour lines.
end
Sets the end contour level value. Must be more than
`contours.start`
highlight
Determines whether or not contour lines about the x
dimension are highlighted on hover.
highlightcolor
Sets the color of the highlighted contour lines.
highlightwidth
Sets the width of the highlighted contour lines.
project
:class:`plotly.graph_objects.surface.contours.x.Project
` instance or dict with compatible properties
show
Determines whether or not contour lines about the x
dimension are drawn.
size
Sets the step between each contour level. Must be
positive.
start
Sets the starting contour level value. Must be less
than `contours.end`
usecolormap
An alternate to "color". Determines whether or not the
contour lines are colored using the trace "colorscale".
width
Sets the width of the contour lines.
Returns
-------
X
"""
super().__init__("x")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.surface.contours.X
constructor must be a dict or
an instance of :class:`plotly.graph_objs.surface.contours.X`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("end", arg, end)
self._set_property("highlight", arg, highlight)
self._set_property("highlightcolor", arg, highlightcolor)
self._set_property("highlightwidth", arg, highlightwidth)
self._set_property("project", arg, project)
self._set_property("show", arg, show)
self._set_property("size", arg, size)
self._set_property("start", arg, start)
self._set_property("usecolormap", arg, usecolormap)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
X
|
python
|
wandb__wandb
|
landfill/functional_tests/lightning_fabric/pl_base.py
|
{
"start": 115,
"end": 387
}
|
class ____(Dataset):
def __init__(self, size, num_samples):
self.len = num_samples
self.data = torch.randn(num_samples, size)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.len
|
RandomDataset
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.