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 | fluentpython__example-code-2e | 19-concurrency/primes/sequential.py | {
"start": 242,
"end": 819
} | class ____(NamedTuple): # <1>
prime: bool
elapsed: float
def check(n: int) -> Result: # <2>
t0 = perf_counter()
prime = is_prime(n)
return Result(prime, perf_counter() - t0)
def main() -> None:
print(f'Checking {len(NUMBERS)} numbers sequentially:')
t0 = perf_counter()
for n in NUMBERS: # <3>
prime, elapsed = check(n)
label = 'P' if prime else ' '
print(f'{n:16} {label} {elapsed:9.6f}s')
elapsed = perf_counter() - t0 # <4>
print(f'Total time: {elapsed:.2f}s')
if __name__ == '__main__':
main()
| Result |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/redshift/resources.py | {
"start": 13221,
"end": 15795
} | class ____(ConfigurableResource):
"""This resource enables connecting to a Redshift cluster and issuing queries against that
cluster.
Example:
.. code-block:: python
from dagster import Definitions, asset, EnvVar
from dagster_aws.redshift import RedshiftClientResource
@asset
def example_redshift_asset(context, redshift: RedshiftClientResource):
redshift.get_client().execute_query('SELECT 1', fetch_results=True)
redshift_configured = RedshiftClientResource(
host='my-redshift-cluster.us-east-1.redshift.amazonaws.com',
port=5439,
user='dagster',
password=EnvVar("DAGSTER_REDSHIFT_PASSWORD"),
database='dev',
)
Definitions(
assets=[example_redshift_asset],
resources={'redshift': redshift_configured},
)
"""
host: str = Field(description="Redshift host")
port: int = Field(default=5439, description="Redshift port")
user: Optional[str] = Field(default=None, description="Username for Redshift connection")
password: Optional[str] = Field(default=None, description="Password for Redshift connection")
database: Optional[str] = Field(
default=None,
description=(
"Name of the default database to use. After login, you can use USE DATABASE to change"
" the database."
),
)
autocommit: Optional[bool] = Field(default=None, description="Whether to autocommit queries")
connect_timeout: int = Field(
default=5, description="Timeout for connection to Redshift cluster. Defaults to 5 seconds."
)
sslmode: str = Field(
default="require",
description=(
"SSL mode to use. See the Redshift documentation for reference:"
" https://docs.aws.amazon.com/redshift/latest/mgmt/connecting-ssl-support.html"
),
)
@classmethod
def _is_dagster_maintained(cls) -> bool:
return True
def get_client(self) -> RedshiftClient:
conn_args = {
k: getattr(self, k, None)
for k in (
"host",
"port",
"user",
"password",
"database",
"connect_timeout",
"sslmode",
)
if getattr(self, k, None) is not None
}
return RedshiftClient(conn_args, self.autocommit, get_dagster_logger())
| RedshiftClientResource |
python | getsentry__sentry | src/sentry/core/endpoints/organization_projects_experiment.py | {
"start": 2274,
"end": 2401
} | class ____(TypedDict):
request: Request
organization: Organization
target_object: int
@region_silo_endpoint
| AuditData |
python | apache__airflow | dev/breeze/src/airflow_breeze/prepare_providers/provider_documentation.py | {
"start": 5278,
"end": 5399
} | class ____(Exception):
"""Raised when package has only documentation changes."""
| PrepareReleaseDocsChangesOnlyException |
python | python__mypy | mypy/test/teststubgen.py | {
"start": 26754,
"end": 28594
} | class ____(unittest.TestCase):
def test_is_blacklisted_path(self) -> None:
assert not is_blacklisted_path("foo/bar.py")
assert not is_blacklisted_path("foo.py")
assert not is_blacklisted_path("foo/xvendor/bar.py")
assert not is_blacklisted_path("foo/vendorx/bar.py")
assert is_blacklisted_path("foo/vendor/bar.py")
assert is_blacklisted_path("foo/vendored/bar.py")
assert is_blacklisted_path("foo/vendored/bar/thing.py")
assert is_blacklisted_path("foo/six.py")
def test_is_non_library_module(self) -> None:
assert not is_non_library_module("foo")
assert not is_non_library_module("foo.bar")
# The following could be test modules, but we are very conservative and
# don't treat them as such since they could plausibly be real modules.
assert not is_non_library_module("foo.bartest")
assert not is_non_library_module("foo.bartests")
assert not is_non_library_module("foo.testbar")
assert is_non_library_module("foo.test")
assert is_non_library_module("foo.test.foo")
assert is_non_library_module("foo.tests")
assert is_non_library_module("foo.tests.foo")
assert is_non_library_module("foo.testing.foo")
assert is_non_library_module("foo.SelfTest.foo")
assert is_non_library_module("foo.test_bar")
assert is_non_library_module("foo.bar_tests")
assert is_non_library_module("foo.testing")
assert is_non_library_module("foo.conftest")
assert is_non_library_module("foo.bar_test_util")
assert is_non_library_module("foo.bar_test_utils")
assert is_non_library_module("foo.bar_test_base")
assert is_non_library_module("foo.setup")
assert is_non_library_module("foo.__main__")
| StubgenHelpersSuite |
python | huggingface__transformers | src/transformers/models/smollm3/configuration_smollm3.py | {
"start": 1315,
"end": 10424
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SmolLM3Model`]. It is used to instantiate a
SmolLM3 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 SmolLM3 3B.
e.g. [HuggingFaceTB/SmolLM3-3B](https://huggingface.co/HuggingFaceTB/SmolLM3-3B)
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 128256):
Vocabulary size of the SmolLM3 model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`SmolLM3Model`]
hidden_size (`int`, *optional*, defaults to 2048):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 11008):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 36):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer encoder.
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 checkout [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `16`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 32768):
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 128004):
The id of the padding token.
bos_token_id (`int`, *optional*, defaults to 128000):
The id of the beginning of sentence token.
eos_token_id (`int`, *optional*, defaults to 128001):
The id of the end of sentence token.
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`.
use_sliding_window (`bool`, *optional*, defaults to `False`):
Whether to use sliding window attention.
sliding_window (`int`, *optional*):
Sliding window attention (SWA) window size. If not specified, will default to `None`.
no_rope_layers (`List[int]`, *optional*):
List with at least the same length as the number of layers in the model.
A `1` at an index position indicates that the corresponding layer will use RoPE,
while a `0` indicates that it's a NoPE layer.
no_rope_layer_interval (`int`, *optional*, defaults to 4):
If `no_rope_layers` is `None`, it will be created using a NoPE layer every
`no_rope_layer_interval` layers.
layer_types (`list`, *optional*):
Attention pattern for each layer. Automatically computed based on sliding window and NoPE settings.
attention_bias (`bool`, *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.
```python
>>> from transformers import SmolLM3Model, SmolLM3Config
>>> # Initializing a SmolLM3 style configuration
>>> configuration = SmolLM3Config()
>>> # Initializing a model from the SmolLM3 style configuration
>>> model = SmolLM3Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "smollm3"
keys_to_ignore_at_inference = ["past_key_values"]
default_theta = 2000000.0
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] = 128256,
hidden_size: Optional[int] = 2048,
intermediate_size: Optional[int] = 11008,
num_hidden_layers: Optional[int] = 36,
num_attention_heads: Optional[int] = 16,
num_key_value_heads: Optional[int] = 4,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 32768,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-6,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = 128004,
bos_token_id: Optional[int] = 128000,
eos_token_id: Optional[int] = 128001,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
use_sliding_window: Optional[bool] = False,
sliding_window: Optional[int] = None,
no_rope_layers: Optional[int] = None,
no_rope_layer_interval: Optional[int] = 4,
layer_types: Optional[int] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
mlp_bias: Optional[bool] = False,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.mlp_bias = mlp_bias
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.use_sliding_window = use_sliding_window
self.sliding_window = sliding_window
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
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
if no_rope_layers is None:
self.no_rope_layers = [
int((layer_idx + 1) % no_rope_layer_interval != 0) for layer_idx in range(num_hidden_layers)
]
else:
self.no_rope_layers = no_rope_layers
self.no_rope_layer_interval = no_rope_layer_interval
# Update layer_types based on sliding window and NoPE pattern
if layer_types is None:
layer_types = []
for layer_idx in range(num_hidden_layers):
has_rope = self.no_rope_layers[layer_idx]
if use_sliding_window and sliding_window is not None and not has_rope:
layer_types.append("sliding_attention")
else:
layer_types.append("full_attention")
self.layer_types = layer_types
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,
**kwargs,
)
__all__ = ["SmolLM3Config"]
| SmolLM3Config |
python | walkccc__LeetCode | solutions/2998. Minimum Number of Operations to Make X and Y Equal/2998.py | {
"start": 0,
"end": 545
} | class ____:
def minimumOperationsToMakeEqual(self, x, y):
if x <= y:
return y - x
queue = collections.deque([x])
seen = set()
ans = 0
while queue:
for _ in range(len(queue)):
num = queue.popleft()
if num == y:
return ans
if num in seen:
continue
seen.add(num)
if num % 11 == 0:
queue.append(num // 11)
if num % 5 == 0:
queue.append(num // 5)
queue.append(num - 1)
queue.append(num + 1)
ans += 1
| Solution |
python | pytorch__pytorch | test/quantization/fx/test_model_report_fx.py | {
"start": 62605,
"end": 74944
} | class ____(QuantizationTestCase):
class LargeBatchModel(torch.nn.Module):
def __init__(self, param_size):
super().__init__()
self.param_size = param_size
self.linear = torch.nn.Linear(param_size, param_size)
self.relu_1 = torch.nn.ReLU()
self.conv = torch.nn.Conv2d(param_size, param_size, 1)
self.relu_2 = torch.nn.ReLU()
def forward(self, x):
x = self.linear(x)
x = self.relu_1(x)
x = self.conv(x)
x = self.relu_2(x)
return x
def get_example_inputs(self):
param_size = self.param_size
return (torch.randn((1, param_size, param_size, param_size)),)
def get_outlier_inputs(self):
param_size = self.param_size
random_vals = torch.randn((1, param_size, param_size, param_size))
# change one in some of them to be a massive value
random_vals[:, 0:param_size:2, 0, 3] = torch.tensor([3.28e8])
return (random_vals,)
def _get_prepped_for_calibration_model(self, model, detector_set, use_outlier_data=False):
r"""Returns a model that has been prepared for calibration and corresponding model_report"""
# call the general helper function to calibrate
example_input = model.get_example_inputs()[0]
# if we specifically want to test data with outliers replace input
if use_outlier_data:
example_input = model.get_outlier_inputs()[0]
return _get_prepped_for_calibration_model_helper(model, detector_set, example_input)
@skipIfNoFBGEMM
def test_outlier_detection_determine_points(self):
# use fbgemm and create our model instance
# then create model report instance with detector
# similar to test for InputWeightEqualization but key differences that made refactoring not viable
# not explicitly testing fusion because fx workflow automatically
with override_quantized_engine('fbgemm'):
detector_set = {OutlierDetector(reference_percentile=0.95)}
# get tst model and calibrate
prepared_for_callibrate_model, mod_report = self._get_prepped_for_calibration_model(
self.LargeBatchModel(param_size=128), detector_set
)
# supported modules to check
mods_to_check = {nn.Linear, nn.Conv2d, nn.ReLU}
# there should be 4 node fqns that have the observer inserted
correct_number_of_obs_inserted = 4
number_of_obs_found = 0
obs_name_to_find = InputWeightEqualizationDetector.DEFAULT_PRE_OBSERVER_NAME
number_of_obs_found = sum(
1 if obs_name_to_find in str(node.target) else 0 for node in prepared_for_callibrate_model.graph.nodes
)
self.assertEqual(number_of_obs_found, correct_number_of_obs_inserted)
# assert that each of the desired modules have the observers inserted
for module in prepared_for_callibrate_model.modules():
# check if module is a supported module
is_in_include_list = isinstance(module, tuple(mods_to_check))
if is_in_include_list:
# make sure it has the observer attribute
self.assertTrue(hasattr(module, InputWeightEqualizationDetector.DEFAULT_PRE_OBSERVER_NAME))
else:
# if it's not a supported type, it shouldn't have observer attached
self.assertTrue(not hasattr(module, InputWeightEqualizationDetector.DEFAULT_PRE_OBSERVER_NAME))
@skipIfNoFBGEMM
def test_no_outlier_report_gen(self):
# use fbgemm and create our model instance
# then create model report instance with detector
with override_quantized_engine('fbgemm'):
# test with multiple detectors
outlier_detector = OutlierDetector(reference_percentile=0.95)
dynamic_static_detector = DynamicStaticDetector(tolerance=0.5)
param_size: int = 4
detector_set = {outlier_detector, dynamic_static_detector}
model = self.LargeBatchModel(param_size=param_size)
# get tst model and calibrate
prepared_for_callibrate_model, mod_report = self._get_prepped_for_calibration_model(
model, detector_set
)
# now we actually calibrate the model
example_input = model.get_example_inputs()[0]
example_input = example_input.to(torch.float)
prepared_for_callibrate_model(example_input)
# now get the report by running it through ModelReport instance
generated_report = mod_report.generate_model_report(True)
# check that sizes are appropriate only 2 detectors
self.assertEqual(len(generated_report), 2)
# get the specific report for input weight equalization
outlier_str, outlier_dict = generated_report[outlier_detector.get_detector_name()]
# we should have 5 layers looked at since 4 conv + linear + relu
self.assertEqual(len(outlier_dict), 4)
# assert the following are true for all the modules
for module_fqn in outlier_dict:
# get the info for the specific module
module_dict = outlier_dict[module_fqn]
# there really should not be any outliers since we used a normal distribution to perform this calculation
outlier_info = module_dict[OutlierDetector.OUTLIER_KEY]
self.assertEqual(sum(outlier_info), 0)
# ensure that the number of ratios and batches counted is the same as the number of params
self.assertEqual(len(module_dict[OutlierDetector.COMP_METRIC_KEY]), param_size)
self.assertEqual(len(module_dict[OutlierDetector.NUM_BATCHES_KEY]), param_size)
@skipIfNoFBGEMM
def test_all_outlier_report_gen(self):
# make the percentile 0 and the ratio 1, and then see that everything is outlier according to it
# use fbgemm and create our model instance
# then create model report instance with detector
with override_quantized_engine('fbgemm'):
# create detector of interest
outlier_detector = OutlierDetector(ratio_threshold=1, reference_percentile=0)
param_size: int = 16
detector_set = {outlier_detector}
model = self.LargeBatchModel(param_size=param_size)
# get tst model and calibrate
prepared_for_callibrate_model, mod_report = self._get_prepped_for_calibration_model(
model, detector_set
)
# now we actually calibrate the model
example_input = model.get_example_inputs()[0]
example_input = example_input.to(torch.float)
prepared_for_callibrate_model(example_input)
# now get the report by running it through ModelReport instance
generated_report = mod_report.generate_model_report(True)
# check that sizes are appropriate only 1 detector
self.assertEqual(len(generated_report), 1)
# get the specific report for input weight equalization
outlier_str, outlier_dict = generated_report[outlier_detector.get_detector_name()]
# we should have 5 layers looked at since 4 conv + linear + relu
self.assertEqual(len(outlier_dict), 4)
# assert the following are true for all the modules
for module_fqn in outlier_dict:
# get the info for the specific module
module_dict = outlier_dict[module_fqn]
# everything should be an outlier because we said that the max should be equal to the min for all of them
# however we will just test and say most should be in case we have several 0 channel values
outlier_info = module_dict[OutlierDetector.OUTLIER_KEY]
assert sum(outlier_info) >= len(outlier_info) / 2
# ensure that the number of ratios and batches counted is the same as the number of params
self.assertEqual(len(module_dict[OutlierDetector.COMP_METRIC_KEY]), param_size)
self.assertEqual(len(module_dict[OutlierDetector.NUM_BATCHES_KEY]), param_size)
@skipIfNoFBGEMM
def test_multiple_run_consistent_spike_outlier_report_gen(self):
# specifically make a row really high consistently in the number of batches that you are testing and try that
# generate report after just 1 run, and after many runs (30) and make sure above minimum threshold is there
with override_quantized_engine('fbgemm'):
# detector of interest
outlier_detector = OutlierDetector(reference_percentile=0.95)
param_size: int = 8
detector_set = {outlier_detector}
model = self.LargeBatchModel(param_size=param_size)
# get tst model and calibrate
prepared_for_callibrate_model, mod_report = self._get_prepped_for_calibration_model(
model, detector_set, use_outlier_data=True
)
# now we actually calibrate the model
example_input = model.get_outlier_inputs()[0]
example_input = example_input.to(torch.float)
# now calibrate minimum 30 times to make it above minimum threshold
for i in range(30):
example_input = model.get_outlier_inputs()[0]
example_input = example_input.to(torch.float)
# make 2 of the batches to have zero channel
if i % 14 == 0:
# make one channel constant
example_input[0][1] = torch.zeros_like(example_input[0][1])
prepared_for_callibrate_model(example_input)
# now get the report by running it through ModelReport instance
generated_report = mod_report.generate_model_report(True)
# check that sizes are appropriate only 1 detector
self.assertEqual(len(generated_report), 1)
# get the specific report for input weight equalization
outlier_str, outlier_dict = generated_report[outlier_detector.get_detector_name()]
# we should have 5 layers looked at since 4 conv + linear + relu
self.assertEqual(len(outlier_dict), 4)
# assert the following are true for all the modules
for module_fqn in outlier_dict:
# get the info for the specific module
module_dict = outlier_dict[module_fqn]
# because we ran 30 times, we should have at least a couple be significant
# could be less because some channels could possibly be all 0
sufficient_batches_info = module_dict[OutlierDetector.IS_SUFFICIENT_BATCHES_KEY]
assert sum(sufficient_batches_info) >= len(sufficient_batches_info) / 2
# half of them should be outliers, because we set a really high value every 2 channels
outlier_info = module_dict[OutlierDetector.OUTLIER_KEY]
self.assertEqual(sum(outlier_info), len(outlier_info) / 2)
# ensure that the number of ratios and batches counted is the same as the number of params
self.assertEqual(len(module_dict[OutlierDetector.COMP_METRIC_KEY]), param_size)
self.assertEqual(len(module_dict[OutlierDetector.NUM_BATCHES_KEY]), param_size)
# for the first one ensure the per channel max values are what we set
if module_fqn == "linear.0":
# check that the non-zero channel count, at least 2 should be there
# for the first module
counts_info = module_dict[OutlierDetector.CONSTANT_COUNTS_KEY]
assert sum(counts_info) >= 2
# half of the recorded max values should be what we set
matched_max = sum(val == 3.28e8 for val in module_dict[OutlierDetector.MAX_VALS_KEY])
self.assertEqual(matched_max, param_size / 2)
| TestFxDetectOutliers |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_workers.py | {
"start": 35709,
"end": 37783
} | class ____:
@pytest.fixture(autouse=True)
async def create_work_pools(self, client):
for name in ["C", "B", "A"]:
await client.post("/work_pools/", json=dict(name=name, type="test"))
async def test_read_work_pools(self, client, session):
response = await client.post("/work_pools/filter")
assert response.status_code == status.HTTP_200_OK, response.text
result = parse_obj_as(List[WorkPool], response.json())
assert [r.name for r in result] == ["A", "B", "C"]
async def test_read_work_pools_with_limit(self, client, session):
response = await client.post("/work_pools/filter", json=dict(limit=2))
assert response.status_code == status.HTTP_200_OK, response.text
result = parse_obj_as(List[WorkPool], response.json())
assert [r.name for r in result] == ["A", "B"]
async def test_read_work_pools_with_offset(self, client, session):
response = await client.post("/work_pools/filter", json=dict(offset=1))
assert response.status_code == status.HTTP_200_OK, response.text
result = parse_obj_as(List[WorkPool], response.json())
assert [r.name for r in result] == ["B", "C"]
async def test_read_work_pool_with_work_pool_that_fails_validation(
self,
client,
invalid_work_pool,
):
response = await client.post("/work_pools/filter")
assert response.status_code == 200, response.text
assert len(response.json()) == 4
async def test_read_work_pool_with_3_3_7_client_version_does_not_include_default_result_storage_block_id(
self,
client: AsyncClient,
):
response = await client.post(
"/work_pools/filter",
headers={"User-Agent": "prefect/3.3.7 (API 0.8.4)"},
)
assert response.status_code == 200
for work_pool in response.json():
assert work_pool["storage_configuration"] == {
"bundle_upload_step": None,
"bundle_execution_step": None,
}
| TestReadWorkPools |
python | ansible__ansible | lib/ansible/plugins/callback/__init__.py | {
"start": 3355,
"end": 4687
} | class ____:
def __getitem__(self, ch):
# "special character" logic from pyyaml yaml.emitter.Emitter.analyze_scalar, translated to decimal
# for perf w/ str.translate
if (ch == 10 or
32 <= ch <= 126 or
ch == 133 or
160 <= ch <= 55295 or
57344 <= ch <= 65533 or
65536 <= ch < 1114111)\
and ch != 65279:
return ch
return None
def _filter_yaml_special(scalar: str) -> str:
"""Filter a string removing any character that libyaml/pyyaml declare as special"""
return scalar.translate(_SpecialCharacterTranslator())
def _munge_data_for_lossy_yaml(scalar: str) -> str:
"""Modify a string so that analyze_scalar in libyaml/pyyaml will allow block formatting"""
# we care more about readability than accuracy, so...
# ...libyaml/pyyaml does not permit trailing spaces for block scalars
scalar = scalar.rstrip()
# ...libyaml/pyyaml does not permit tabs for block scalars
scalar = scalar.expandtabs()
# ...libyaml/pyyaml only permits special characters for double quoted scalars
scalar = _filter_yaml_special(scalar)
# ...libyaml/pyyaml only permits spaces followed by breaks for double quoted scalars
return _SPACE_BREAK_RE.sub(r'\1', scalar)
| _SpecialCharacterTranslator |
python | joke2k__faker | tests/test_proxy.py | {
"start": 243,
"end": 17290
} | class ____:
"""Test Faker proxy class"""
def test_unspecified_locale(self):
fake = Faker()
assert len(fake.locales) == 1
assert len(fake.factories) == 1
assert fake.locales[0] == DEFAULT_LOCALE
def test_locale_as_string(self):
locale = "en_US"
fake = Faker(locale)
assert len(fake.locales) == 1
assert len(fake.factories) == 1
assert fake.locales[0] == locale
def test_locale_as_list(self):
locale = ["en-US", "en_PH", "ja_JP", "de-DE"]
expected = ["en_US", "en_PH", "ja_JP", "de_DE"]
fake = Faker(locale)
assert fake.locales == expected
assert len(fake.factories) == len(expected)
locale = ["en-US", "en_PH", "ja_JP", "de-DE", "ja-JP", "de_DE", "en-US"] * 3
expected = ["en_US", "en_PH", "ja_JP", "de_DE"]
fake = Faker(locale)
assert fake.locales == expected
assert len(fake.factories) == len(expected)
def test_locale_as_list_invalid_value_type(self):
locale = [1, 2]
with pytest.raises(TypeError) as exc:
Faker(locale)
assert str(exc.value) == 'The locale "1" must be a string.'
def test_locale_as_ordereddict(self):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale)
assert fake.locales == ["de_DE", "en_US", "en_PH", "ja_JP"]
assert len(fake.factories) == 4
assert fake.weights == [3, 2, 1, 5]
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
("de-DE", 4),
("ja-JP", 2),
("en-US", 1),
]
)
fake = Faker(locale)
assert fake.locales == ["de_DE", "en_US", "en_PH", "ja_JP"]
assert len(fake.factories) == 4
assert fake.weights == [4, 1, 1, 2]
def test_invalid_locale(self):
with pytest.raises(AttributeError):
Faker("foo_Bar")
with pytest.raises(AttributeError):
Faker(["en_US", "foo_Bar"])
with pytest.raises(AttributeError):
Faker(
OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("foo_Bar", 5),
]
)
)
def test_items(self):
locale = ["de_DE", "en-US", "en-PH", "ja_JP", "de-DE", "ja-JP", "en-US"]
processed_locale = list({code.replace("-", "_") for code in locale})
fake = Faker(locale)
for locale_name, factory in fake.items():
assert locale_name in processed_locale
assert isinstance(factory, (Generator, Faker))
def test_dunder_getitem(self):
locale = ["de_DE", "en-US", "en-PH", "ja_JP"]
fake = Faker(locale)
for code in locale:
assert isinstance(fake[code], (Generator, Faker))
with pytest.raises(KeyError):
fake["en_GB"]
def test_seed_classmethod(self):
fake = Faker()
# Verify `seed()` is not callable from a class instance
with pytest.raises(TypeError):
fake.seed(0)
# Verify calls to `seed()` from a class object are proxied properly
with patch("faker.generator.Generator.seed") as mock_seed:
mock_seed.assert_not_called()
Faker.seed(0)
mock_seed.assert_called_once_with(0)
def test_seed_class_locales(self):
Faker.seed(2043)
count = 5
fake = Faker(["en_GB", "fr_FR", "en_IN"])
first_list = [fake.name() for _ in range(count)]
# We convert the list to a set to remove duplicates and ensure
# that we have exactly `count` unique fake values
assert len(set(first_list)) == count
Faker.seed(2043)
fake = Faker(["en_GB", "fr_FR", "en_IN"])
second_list = [fake.name() for _ in range(count)]
assert first_list == second_list
def test_seed_instance(self):
locale = ["de_DE", "en-US", "en-PH", "ja_JP"]
fake = Faker(locale)
with patch("faker.generator.Generator.seed_instance") as mock_seed_instance:
mock_seed_instance.assert_not_called()
fake.seed_instance(0)
# Verify `seed_instance(0)` was called 4 times (one for each locale)
calls = mock_seed_instance.call_args_list
assert len(calls) == 4
for call in calls:
args, kwargs = call
assert args == (0,)
assert kwargs == {}
def test_seed_locale(self):
from faker.generator import random as shared_random_instance
locale = ["de_DE", "en-US", "en-PH", "ja_JP"]
fake = Faker(locale)
# Get current state of each factory's random instance
states = {}
for locale, factory in fake.items():
states[locale] = factory.random.getstate()
# Create a new random instance for en_US factory with seed value
fake.seed_locale("en_US", 0)
for locale, factory in fake.items():
# en_US factory should have changed
if locale == "en_US":
assert factory.random != shared_random_instance
assert factory.random.getstate() != states[locale]
# There should be no changes for the rest
else:
assert factory.random == shared_random_instance
assert factory.random.getstate() == states[locale]
def test_single_locale_proxy_behavior(self):
fake = Faker()
internal_factory = fake.factories[0]
# Test if `Generator` attributes are proxied properly
for attr in fake.generator_attrs:
assert getattr(fake, attr) == getattr(internal_factory, attr)
# Test if `random` getter and setter are proxied properly
tmp_random = fake.random
assert internal_factory.random != 1
fake.random = 1
assert internal_factory.random == 1
fake.random = tmp_random
# Test if a valid provider method is proxied properly
# Factory selection logic should not be triggered
with patch("faker.proxy.Faker._select_factory") as mock_select_factory:
mock_select_factory.assert_not_called()
assert fake.name == internal_factory.name
fake.name()
mock_select_factory.assert_not_called()
def test_multiple_locale_proxy_behavior(self):
fake = Faker(["de-DE", "en-US", "en-PH", "ja-JP"])
# `Generator` attributes are not implemented
for attr in fake.generator_attrs:
with pytest.raises(NotImplementedError):
getattr(fake, attr)
# The `random` getter is not implemented
with pytest.raises(NotImplementedError):
random = fake.random
random.seed(0)
# The `random` setter is not implemented
with pytest.raises(NotImplementedError):
fake.random = 1
def test_multiple_locale_caching_behavior(self):
fake = Faker(["de_DE", "en-US", "en-PH", "ja_JP"])
with patch("faker.proxy.Faker._map_provider_method", wraps=fake._map_provider_method) as mock_map_method:
mock_map_method.assert_not_called()
assert not hasattr(fake, "_cached_name_mapping")
# Test cache creation
fake.name()
assert hasattr(fake, "_cached_name_mapping")
mock_map_method.assert_called_once_with("name")
# Test subsequent cache access
with patch.object(Faker, "_cached_name_mapping", create=True, new_callable=PropertyMock) as mock_cached_map:
# Keep test fast by patching the cached mapping to return something simpler
mock_cached_map.return_value = [fake["en_US"]], [1]
for _ in range(100):
fake.name()
# Python's hasattr() internally calls getattr()
# So each call to name() accesses the cached mapping twice
assert mock_cached_map.call_count == 200
@patch("faker.proxy.Faker._select_factory_choice")
@patch("faker.proxy.Faker._select_factory_distribution")
def test_multiple_locale_factory_selection_no_weights(self, mock_factory_distribution, mock_factory_choice):
fake = Faker(["de_DE", "en-US", "en-PH", "ja_JP"])
# There are no distribution weights, so factory selection logic will use `random.choice`
# if multiple factories have the specified provider method
with patch("faker.proxy.Faker._select_factory", wraps=fake._select_factory) as mock_select_factory:
mock_select_factory.assert_not_called()
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_not_called()
# All factories for the listed locales have the `name` provider method
fake.name()
mock_select_factory.assert_called_once_with("name")
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_called_once_with(fake.factories)
mock_select_factory.reset_mock()
mock_factory_distribution.reset_mock()
mock_factory_choice.reset_mock()
# Only `en_PH` factory has provider method `luzon_province`, so there is no
# need for `random.choice` factory selection logic to run
fake.luzon_province()
mock_select_factory.assert_called_with("luzon_province")
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_not_called()
mock_select_factory.reset_mock()
mock_factory_distribution.reset_mock()
mock_factory_choice.reset_mock()
# Both `en_US` and `ja_JP` factories have provider method `zipcode`
fake.zipcode()
mock_select_factory.assert_called_once_with("zipcode")
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_called_once_with(
[fake["en_US"], fake["ja_JP"]],
)
@patch("faker.proxy.Faker._select_factory_choice")
@patch("faker.proxy.Faker._select_factory_distribution")
def test_multiple_locale_factory_selection_with_weights(self, mock_factory_distribution, mock_factory_choice):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale)
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_not_called()
# Distribution weights have been specified, so factory selection logic will use
# `choices_distribution` if multiple factories have the specified provider method
with patch("faker.proxy.Faker._select_factory", wraps=fake._select_factory) as mock_select_factory:
# All factories for the listed locales have the `name` provider method
fake.name()
mock_select_factory.assert_called_once_with("name")
mock_factory_distribution.assert_called_once_with(fake.factories, fake.weights)
mock_factory_choice.assert_not_called()
@patch("faker.proxy.Faker._select_factory_choice")
@patch("faker.proxy.Faker._select_factory_distribution")
def test_multiple_locale_factory_selection_single_provider(self, mock_factory_distribution, mock_factory_choice):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale)
# Distribution weights have been specified, so factory selection logic will use
# `choices_distribution` if multiple factories have the specified provider method
with patch("faker.proxy.Faker._select_factory", wraps=fake._select_factory) as mock_select_factory:
# Only `en_PH` factory has provider method `luzon_province`, so there is no
# need for `choices_distribution` factory selection logic to run
fake.luzon_province()
mock_select_factory.assert_called_once_with("luzon_province")
mock_factory_distribution.assert_not_called()
mock_factory_choice.assert_not_called()
@patch("faker.proxy.Faker._select_factory_choice")
@patch("faker.proxy.Faker._select_factory_distribution")
def test_multiple_locale_factory_selection_shared_providers(self, mock_factory_distribution, mock_factory_choice):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale)
with patch("faker.proxy.Faker._select_factory", wraps=fake._select_factory) as mock_select_factory:
# Both `en_US` and `ja_JP` factories have provider method `zipcode`
fake.zipcode()
mock_select_factory.assert_called_once_with("zipcode")
mock_factory_distribution.assert_called_once_with([fake["en_US"], fake["ja_JP"]], [2, 5])
mock_factory_choice.assert_not_called()
def test_multiple_locale_factory_selection_unsupported_method(self):
fake = Faker(["en_US", "en_PH"])
with pytest.raises(AttributeError):
fake.obviously_invalid_provider_method_a23f()
@patch("random.Random.choice")
@patch("random.Random.choices")
def test_weighting_disabled_single_choice(self, mock_choices_fn, mock_choice_fn):
fake = Faker(use_weighting=False)
fake.first_name()
mock_choice_fn.assert_called()
mock_choices_fn.assert_not_called()
@patch("random.Random.choice")
@patch("random.Random.choices", wraps=random.Random().choices)
def test_weighting_disabled_with_locales(self, mock_choices_fn, mock_choice_fn):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale, use_weighting=False)
fake.first_name()
mock_choices_fn.assert_called() # select provider
mock_choice_fn.assert_called() # select within provider
@patch("random.Random.choice")
@patch("random.Random.choices", wraps=random.Random().choices)
def test_weighting_disabled_multiple_locales(self, mock_choices_fn, mock_choice_fn):
locale = OrderedDict(
[
("de_DE", 3),
("en-US", 2),
("en-PH", 1),
("ja_JP", 5),
]
)
fake = Faker(locale, use_weighting=False)
fake.first_name()
mock_choices_fn.assert_called() # select provider
mock_choice_fn.assert_called() # select within provider
@patch("random.Random.choice")
@patch("random.Random.choices", wraps=random.Random().choices)
def test_weighting_disabled_multiple_choices(self, mock_choices_fn, mock_choice_fn):
fake = Faker(use_weighting=False)
fake.uri_path(deep=3)
assert mock_choices_fn.mock_calls[0][2]["k"] == 3
assert mock_choices_fn.mock_calls[0][2]["weights"] is None
mock_choice_fn.assert_not_called()
@patch("random.Random.choice")
@patch("random.Random.choices", wraps=random.Random().choices)
def test_weighting_enabled_multiple_choices(self, mock_choices_fn, mock_choice_fn):
fake = Faker(use_weighting=True)
fake.uri_path(deep=3)
assert mock_choices_fn.mock_calls[0][2]["k"] == 3
assert mock_choices_fn.mock_calls[0][2]["weights"] is None
mock_choice_fn.assert_not_called()
def test_dir_include_all_providers_attribute_in_list(self):
fake = Faker(["en_US", "en_PH"])
expected = set(
dir(Faker)
+ [
"_factories",
"_locales",
"_factory_map",
"_weights",
"_unique_proxy",
"_optional_proxy",
]
)
for factory in fake.factories:
expected |= {attr for attr in dir(factory) if not attr.startswith("_")}
expected = sorted(expected)
attributes = dir(fake)
assert attributes == expected
def test_copy(self):
fake = Faker("it_IT")
fake2 = copy.deepcopy(fake)
assert fake.locales == fake2.locales
assert fake.locales is not fake2.locales
def test_pickle(self):
fake = Faker()
pickled = pickle.dumps(fake)
pickle.loads(pickled)
| TestFakerProxyClass |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 961497,
"end": 962053
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node", "text_matches")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("SearchResultItem", graphql_name="node")
"""The item at the end of the edge."""
text_matches = sgqlc.types.Field(sgqlc.types.list_of("TextMatch"), graphql_name="textMatches")
"""Text matches on the result found."""
| SearchResultItemEdge |
python | huggingface__transformers | tests/models/superpoint/test_image_processing_superpoint.py | {
"start": 3737,
"end": 8295
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = SuperPointImageProcessor if is_vision_available() else None
fast_image_processing_class = SuperPointImageProcessorFast if is_torchvision_available() else None
def setUp(self) -> None:
super().setUp()
self.image_processor_tester = SuperPointImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
def test_image_processing(self):
for image_processing_class in self.image_processor_list:
image_processing = image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(image_processing, "do_resize"))
self.assertTrue(hasattr(image_processing, "size"))
self.assertTrue(hasattr(image_processing, "do_rescale"))
self.assertTrue(hasattr(image_processing, "rescale_factor"))
self.assertTrue(hasattr(image_processing, "do_grayscale"))
def test_image_processor_from_dict_with_kwargs(self):
for image_processing_class in self.image_processor_list:
image_processor = image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size, {"height": 480, "width": 640})
image_processor = self.image_processing_class.from_dict(
self.image_processor_dict, size={"height": 42, "width": 42}
)
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
@unittest.skip(reason="SuperPointImageProcessor is always supposed to return a grayscaled image")
def test_call_numpy_4_channels(self):
pass
def test_input_image_properly_converted_to_grayscale(self):
for image_processing_class in self.image_processor_list:
image_processor = image_processing_class.from_dict(self.image_processor_dict)
image_inputs = self.image_processor_tester.prepare_image_inputs()
pre_processed_images = image_processor.preprocess(image_inputs)
for image in pre_processed_images["pixel_values"]:
if isinstance(image, torch.Tensor):
self.assertTrue(
torch.all(image[0, ...] == image[1, ...]).item()
and torch.all(image[1, ...] == image[2, ...]).item()
)
else:
self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))
@require_torch
def test_post_processing_keypoint_detection(self):
def check_post_processed_output(post_processed_output, image_size):
for post_processed_output, image_size in zip(post_processed_output, image_size):
self.assertTrue("keypoints" in post_processed_output)
self.assertTrue("descriptors" in post_processed_output)
self.assertTrue("scores" in post_processed_output)
keypoints = post_processed_output["keypoints"]
all_below_image_size = torch.all(keypoints[:, 0] <= image_size[1]) and torch.all(
keypoints[:, 1] <= image_size[0]
)
all_above_zero = torch.all(keypoints[:, 0] >= 0) and torch.all(keypoints[:, 1] >= 0)
self.assertTrue(all_below_image_size)
self.assertTrue(all_above_zero)
for image_processing_class in self.image_processor_list:
image_processor = image_processing_class.from_dict(self.image_processor_dict)
image_inputs = self.image_processor_tester.prepare_image_inputs()
pre_processed_images = image_processor.preprocess(image_inputs, return_tensors="pt")
outputs = self.image_processor_tester.prepare_keypoint_detection_output(**pre_processed_images)
tuple_image_sizes = [(image.size[0], image.size[1]) for image in image_inputs]
tuple_post_processed_outputs = image_processor.post_process_keypoint_detection(outputs, tuple_image_sizes)
check_post_processed_output(tuple_post_processed_outputs, tuple_image_sizes)
tensor_image_sizes = torch.tensor([image.size for image in image_inputs]).flip(1)
tensor_post_processed_outputs = image_processor.post_process_keypoint_detection(
outputs, tensor_image_sizes
)
check_post_processed_output(tensor_post_processed_outputs, tensor_image_sizes)
| SuperPointImageProcessingTest |
python | scipy__scipy | scipy/fft/_pocketfft/tests/test_basic.py | {
"start": 10513,
"end": 10642
} | class ____(_TestRFFTBase):
def setup_method(self):
self.cdt = np.complex64
self.rdt = np.float32
| TestRFFTSingle |
python | FactoryBoy__factory_boy | tests/test_using.py | {
"start": 38395,
"end": 45792
} | class ____(unittest.TestCase):
def test_traits(self):
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
even = factory.Trait(two=True, four=True)
odd = factory.Trait(one=True, three=True, five=True)
obj1 = TestObjectFactory()
self.assertEqual(
obj1.as_dict(),
dict(one=None, two=None, three=None, four=None, five=None),
)
obj2 = TestObjectFactory(even=True)
self.assertEqual(
obj2.as_dict(),
dict(one=None, two=True, three=None, four=True, five=None),
)
obj3 = TestObjectFactory(odd=True)
self.assertEqual(
obj3.as_dict(),
dict(one=True, two=None, three=True, four=None, five=True),
)
obj4 = TestObjectFactory(even=True, odd=True)
self.assertEqual(
obj4.as_dict(),
dict(one=True, two=True, three=True, four=True, five=True),
)
obj5 = TestObjectFactory(odd=True, two=True)
self.assertEqual(
obj5.as_dict(),
dict(one=True, two=True, three=True, four=None, five=True),
)
def test_post_generation_traits(self):
@factory.post_generation
def compute(obj, _create, _value, power=2, **kwargs):
obj.value = obj.value ** power
class DummyFactory(factory.Factory):
class Meta:
model = Dummy
value = 3
class Params:
exponentiate = factory.Trait(apply_exponent=compute)
base = DummyFactory.build()
self.assertEqual(dict(value=3), base.as_dict)
exp = DummyFactory.build(exponentiate=True)
self.assertEqual(dict(value=9), exp.as_dict)
higher = DummyFactory.build(exponentiate=True, apply_exponent__power=4)
self.assertEqual(dict(value=81), higher.as_dict)
def test_traits_inheritance(self):
"""A trait can be set in an inherited class."""
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
even = factory.Trait(two=True, four=True)
odd = factory.Trait(one=True, three=True, five=True)
class EvenObjectFactory(TestObjectFactory):
even = True
# Simple call
obj1 = EvenObjectFactory()
self.assertEqual(
obj1.as_dict(),
dict(one=None, two=True, three=None, four=True, five=None),
)
# Force-disable it
obj2 = EvenObjectFactory(even=False)
self.assertEqual(
obj2.as_dict(),
dict(one=None, two=None, three=None, four=None, five=None),
)
def test_traits_override_params(self):
"""Override a Params value in a trait"""
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
one = factory.LazyAttribute(lambda o: o.zero + 1)
class Params:
zero = 0
plus_one = factory.Trait(zero=1)
obj = TestObjectFactory(plus_one=True)
self.assertEqual(obj.one, 2)
def test_traits_override(self):
"""Override a trait in a subclass."""
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
even = factory.Trait(two=True, four=True)
odd = factory.Trait(one=True, three=True, five=True)
class WeirdMathFactory(TestObjectFactory):
class Params:
# Here, one is even.
even = factory.Trait(two=True, four=True, one=True)
obj = WeirdMathFactory(even=True)
self.assertEqual(
obj.as_dict(),
dict(one=True, two=True, three=None, four=True, five=None),
)
def test_traits_chaining(self):
"""Use a trait to enable other traits."""
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
even = factory.Trait(two=True, four=True)
odd = factory.Trait(one=True, three=True, five=True)
full = factory.Trait(even=True, odd=True)
override = factory.Trait(even=True, two=False)
# Setting "full" should enable all fields.
obj = TestObjectFactory(full=True)
self.assertEqual(
obj.as_dict(),
dict(one=True, two=True, three=True, four=True, five=True),
)
# Does it break usual patterns?
obj1 = TestObjectFactory()
self.assertEqual(
obj1.as_dict(),
dict(one=None, two=None, three=None, four=None, five=None),
)
obj2 = TestObjectFactory(even=True)
self.assertEqual(
obj2.as_dict(),
dict(one=None, two=True, three=None, four=True, five=None),
)
obj3 = TestObjectFactory(odd=True)
self.assertEqual(
obj3.as_dict(),
dict(one=True, two=None, three=True, four=None, five=True),
)
# Setting override should override two and set it to False
obj = TestObjectFactory(override=True)
self.assertEqual(
obj.as_dict(),
dict(one=None, two=False, three=None, four=True, five=None),
)
def test_prevent_cyclic_traits(self):
with self.assertRaises(errors.CyclicDefinitionError):
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
a = factory.Trait(b=True, one=True)
b = factory.Trait(a=True, two=True)
def test_deep_traits(self):
class TestObjectFactory(factory.Factory):
class Meta:
model = TestObject
class WrapperFactory(factory.Factory):
class Meta:
model = TestObject
class Params:
deep_one = factory.Trait(
one=1,
two__one=2,
)
two = factory.SubFactory(TestObjectFactory)
wrapper = WrapperFactory(deep_one=True)
self.assertEqual(1, wrapper.one)
self.assertEqual(2, wrapper.two.one)
def test_traits_and_postgeneration(self):
"""A trait parameter should be resolved before post_generation hooks.
See https://github.com/FactoryBoy/factory_boy/issues/466.
"""
PRICES = {}
Pizza = collections.namedtuple('Pizza', ['style', 'toppings'])
class PizzaFactory(factory.Factory):
class Meta:
model = Pizza
class Params:
fancy = factory.Trait(
toppings=['eggs', 'ham', 'extra_cheese'],
pricing__extra=10,
)
pricing__extra = 0
toppings = ['tomato', 'cheese']
style = 'margharita'
@factory.post_generation
def pricing(self, create, extracted, base_price=5, extra=0, **kwargs):
PRICES[base_price + extra] = self
p = PizzaFactory.build()
self.assertEqual({5: p}, PRICES)
| TraitTestCase |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_wx.py | {
"start": 31504,
"end": 33571
} | class ____(_FigureCanvasWxBase):
# Rendering to a Wx canvas using the deprecated Wx renderer.
def draw(self, drawDC=None):
"""
Render the figure using RendererWx instance renderer, or using a
previously defined renderer if none is specified.
"""
_log.debug("%s - draw()", type(self))
self.renderer = RendererWx(self.bitmap, self.figure.dpi)
self.figure.draw(self.renderer)
self._isDrawn = True
self.gui_repaint(drawDC=drawDC)
def _print_image(self, filetype, filename):
bitmap = wx.Bitmap(math.ceil(self.figure.bbox.width),
math.ceil(self.figure.bbox.height))
self.figure.draw(RendererWx(bitmap, self.figure.dpi))
saved_obj = (bitmap.ConvertToImage()
if cbook.is_writable_file_like(filename)
else bitmap)
if not saved_obj.SaveFile(filename, filetype):
raise RuntimeError(f'Could not save figure to {filename}')
# draw() is required here since bits of state about the last renderer
# are strewn about the artist draw methods. Do not remove the draw
# without first verifying that these have been cleaned up. The artist
# contains() methods will fail otherwise.
if self._isDrawn:
self.draw()
# The "if self" check avoids a "wrapped C/C++ object has been deleted"
# RuntimeError if doing things after window is closed.
if self:
self.Refresh()
print_bmp = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_BMP)
print_jpeg = print_jpg = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_JPEG)
print_pcx = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_PCX)
print_png = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_PNG)
print_tiff = print_tif = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_TIF)
print_xpm = functools.partialmethod(
_print_image, wx.BITMAP_TYPE_XPM)
| FigureCanvasWx |
python | modin-project__modin | modin/tests/config/docs_module/classes.py | {
"start": 1031,
"end": 1357
} | class ____:
"""This is a test of the documentation module for BasePandasDataSet."""
def apply():
"""This is a test of the documentation module for BasePandasDataSet.apply."""
return
def astype():
"""This is a test of the documentation module for BasePandasDataSet.astype."""
| BasePandasDataset |
python | Delgan__loguru | tests/exceptions/source/others/broken_but_decorated_repr.py | {
"start": 274,
"end": 532
} | class ____:
def __repr__(self):
with logger.catch(reraise=True):
raise ValueError("Something went wrong (Bar)")
foo = Foo()
bar = Bar()
try:
repr(foo)
except ValueError:
pass
try:
repr(bar)
except ValueError:
pass
| Bar |
python | ansible__ansible | lib/ansible/executor/task_queue_manager.py | {
"start": 2384,
"end": 2560
} | class ____:
def __init__(self, method, *args, **kwargs):
self.method = method
self.args = args
self.kwargs = kwargs
@dataclasses.dataclass
| DisplaySend |
python | zostera__django-bootstrap4 | tests/test_alerts.py | {
"start": 129,
"end": 1918
} | class ____(TestCase):
def test_render_alert_without_type(self):
self.assertEqual(
render_alert("content"),
(
'<div class="alert alert-info alert-dismissible" role="alert">'
'<button type="button" class="close" data-dismiss="alert" aria-label="close">×</button>content'
"</div>"
),
)
def test_render_alert_with_type(self):
self.assertEqual(
render_alert("content", alert_type="danger"),
(
'<div class="alert alert-danger alert-dismissible" role="alert">'
'<button type="button" class="close" data-dismiss="alert" aria-label="close">×</button>'
"content"
"</div>"
),
)
def test_render_alert_with_safe_content(self):
self.assertEqual(
render_alert(mark_safe('This is <a href="https://example.com" class="alert-link">a safe link</a>!')),
(
'<div class="alert alert-info alert-dismissible" role="alert">'
'<button type="button" class="close" data-dismiss="alert" aria-label="close">×</button>'
'This is <a href="https://example.com" class="alert-link">a safe link</a>!'
"</div>"
),
)
def test_render_alert_with_unsafe_content(self):
self.assertEqual(
render_alert("This is <b>unsafe</b>!"),
(
'<div class="alert alert-info alert-dismissible" role="alert">'
'<button type="button" class="close" data-dismiss="alert" aria-label="close">×</button>'
"This is <b>unsafe</b>!"
"</div>"
),
)
| AlertsTest |
python | django__django | tests/expressions/tests.py | {
"start": 1692,
"end": 44750
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.example_inc = Company.objects.create(
name="Example Inc.",
num_employees=2300,
num_chairs=5,
ceo=Employee.objects.create(firstname="Joe", lastname="Smith", salary=10),
)
cls.foobar_ltd = Company.objects.create(
name="Foobar Ltd.",
num_employees=3,
num_chairs=4,
based_in_eu=True,
ceo=Employee.objects.create(firstname="Frank", lastname="Meyer", salary=20),
)
cls.max = Employee.objects.create(
firstname="Max", lastname="Mustermann", salary=30
)
cls.gmbh = Company.objects.create(
name="Test GmbH", num_employees=32, num_chairs=1, ceo=cls.max
)
def setUp(self):
self.company_query = Company.objects.values(
"name", "num_employees", "num_chairs"
).order_by("name", "num_employees", "num_chairs")
def test_annotate_values_aggregate(self):
companies = (
Company.objects.annotate(
salaries=F("ceo__salary"),
)
.values("num_employees", "salaries")
.aggregate(
result=Sum(
F("salaries") + F("num_employees"), output_field=IntegerField()
),
)
)
self.assertEqual(companies["result"], 2395)
def test_annotate_values_filter(self):
companies = (
Company.objects.annotate(
foo=RawSQL("%s", ["value"]),
)
.filter(foo="value")
.order_by("name")
)
self.assertSequenceEqual(
companies,
[self.example_inc, self.foobar_ltd, self.gmbh],
)
def test_annotate_values_count(self):
companies = Company.objects.annotate(foo=RawSQL("%s", ["value"]))
self.assertEqual(companies.count(), 3)
@skipUnlessDBFeature("supports_boolean_expr_in_select_clause")
def test_filtering_on_annotate_that_uses_q(self):
self.assertEqual(
Company.objects.annotate(
num_employees_check=ExpressionWrapper(
Q(num_employees__gt=3), output_field=BooleanField()
)
)
.filter(num_employees_check=True)
.count(),
2,
)
def test_filtering_on_q_that_is_boolean(self):
self.assertEqual(
Company.objects.filter(
ExpressionWrapper(Q(num_employees__gt=3), output_field=BooleanField())
).count(),
2,
)
def test_filtering_on_rawsql_that_is_boolean(self):
self.assertEqual(
Company.objects.filter(
RawSQL("num_employees > %s", (3,), output_field=BooleanField()),
).count(),
2,
)
def test_filter_inter_attribute(self):
# We can filter on attribute relationships on same model obj, e.g.
# find companies where the number of employees is greater
# than the number of chairs.
self.assertSequenceEqual(
self.company_query.filter(num_employees__gt=F("num_chairs")),
[
{
"num_chairs": 5,
"name": "Example Inc.",
"num_employees": 2300,
},
{"num_chairs": 1, "name": "Test GmbH", "num_employees": 32},
],
)
def test_update(self):
# We can set one field to have the value of another field
# Make sure we have enough chairs
self.company_query.update(num_chairs=F("num_employees"))
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 2300, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 3, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 32, "name": "Test GmbH", "num_employees": 32},
],
)
def _test_slicing_of_f_expressions(self, model):
tests = [
(F("name")[:], "Example Inc."),
(F("name")[:7], "Example"),
(F("name")[:6][:5], "Examp"), # Nested slicing.
(F("name")[0], "E"),
(F("name")[13], ""),
(F("name")[8:], "Inc."),
(F("name")[0:15], "Example Inc."),
(F("name")[2:7], "ample"),
(F("name")[1:][:3], "xam"),
(F("name")[2:2], ""),
]
for expression, expected in tests:
with self.subTest(expression=expression, expected=expected):
obj = model.objects.get(name="Example Inc.")
try:
obj.name = expression
obj.save(update_fields=["name"])
obj.refresh_from_db()
self.assertEqual(obj.name, expected)
finally:
obj.name = "Example Inc."
obj.save(update_fields=["name"])
def test_slicing_of_f_expressions_charfield(self):
self._test_slicing_of_f_expressions(Company)
def test_slicing_of_f_expressions_textfield(self):
Text.objects.bulk_create(
[Text(name=company.name) for company in Company.objects.all()]
)
self._test_slicing_of_f_expressions(Text)
def test_slicing_of_f_expressions_with_annotate(self):
qs = Company.objects.annotate(
first_three=F("name")[:3],
after_three=F("name")[3:],
random_four=F("name")[2:5],
first_letter_slice=F("name")[:1],
first_letter_index=F("name")[0],
)
tests = [
("first_three", ["Exa", "Foo", "Tes"]),
("after_three", ["mple Inc.", "bar Ltd.", "t GmbH"]),
("random_four", ["amp", "oba", "st "]),
("first_letter_slice", ["E", "F", "T"]),
("first_letter_index", ["E", "F", "T"]),
]
for annotation, expected in tests:
with self.subTest(annotation):
self.assertCountEqual(qs.values_list(annotation, flat=True), expected)
def test_slicing_of_f_expression_with_annotated_expression(self):
qs = Company.objects.annotate(
new_name=Case(
When(based_in_eu=True, then=Concat(Value("EU:"), F("name"))),
default=F("name"),
),
first_two=F("new_name")[:3],
)
self.assertCountEqual(
qs.values_list("first_two", flat=True),
["Exa", "EU:", "Tes"],
)
def test_slicing_of_f_expressions_with_negative_index(self):
msg = "Negative indexing is not supported."
indexes = [slice(0, -4), slice(-4, 0), slice(-4), -5]
for i in indexes:
with self.subTest(i=i), self.assertRaisesMessage(ValueError, msg):
F("name")[i]
def test_slicing_of_f_expressions_with_slice_stop_less_than_slice_start(self):
msg = "Slice stop must be greater than slice start."
with self.assertRaisesMessage(ValueError, msg):
F("name")[4:2]
def test_slicing_of_f_expressions_with_invalid_type(self):
msg = "Argument to slice must be either int or slice instance."
with self.assertRaisesMessage(TypeError, msg):
F("name")["error"]
def test_slicing_of_f_expressions_with_step(self):
msg = "Step argument is not supported."
with self.assertRaisesMessage(ValueError, msg):
F("name")[::4]
def test_slicing_of_f_unsupported_field(self):
msg = "This field does not support slicing."
with self.assertRaisesMessage(NotSupportedError, msg):
Company.objects.update(num_chairs=F("num_chairs")[:4])
def test_slicing_of_outerref(self):
inner = Company.objects.filter(name__startswith=OuterRef("ceo__firstname")[0])
outer = Company.objects.filter(Exists(inner)).values_list("name", flat=True)
self.assertSequenceEqual(outer, ["Foobar Ltd."])
def test_arithmetic(self):
# We can perform arithmetic operations in expressions
# Make sure we have 2 spare chairs
self.company_query.update(num_chairs=F("num_employees") + 2)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 2302, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 5, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 34, "name": "Test GmbH", "num_employees": 32},
],
)
def test_order_of_operations(self):
# Law of order of operations is followed
self.company_query.update(
num_chairs=F("num_employees") + 2 * F("num_employees")
)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 6900, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 9, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 96, "name": "Test GmbH", "num_employees": 32},
],
)
def test_parenthesis_priority(self):
# Law of order of operations can be overridden by parentheses
self.company_query.update(
num_chairs=(F("num_employees") + 2) * F("num_employees")
)
self.assertSequenceEqual(
self.company_query,
[
{"num_chairs": 5294600, "name": "Example Inc.", "num_employees": 2300},
{"num_chairs": 15, "name": "Foobar Ltd.", "num_employees": 3},
{"num_chairs": 1088, "name": "Test GmbH", "num_employees": 32},
],
)
def test_update_with_fk(self):
# ForeignKey can become updated with the value of another ForeignKey.
self.assertEqual(Company.objects.update(point_of_contact=F("ceo")), 3)
self.assertQuerySetEqual(
Company.objects.all(),
["Joe Smith", "Frank Meyer", "Max Mustermann"],
lambda c: str(c.point_of_contact),
ordered=False,
)
def test_update_with_none(self):
Number.objects.create(integer=1, float=1.0)
Number.objects.create(integer=2)
Number.objects.filter(float__isnull=False).update(float=Value(None))
self.assertQuerySetEqual(
Number.objects.all(), [None, None], lambda n: n.float, ordered=False
)
@skipUnlessDBFeature("supports_json_field")
def test_update_jsonfield_case_when_key_is_null(self):
obj = JSONFieldModel.objects.create(data={"key": None})
updated = JSONFieldModel.objects.update(
data=Case(
When(
data__key=Value(None, JSONField()),
then=Value({"key": "something"}, JSONField()),
),
)
)
self.assertEqual(updated, 1)
obj.refresh_from_db()
self.assertEqual(obj.data, {"key": "something"})
def test_filter_with_join(self):
# F Expressions can also span joins
Company.objects.update(point_of_contact=F("ceo"))
c = Company.objects.first()
c.point_of_contact = Employee.objects.create(
firstname="Guido", lastname="van Rossum"
)
c.save()
self.assertQuerySetEqual(
Company.objects.filter(ceo__firstname=F("point_of_contact__firstname")),
["Foobar Ltd.", "Test GmbH"],
lambda c: c.name,
ordered=False,
)
Company.objects.exclude(ceo__firstname=F("point_of_contact__firstname")).update(
name="foo"
)
self.assertEqual(
Company.objects.exclude(ceo__firstname=F("point_of_contact__firstname"))
.get()
.name,
"foo",
)
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
Company.objects.exclude(
ceo__firstname=F("point_of_contact__firstname")
).update(name=F("point_of_contact__lastname"))
def test_object_update(self):
# F expressions can be used to update attributes on single objects
self.gmbh.num_employees = F("num_employees") + 4
self.gmbh.save()
expected_num_queries = (
0 if connection.features.can_return_rows_from_update else 1
)
with self.assertNumQueries(expected_num_queries):
self.assertEqual(self.gmbh.num_employees, 36)
def test_new_object_save(self):
# We should be able to use Funcs when inserting new data
test_co = Company(
name=Lower(Value("UPPER")), num_employees=32, num_chairs=1, ceo=self.max
)
test_co.save()
test_co.refresh_from_db()
self.assertEqual(test_co.name, "upper")
def test_new_object_create(self):
test_co = Company.objects.create(
name=Lower(Value("UPPER")), num_employees=32, num_chairs=1, ceo=self.max
)
test_co.refresh_from_db()
self.assertEqual(test_co.name, "upper")
def test_object_create_with_aggregate(self):
# Aggregates are not allowed when inserting new data
msg = (
"Aggregate functions are not allowed in this query "
"(num_employees=Max(Value(1)))."
)
with self.assertRaisesMessage(FieldError, msg):
Company.objects.create(
name="Company",
num_employees=Max(Value(1)),
num_chairs=1,
ceo=Employee.objects.create(
firstname="Just", lastname="Doit", salary=30
),
)
def test_object_update_fk(self):
# F expressions cannot be used to update attributes which are foreign
# keys, or attributes which involve joins.
test_gmbh = Company.objects.get(pk=self.gmbh.pk)
msg = 'F(ceo)": "Company.point_of_contact" must be a "Employee" instance.'
with self.assertRaisesMessage(ValueError, msg):
test_gmbh.point_of_contact = F("ceo")
test_gmbh.point_of_contact = self.gmbh.ceo
test_gmbh.save()
test_gmbh.name = F("ceo__lastname")
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
test_gmbh.save()
def test_update_inherited_field_value(self):
msg = "Joined field references are not permitted in this query"
with self.assertRaisesMessage(FieldError, msg):
RemoteEmployee.objects.update(adjusted_salary=F("salary") * 5)
def test_object_update_unsaved_objects(self):
# F expressions cannot be used to update attributes on objects which do
# not yet exist in the database
acme = Company(
name="The Acme Widget Co.", num_employees=12, num_chairs=5, ceo=self.max
)
acme.num_employees = F("num_employees") + 16
msg = (
'Failed to insert expression "Col(expressions_company, '
'expressions.Company.num_employees) + Value(16)" on '
"expressions.Company.num_employees. F() expressions can only be "
"used to update, not to insert."
)
with self.assertRaisesMessage(ValueError, msg):
acme.save()
acme.num_employees = 12
acme.name = Lower(F("name"))
msg = (
'Failed to insert expression "Lower(Col(expressions_company, '
'expressions.Company.name))" on expressions.Company.name. F() '
"expressions can only be used to update, not to insert."
)
with self.assertRaisesMessage(ValueError, msg):
acme.save()
def test_ticket_11722_iexact_lookup(self):
Employee.objects.create(firstname="John", lastname="Doe")
test = Employee.objects.create(firstname="Test", lastname="test")
queryset = Employee.objects.filter(firstname__iexact=F("lastname"))
self.assertSequenceEqual(queryset, [test])
def test_ticket_16731_startswith_lookup(self):
Employee.objects.create(firstname="John", lastname="Doe")
e2 = Employee.objects.create(firstname="Jack", lastname="Jackson")
e3 = Employee.objects.create(firstname="Jack", lastname="jackson")
self.assertSequenceEqual(
Employee.objects.filter(lastname__startswith=F("firstname")),
[e2, e3] if connection.features.has_case_insensitive_like else [e2],
)
qs = Employee.objects.filter(lastname__istartswith=F("firstname")).order_by(
"pk"
)
self.assertSequenceEqual(qs, [e2, e3])
def test_ticket_18375_join_reuse(self):
# Reverse multijoin F() references and the lookup target the same join.
# Pre #18375 the F() join was generated first and the lookup couldn't
# reuse that join.
qs = Employee.objects.filter(
company_ceo_set__num_chairs=F("company_ceo_set__num_employees")
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_kwarg_ordering(self):
# The next query was dict-randomization dependent - if the "gte=1"
# was seen first, then the F() will reuse the join generated by the
# gte lookup, if F() was seen first, then it generated a join the
# other lookups could not reuse.
qs = Employee.objects.filter(
company_ceo_set__num_chairs=F("company_ceo_set__num_employees"),
company_ceo_set__num_chairs__gte=1,
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_kwarg_ordering_2(self):
# Another similar case for F() than above. Now we have the same join
# in two filter kwargs, one in the lhs lookup, one in F. Here pre
# #18375 the amount of joins generated was random if dict
# randomization was enabled, that is the generated query dependent
# on which clause was seen first.
qs = Employee.objects.filter(
company_ceo_set__num_employees=F("pk"),
pk=F("company_ceo_set__num_employees"),
)
self.assertEqual(str(qs.query).count("JOIN"), 1)
def test_ticket_18375_chained_filters(self):
# F() expressions do not reuse joins from previous filter.
qs = Employee.objects.filter(company_ceo_set__num_employees=F("pk")).filter(
company_ceo_set__num_employees=F("company_ceo_set__num_employees")
)
self.assertEqual(str(qs.query).count("JOIN"), 2)
def test_order_by_exists(self):
mary = Employee.objects.create(
firstname="Mary", lastname="Mustermann", salary=20
)
mustermanns_by_seniority = Employee.objects.filter(
lastname="Mustermann"
).order_by(
# Order by whether the employee is the CEO of a company
Exists(Company.objects.filter(ceo=OuterRef("pk"))).desc()
)
self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary])
def test_order_by_multiline_sql(self):
raw_order_by = (
RawSQL(
"""
CASE WHEN num_employees > 1000
THEN num_chairs
ELSE 0 END
""",
[],
).desc(),
RawSQL(
"""
CASE WHEN num_chairs > 1
THEN 1
ELSE 0 END
""",
[],
).asc(),
)
for qs in (
Company.objects.all(),
Company.objects.distinct(),
):
with self.subTest(qs=qs):
self.assertSequenceEqual(
qs.order_by(*raw_order_by),
[self.example_inc, self.gmbh, self.foobar_ltd],
)
def test_outerref(self):
inner = Company.objects.filter(point_of_contact=OuterRef("pk"))
msg = (
"This queryset contains a reference to an outer query and may only "
"be used in a subquery."
)
with self.assertRaisesMessage(ValueError, msg):
inner.exists()
outer = Employee.objects.annotate(is_point_of_contact=Exists(inner))
self.assertIs(outer.exists(), True)
def test_exist_single_field_output_field(self):
queryset = Company.objects.values("pk")
self.assertIsInstance(Exists(queryset).output_field, BooleanField)
def test_subquery(self):
Company.objects.filter(name="Example Inc.").update(
point_of_contact=Employee.objects.get(firstname="Joe", lastname="Smith"),
ceo=self.max,
)
Employee.objects.create(firstname="Bob", lastname="Brown", salary=40)
qs = (
Employee.objects.annotate(
is_point_of_contact=Exists(
Company.objects.filter(point_of_contact=OuterRef("pk"))
),
is_not_point_of_contact=~Exists(
Company.objects.filter(point_of_contact=OuterRef("pk"))
),
is_ceo_of_small_company=Exists(
Company.objects.filter(num_employees__lt=200, ceo=OuterRef("pk"))
),
is_ceo_small_2=~~Exists(
Company.objects.filter(num_employees__lt=200, ceo=OuterRef("pk"))
),
largest_company=Subquery(
Company.objects.order_by("-num_employees")
.filter(Q(ceo=OuterRef("pk")) | Q(point_of_contact=OuterRef("pk")))
.values("name")[:1],
output_field=CharField(),
),
)
.values(
"firstname",
"is_point_of_contact",
"is_not_point_of_contact",
"is_ceo_of_small_company",
"is_ceo_small_2",
"largest_company",
)
.order_by("firstname")
)
results = list(qs)
# Could use Coalesce(subq, Value('')) instead except for the bug in
# oracledb mentioned in #23843.
bob = results[0]
if (
bob["largest_company"] == ""
and connection.features.interprets_empty_strings_as_nulls
):
bob["largest_company"] = None
self.assertEqual(
results,
[
{
"firstname": "Bob",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": False,
"is_ceo_small_2": False,
"largest_company": None,
},
{
"firstname": "Frank",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": True,
"is_ceo_small_2": True,
"largest_company": "Foobar Ltd.",
},
{
"firstname": "Joe",
"is_point_of_contact": True,
"is_not_point_of_contact": False,
"is_ceo_of_small_company": False,
"is_ceo_small_2": False,
"largest_company": "Example Inc.",
},
{
"firstname": "Max",
"is_point_of_contact": False,
"is_not_point_of_contact": True,
"is_ceo_of_small_company": True,
"is_ceo_small_2": True,
"largest_company": "Example Inc.",
},
],
)
# A less elegant way to write the same query: this uses a LEFT OUTER
# JOIN and an IS NULL, inside a WHERE NOT IN which is probably less
# efficient than EXISTS.
self.assertCountEqual(
qs.filter(is_point_of_contact=True).values("pk"),
Employee.objects.exclude(company_point_of_contact_set=None).values("pk"),
)
def test_subquery_eq(self):
qs = Employee.objects.annotate(
is_ceo=Exists(Company.objects.filter(ceo=OuterRef("pk"))),
is_point_of_contact=Exists(
Company.objects.filter(point_of_contact=OuterRef("pk")),
),
small_company=Exists(
queryset=Company.objects.filter(num_employees__lt=200),
),
).filter(is_ceo=True, is_point_of_contact=False, small_company=True)
self.assertNotEqual(
qs.query.annotations["is_ceo"],
qs.query.annotations["is_point_of_contact"],
)
self.assertNotEqual(
qs.query.annotations["is_ceo"],
qs.query.annotations["small_company"],
)
def test_subquery_sql(self):
employees = Employee.objects.all()
employees_subquery = Subquery(employees)
self.assertIs(employees_subquery.query.subquery, True)
self.assertIs(employees.query.subquery, False)
compiler = employees_subquery.query.get_compiler(connection=connection)
sql, _ = employees_subquery.as_sql(compiler, connection)
self.assertIn("(SELECT ", sql)
def test_in_subquery(self):
# This is a contrived test (and you really wouldn't write this query),
# but it is a succinct way to test the __in=Subquery() construct.
small_companies = Company.objects.filter(num_employees__lt=200).values("pk")
subquery_test = Company.objects.filter(pk__in=Subquery(small_companies))
self.assertCountEqual(subquery_test, [self.foobar_ltd, self.gmbh])
subquery_test2 = Company.objects.filter(
pk=Subquery(small_companies.filter(num_employees=3)[:1])
)
self.assertCountEqual(subquery_test2, [self.foobar_ltd])
def test_lookups_subquery(self):
smallest_company = Company.objects.order_by("num_employees").values("name")[:1]
for lookup in CharField.get_lookups():
if lookup == "isnull":
continue # not allowed, rhs must be a literal boolean.
if (
lookup == "in"
and not connection.features.allow_sliced_subqueries_with_in
):
continue
if lookup == "range":
rhs = (Subquery(smallest_company), Subquery(smallest_company))
else:
rhs = Subquery(smallest_company)
with self.subTest(lookup=lookup):
qs = Company.objects.filter(**{f"name__{lookup}": rhs})
self.assertGreater(len(qs), 0)
def test_uuid_pk_subquery(self):
u = UUIDPK.objects.create()
UUID.objects.create(uuid_fk=u)
qs = UUIDPK.objects.filter(id__in=Subquery(UUID.objects.values("uuid_fk__id")))
self.assertCountEqual(qs, [u])
def test_nested_subquery(self):
inner = Company.objects.filter(point_of_contact=OuterRef("pk"))
outer = Employee.objects.annotate(is_point_of_contact=Exists(inner))
contrived = Employee.objects.annotate(
is_point_of_contact=Subquery(
outer.filter(pk=OuterRef("pk")).values("is_point_of_contact"),
output_field=BooleanField(),
),
)
self.assertCountEqual(contrived.values_list(), outer.values_list())
def test_nested_subquery_join_outer_ref(self):
inner = Employee.objects.filter(pk=OuterRef("ceo__pk")).values("pk")
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
ceo__in=inner,
ceo__pk=OuterRef("pk"),
).values("pk"),
),
)
self.assertSequenceEqual(
qs.values_list("ceo_company", flat=True),
[self.example_inc.pk, self.foobar_ltd.pk, self.gmbh.pk],
)
def test_nested_subquery_outer_ref_2(self):
first = Time.objects.create(time="09:00")
second = Time.objects.create(time="17:00")
third = Time.objects.create(time="21:00")
SimulationRun.objects.bulk_create(
[
SimulationRun(start=first, end=second, midpoint="12:00"),
SimulationRun(start=first, end=third, midpoint="15:00"),
SimulationRun(start=second, end=first, midpoint="00:00"),
]
)
inner = Time.objects.filter(
time=OuterRef(OuterRef("time")), pk=OuterRef("start")
).values("time")
middle = SimulationRun.objects.annotate(other=Subquery(inner)).values("other")[
:1
]
outer = Time.objects.annotate(other=Subquery(middle, output_field=TimeField()))
# This is a contrived example. It exercises the double OuterRef form.
self.assertCountEqual(outer, [first, second, third])
def test_nested_subquery_outer_ref_with_autofield(self):
first = Time.objects.create(time="09:00")
second = Time.objects.create(time="17:00")
SimulationRun.objects.create(start=first, end=second, midpoint="12:00")
inner = SimulationRun.objects.filter(start=OuterRef(OuterRef("pk"))).values(
"start"
)
middle = Time.objects.annotate(other=Subquery(inner)).values("other")[:1]
outer = Time.objects.annotate(
other=Subquery(middle, output_field=IntegerField())
)
# This exercises the double OuterRef form with AutoField as pk.
self.assertCountEqual(outer, [first, second])
def test_annotations_within_subquery(self):
Company.objects.filter(num_employees__lt=50).update(
ceo=Employee.objects.get(firstname="Frank")
)
inner = (
Company.objects.filter(ceo=OuterRef("pk"))
.values("ceo")
.annotate(total_employees=Sum("num_employees"))
.values("total_employees")
)
outer = Employee.objects.annotate(total_employees=Subquery(inner)).filter(
salary__lte=Subquery(inner)
)
self.assertSequenceEqual(
outer.order_by("-total_employees").values("salary", "total_employees"),
[
{"salary": 10, "total_employees": 2300},
{"salary": 20, "total_employees": 35},
],
)
def test_subquery_references_joined_table_twice(self):
inner = Company.objects.filter(
num_chairs__gte=OuterRef("ceo__salary"),
num_employees__gte=OuterRef("point_of_contact__salary"),
)
# Another contrived example (there is no need to have a subquery here)
outer = Company.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertFalse(outer.exists())
def test_subquery_filter_by_aggregate(self):
Number.objects.create(integer=1000, float=1.2)
Employee.objects.create(salary=1000)
qs = Number.objects.annotate(
min_valuable_count=Subquery(
Employee.objects.filter(
salary=OuterRef("integer"),
)
.annotate(cnt=Count("salary"))
.filter(cnt__gt=0)
.values("cnt")[:1]
),
)
self.assertEqual(qs.get().float, 1.2)
def test_subquery_filter_by_lazy(self):
self.max.manager = Manager.objects.create(name="Manager")
self.max.save()
max_manager = SimpleLazyObject(
lambda: Manager.objects.get(pk=self.max.manager.pk)
)
qs = Company.objects.annotate(
ceo_manager=Subquery(
Employee.objects.filter(
lastname=OuterRef("ceo__lastname"),
).values("manager"),
),
).filter(ceo_manager=max_manager)
self.assertEqual(qs.get(), self.gmbh)
def test_aggregate_subquery_annotation(self):
with self.assertNumQueries(1) as ctx:
aggregate = Company.objects.annotate(
ceo_salary=Subquery(
Employee.objects.filter(
id=OuterRef("ceo_id"),
).values("salary")
),
).aggregate(
ceo_salary_gt_20=Count("pk", filter=Q(ceo_salary__gt=20)),
)
self.assertEqual(aggregate, {"ceo_salary_gt_20": 1})
# Aggregation over a subquery annotation doesn't annotate the subquery
# twice in the inner query.
sql = ctx.captured_queries[0]["sql"]
self.assertLessEqual(sql.count("SELECT"), 3)
# GROUP BY isn't required to aggregate over a query that doesn't
# contain nested aggregates.
self.assertNotIn("GROUP BY", sql)
def test_object_create_with_f_expression_in_subquery(self):
Company.objects.create(
name="Big company", num_employees=100000, num_chairs=1, ceo=self.max
)
biggest_company = Company.objects.create(
name="Biggest company",
num_chairs=1,
ceo=self.max,
num_employees=Subquery(
Company.objects.order_by("-num_employees")
.annotate(max_num_employees=Max("num_employees"))
.annotate(new_num_employees=F("max_num_employees") + 1)
.values("new_num_employees")[:1]
),
)
biggest_company.refresh_from_db()
self.assertEqual(biggest_company.num_employees, 100001)
@skipUnlessDBFeature("supports_over_clause")
def test_aggregate_rawsql_annotation(self):
with self.assertNumQueries(1) as ctx:
aggregate = Company.objects.annotate(
salary=RawSQL("SUM(num_chairs) OVER (ORDER BY num_employees)", []),
).aggregate(
count=Count("pk"),
)
self.assertEqual(aggregate, {"count": 3})
sql = ctx.captured_queries[0]["sql"]
self.assertNotIn("GROUP BY", sql)
def test_explicit_output_field(self):
class FuncA(Func):
output_field = CharField()
class FuncB(Func):
pass
expr = FuncB(FuncA())
self.assertEqual(expr.output_field, FuncA.output_field)
def test_outerref_mixed_case_table_name(self):
inner = Result.objects.filter(result_time__gte=OuterRef("experiment__assigned"))
outer = Result.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertFalse(outer.exists())
def test_outerref_with_operator(self):
inner = Company.objects.filter(num_employees=OuterRef("ceo__salary") + 2)
outer = Company.objects.filter(pk__in=Subquery(inner.values("pk")))
self.assertEqual(outer.get().name, "Test GmbH")
def test_nested_outerref_with_function(self):
self.gmbh.point_of_contact = Employee.objects.get(lastname="Meyer")
self.gmbh.save()
inner = Employee.objects.filter(
lastname__startswith=Left(OuterRef(OuterRef("lastname")), 1),
)
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
point_of_contact__in=inner,
ceo__pk=OuterRef("pk"),
).values("name"),
),
).filter(ceo_company__isnull=False)
self.assertEqual(qs.get().ceo_company, "Test GmbH")
def test_annotation_with_outerref(self):
gmbh_salary = Company.objects.annotate(
max_ceo_salary_raise=Subquery(
Company.objects.annotate(
salary_raise=OuterRef("num_employees") + F("num_employees"),
)
.order_by("-salary_raise")
.values("salary_raise")[:1],
),
).get(pk=self.gmbh.pk)
self.assertEqual(gmbh_salary.max_ceo_salary_raise, 2332)
def test_annotation_with_outerref_and_output_field(self):
gmbh_salary = Company.objects.annotate(
max_ceo_salary_raise=Subquery(
Company.objects.annotate(
salary_raise=OuterRef("num_employees") + F("num_employees"),
)
.order_by("-salary_raise")
.values("salary_raise")[:1],
output_field=DecimalField(),
),
).get(pk=self.gmbh.pk)
self.assertEqual(gmbh_salary.max_ceo_salary_raise, 2332.0)
self.assertIsInstance(gmbh_salary.max_ceo_salary_raise, Decimal)
def test_annotation_with_nested_outerref(self):
self.gmbh.point_of_contact = Employee.objects.get(lastname="Meyer")
self.gmbh.save()
inner = Employee.objects.annotate(
outer_lastname=OuterRef(OuterRef("lastname")),
).filter(lastname__startswith=Left("outer_lastname", 1))
qs = Employee.objects.annotate(
ceo_company=Subquery(
Company.objects.filter(
point_of_contact__in=inner,
ceo__pk=OuterRef("pk"),
).values("name"),
),
).filter(ceo_company__isnull=False)
self.assertEqual(qs.get().ceo_company, "Test GmbH")
def test_annotation_with_deeply_nested_outerref(self):
bob = Employee.objects.create(firstname="Bob", based_in_eu=True)
self.max.manager = Manager.objects.create(name="Rock", secretary=bob)
self.max.save()
qs = Employee.objects.filter(
Exists(
Manager.objects.filter(
Exists(
Employee.objects.filter(
pk=OuterRef("secretary__pk"),
)
.annotate(
secretary_based_in_eu=OuterRef(OuterRef("based_in_eu"))
)
.filter(
Exists(
Company.objects.filter(
# Inner OuterRef refers to an outer
# OuterRef (not ResolvedOuterRef).
based_in_eu=OuterRef("secretary_based_in_eu")
)
)
)
),
secretary__pk=OuterRef("pk"),
)
)
)
self.assertEqual(qs.get(), bob)
def test_pickle_expression(self):
expr = Value(1)
expr.convert_value # populate cached property
self.assertEqual(pickle.loads(pickle.dumps(expr)), expr)
def test_incorrect_field_in_F_expression(self):
with self.assertRaisesMessage(
FieldError, "Cannot resolve keyword 'nope' into field."
):
list(Employee.objects.filter(firstname=F("nope")))
def test_incorrect_joined_field_in_F_expression(self):
with self.assertRaisesMessage(
FieldError, "Cannot resolve keyword 'nope' into field."
):
list(Company.objects.filter(ceo__pk=F("point_of_contact__nope")))
def test_exists_in_filter(self):
inner = Company.objects.filter(ceo=OuterRef("pk")).values("pk")
qs1 = Employee.objects.filter(Exists(inner))
qs2 = Employee.objects.annotate(found=Exists(inner)).filter(found=True)
self.assertCountEqual(qs1, qs2)
self.assertFalse(Employee.objects.exclude(Exists(inner)).exists())
self.assertCountEqual(qs2, Employee.objects.exclude(~Exists(inner)))
def test_subquery_in_filter(self):
inner = Company.objects.filter(ceo=OuterRef("pk")).values("based_in_eu")
self.assertSequenceEqual(
Employee.objects.filter(Subquery(inner)),
[self.foobar_ltd.ceo],
)
def test_subquery_group_by_outerref_in_filter(self):
inner = (
Company.objects.annotate(
employee=OuterRef("pk"),
)
.values("employee")
.annotate(
min_num_chairs=Min("num_chairs"),
)
.values("ceo")
)
self.assertIs(Employee.objects.filter(pk__in=Subquery(inner)).exists(), True)
def test_case_in_filter_if_boolean_output_field(self):
is_ceo = Company.objects.filter(ceo=OuterRef("pk"))
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
qs = Employee.objects.filter(
Case(
When(Exists(is_ceo), then=True),
When(Exists(is_poc), then=True),
default=False,
output_field=BooleanField(),
),
)
self.assertCountEqual(qs, [self.example_inc.ceo, self.foobar_ltd.ceo, self.max])
def test_boolean_expression_combined(self):
is_ceo = Company.objects.filter(ceo=OuterRef("pk"))
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) | Exists(is_poc)),
[self.example_inc.ceo, self.foobar_ltd.ceo, self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) & Exists(is_poc)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_ceo) & Q(salary__gte=30)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Exists(is_poc) | Q(salary__lt=15)),
[self.example_inc.ceo, self.max],
)
self.assertCountEqual(
Employee.objects.filter(Q(salary__gte=30) & Exists(is_ceo)),
[self.max],
)
self.assertCountEqual(
Employee.objects.filter(Q(salary__lt=15) | Exists(is_poc)),
[self.example_inc.ceo, self.max],
)
def test_boolean_expression_combined_with_empty_Q(self):
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
tests = [
Exists(is_poc) & Q(),
Q() & Exists(is_poc),
Exists(is_poc) | Q(),
Q() | Exists(is_poc),
Q(Exists(is_poc)) & Q(),
Q() & Q(Exists(is_poc)),
Q(Exists(is_poc)) | Q(),
Q() | Q(Exists(is_poc)),
]
for conditions in tests:
with self.subTest(conditions):
self.assertCountEqual(Employee.objects.filter(conditions), [self.max])
def test_boolean_expression_in_Q(self):
is_poc = Company.objects.filter(point_of_contact=OuterRef("pk"))
self.gmbh.point_of_contact = self.max
self.gmbh.save()
self.assertCountEqual(Employee.objects.filter(Q(Exists(is_poc))), [self.max])
| BasicExpressionsTests |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 5231,
"end": 5624
} | class ____(BaseException):
"""Raise when the task execution is terminated."""
# Important to inherit BaseException instead of AirflowException->Exception, since this Exception is used
# to explicitly interrupt ongoing task. Code that does normal error-handling should not treat
# such interrupt as an error that can be handled normally. (Compare with KeyboardInterrupt)
| AirflowTaskTerminated |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_us_state_or_territory_abbreviation.py | {
"start": 1940,
"end": 4945
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid state or territory abbreviations.
See https://pypi.org/project/us/ for more information.
DC statehood is a perennial issue in data science, and the owners of the us repo addressed it differently than we have: https://github.com/unitedstates/python-us/issues/50
dc_statehood defaults to True, though can be overriden by end users
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"valid_state_or_territory_abbreviation": [
"KS",
"AS",
"GU",
"PR",
"VI",
"MP",
],
"invalid_state_or_territory_abbreviation": [
"",
"1234",
"WVV",
"AA",
"WX",
"2V",
],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "valid_state_or_territory_abbreviation"},
"out": {"success": True},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {"column": "invalid_state_or_territory_abbreviation"},
"out": {"success": False},
},
],
}
]
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.valid_state_or_territory_abbreviation"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
success_keys = ("mostly",)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {}
# This object contains metadata for display in the public Gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"hackathon",
"typed-entities",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73", # Don't forget to add your github handle here!
],
"requirements": ["us"],
}
if __name__ == "__main__":
ExpectColumnValuesToBeValidUSStateOrTerritoryAbbreviation().print_diagnostic_checklist()
| ExpectColumnValuesToBeValidUSStateOrTerritoryAbbreviation |
python | jpadilla__pyjwt | tests/test_advisory.py | {
"start": 851,
"end": 5091
} | class ____:
@crypto_required
def test_ghsa_ffqj_6fqr_9h24(self):
# Generate ed25519 private key
# private_key = ed25519.Ed25519PrivateKey.generate()
# Get private key bytes as they would be stored in a file
# priv_key_bytes = private_key.private_bytes(
# encoding=serialization.Encoding.PEM,
# format=serialization.PrivateFormat.PKCS8,
# encryption_algorithm=serialization.NoEncryption(),
# )
# Get public key bytes as they would be stored in a file
# pub_key_bytes = private_key.public_key().public_bytes(
# encoding=serialization.Encoding.OpenSSH,
# format=serialization.PublicFormat.OpenSSH,
# )
# Making a good jwt token that should work by signing it
# with the private key
# encoded_good = jwt.encode({"test": 1234}, priv_key_bytes, algorithm="EdDSA")
encoded_good = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJ0ZXN0IjoxMjM0fQ.M5y1EEavZkHSlj9i8yi9nXKKyPBSAUhDRTOYZi3zZY11tZItDaR3qwAye8pc74_lZY3Ogt9KPNFbVOSGnUBHDg"
# Using HMAC with the public key to trick the receiver to think that the
# public key is a HMAC secret
encoded_bad = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0ZXN0IjoxMjM0fQ.6ulDpqSlbHmQ8bZXhZRLFko9SwcHrghCwh8d-exJEE4"
algorithm_names = list(get_default_algorithms())
# Both of the jwt tokens are validated as valid
jwt.decode(
encoded_good,
pub_key_bytes,
algorithms=algorithm_names,
)
with pytest.raises(InvalidKeyError):
jwt.decode(
encoded_bad,
pub_key_bytes,
algorithms=algorithm_names,
)
# Of course the receiver should specify ed25519 algorithm to be used if
# they specify ed25519 public key. However, if other algorithms are used,
# the POC does not work
# HMAC specifies illegal strings for the HMAC secret in jwt/algorithms.py
#
# invalid_str ings = [
# b"-----BEGIN PUBLIC KEY-----",
# b"-----BEGIN CERTIFICATE-----",
# b"-----BEGIN RSA PUBLIC KEY-----",
# b"ssh-rsa",
# ]
#
# However, OKPAlgorithm (ed25519) accepts the following in jwt/algorithms.py:
#
# if "-----BEGIN PUBLIC" in str_key:
# return load_pem_public_key(key)
# if "-----BEGIN PRIVATE" in str_key:
# return load_pem_private_key(key, password=None)
# if str_key[0:4] == "ssh-":
# return load_ssh_public_key(key)
#
# These should most likely made to match each other to prevent this behavior
# POC for the ecdsa-sha2-nistp256 format.
# openssl ecparam -genkey -name prime256v1 -noout -out ec256-key-priv.pem
# openssl ec -in ec256-key-priv.pem -pubout > ec256-key-pub.pem
# ssh-keygen -y -f ec256-key-priv.pem > ec256-key-ssh.pub
# Making a good jwt token that should work by signing it with the private key
# encoded_good = jwt.encode({"test": 1234}, ssh_priv_key_bytes, algorithm="ES256")
encoded_good = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoxMjM0fQ.NX42mS8cNqYoL3FOW9ZcKw8Nfq2mb6GqJVADeMA1-kyHAclilYo_edhdM_5eav9tBRQTlL0XMeu_WFE_mz3OXg"
# Using HMAC with the ssh public key to trick the receiver to think that the public key is a HMAC secret
# encoded_bad = jwt.encode({"test": 1234}, ssh_key_bytes, algorithm="HS256")
encoded_bad = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0ZXN0IjoxMjM0fQ.5eYfbrbeGYmWfypQ6rMWXNZ8bdHcqKng5GPr9MJZITU"
algorithm_names = list(get_default_algorithms())
# Both of the jwt tokens are validated as valid
jwt.decode(
encoded_good,
ssh_key_bytes,
algorithms=algorithm_names,
)
with pytest.raises(InvalidKeyError):
jwt.decode(
encoded_bad,
ssh_key_bytes,
algorithms=algorithm_names,
)
| TestAdvisory |
python | PyCQA__pylint | pylint/lint/run.py | {
"start": 9617,
"end": 9894
} | class ____(Run):
"""A private wrapper for the 'pylint-config' command."""
_is_pylint_config: ClassVar[bool] = True
"""Boolean whether or not this is a 'pylint-config' run.
Used by _PylintConfigRun to make the 'pylint-config' command work.
"""
| _PylintConfigRun |
python | PyCQA__pylint | pylint/utils/linterstats.py | {
"start": 362,
"end": 730
} | class ____(TypedDict):
"""TypedDict to store counts of node types with bad names."""
argument: int
attr: int
klass: int
class_attribute: int
class_const: int
const: int
inlinevar: int
function: int
method: int
module: int
variable: int
typevar: int
paramspec: int
typevartuple: int
typealias: int
| BadNames |
python | wandb__wandb | wandb/apis/importers/mlflow.py | {
"start": 4735,
"end": 8257
} | class ____:
def __init__(
self,
dst_base_url: str,
dst_api_key: str,
mlflow_tracking_uri: str,
mlflow_registry_uri: Optional[str] = None,
*,
custom_api_kwargs: Optional[Dict[str, Any]] = None,
) -> None:
self.dst_base_url = dst_base_url
self.dst_api_key = dst_api_key
if custom_api_kwargs is None:
custom_api_kwargs = {"timeout": 600}
self.dst_api = wandb.Api(
api_key=dst_api_key,
overrides={"base_url": dst_base_url},
**custom_api_kwargs,
)
self.mlflow_tracking_uri = mlflow_tracking_uri
mlflow.set_tracking_uri(self.mlflow_tracking_uri)
if mlflow_registry_uri:
mlflow.set_registry_uri(mlflow_registry_uri)
self.mlflow_client = mlflow.tracking.MlflowClient(mlflow_tracking_uri)
def __repr__(self):
return f"<MlflowImporter src={self.mlflow_tracking_uri}>"
def collect_runs(self, *, limit: Optional[int] = None) -> Iterable[MlflowRun]:
if mlflow_version < Version("1.28.0"):
experiments = self.mlflow_client.list_experiments()
else:
experiments = self.mlflow_client.search_experiments()
def _runs():
for exp in experiments:
for run in self.mlflow_client.search_runs(exp.experiment_id):
yield MlflowRun(run, self.mlflow_client)
runs = itertools.islice(_runs(), limit)
yield from runs
def _import_run(
self,
run: MlflowRun,
*,
artifacts: bool = True,
namespace: Optional[Namespace] = None,
config: Optional[internal.SendManagerConfig] = None,
) -> None:
if namespace is None:
namespace = Namespace(run.entity(), run.project())
if config is None:
config = internal.SendManagerConfig(
metadata=True,
files=True,
media=True,
code=True,
history=True,
summary=True,
terminal_output=True,
)
settings_override = {
"api_key": self.dst_api_key,
"base_url": self.dst_base_url,
"resume": "allow",
"resumed": True,
}
mlflow.set_tracking_uri(self.mlflow_tracking_uri)
internal.send_run(
run,
overrides=namespace.send_manager_overrides,
settings_override=settings_override,
config=config,
)
# in mlflow, the artifacts come with the runs, so import them together
if artifacts:
arts = list(run.artifacts())
logger.debug(f"Importing history artifacts, {run=}")
internal.send_run(
run,
extra_arts=arts,
overrides=namespace.send_manager_overrides,
settings_override=settings_override,
config=internal.SendManagerConfig(log_artifacts=True),
)
def import_runs(
self,
runs: Iterable[MlflowRun],
*,
artifacts: bool = True,
namespace: Optional[Namespace] = None,
parallel: bool = True,
max_workers: Optional[int] = None,
) -> None:
def _import_run_wrapped(run):
self._import_run(run, namespace=namespace, artifacts=artifacts)
for_each(_import_run_wrapped, runs, parallel=parallel, max_workers=max_workers)
| MlflowImporter |
python | realpython__materials | hashtable/01_hashtable_prototype/08_get_the_keys_and_values/hashtable.py | {
"start": 107,
"end": 1281
} | class ____:
def __init__(self, capacity):
self._pairs = capacity * [None]
def __len__(self):
return len(self._pairs)
def __delitem__(self, key):
if key in self:
self._pairs[self._index(key)] = None
else:
raise KeyError(key)
def __setitem__(self, key, value):
self._pairs[self._index(key)] = Pair(key, value)
def __getitem__(self, key):
pair = self._pairs[self._index(key)]
if pair is None:
raise KeyError(key)
return pair.value
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
@property
def pairs(self):
return {pair for pair in self._pairs if pair}
@property
def values(self):
return [pair.value for pair in self.pairs]
@property
def keys(self):
return {pair.key for pair in self.pairs}
def _index(self, key):
return hash(key) % len(self)
| HashTable |
python | pypa__warehouse | tests/common/db/subscriptions.py | {
"start": 1006,
"end": 1343
} | class ____(WarehouseFactory):
class Meta:
model = StripeSubscriptionPrice
id = factory.Faker("uuid4", cast_to=None)
price_id = "price_123"
currency = "usd"
unit_amount = 2500
recurring = "month"
subscription_product = factory.SubFactory(StripeSubscriptionProductFactory)
| StripeSubscriptionPriceFactory |
python | walkccc__LeetCode | solutions/1301. Number of Paths with Max Score/1301.py | {
"start": 0,
"end": 1130
} | class ____:
def pathsWithMaxScore(self, board: list[str]) -> list[int]:
MOD = 1_000_000_007
DIRS = ((0, 1), (1, 0), (1, 1))
n = len(board)
# dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j)
dp = [[-1] * (n + 1) for _ in range(n + 1)]
# count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to
# (i, j)
count = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 0
dp[n - 1][n - 1] = 0
count[n - 1][n - 1] = 1
for i in reversed(range(n)):
for j in reversed(range(n)):
if board[i][j] == 'S' or board[i][j] == 'X':
continue
for dx, dy in DIRS:
x = i + dx
y = j + dy
if dp[i][j] < dp[x][y]:
dp[i][j] = dp[x][y]
count[i][j] = count[x][y]
elif dp[i][j] == dp[x][y]:
count[i][j] += count[x][y]
count[i][j] %= MOD
# If there's path(s) from 'S' to (i, j) and the cell is not 'E'.
if dp[i][j] != -1 and board[i][j] != 'E':
dp[i][j] += int(board[i][j])
dp[i][j] %= MOD
return [dp[0][0], count[0][0]]
| Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink38.py | {
"start": 315,
"end": 898
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink38.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_image(
"E9", self.image_dir + "red.png", {"url": "internal:Sheet1!A1"}
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | mlflow__mlflow | mlflow/utils/databricks_utils.py | {
"start": 22881,
"end": 33582
} | class ____(DatabricksConfigProvider):
"""
TrackingURIConfigProvider extracts `scope` and `key_prefix` from tracking URI
of format like `databricks://scope:key_prefix`,
then read host and token value from dbutils secrets by key
"{key_prefix}-host" and "{key_prefix}-token"
This provider only works in Databricks runtime and it is deprecated,
in Databricks runtime you can simply use 'databricks'
as the tracking URI and MLflow can automatically read dynamic token in
Databricks runtime.
"""
def __init__(self, tracking_uri):
self.tracking_uri = tracking_uri
def get_config(self):
scope, key_prefix = get_db_info_from_uri(self.tracking_uri)
if scope and key_prefix:
if dbutils := _get_dbutils():
# Prefix differentiates users and is provided as path information in the URI
host = dbutils.secrets.get(scope=scope, key=key_prefix + "-host")
token = dbutils.secrets.get(scope=scope, key=key_prefix + "-token")
return DatabricksConfig.from_token(host=host, token=token, insecure=False)
return None
def get_databricks_host_creds(server_uri=None):
"""
Reads in configuration necessary to make HTTP requests to a Databricks server. This
uses Databricks SDK workspace client API,
If no available credential configuration is found to the server URI, this function
will attempt to retrieve these credentials from the Databricks Secret Manager. For that to work,
the server URI will need to be of the following format: "databricks://scope:prefix". In the
Databricks Secret Manager, we will query for a secret in the scope "<scope>" for secrets with
keys of the form "<prefix>-host" and "<prefix>-token". Note that this prefix *cannot* be empty
if trying to authenticate with this method. If found, those host credentials will be used. This
method will throw an exception if sufficient auth cannot be found.
Args:
server_uri: A URI that specifies the Databricks profile you want to use for making
requests.
Returns:
MlflowHostCreds which includes the hostname if databricks sdk authentication is available,
otherwise includes the hostname and authentication information necessary to
talk to the Databricks server.
.. Warning:: This API is deprecated. In the future it might be removed.
"""
if MLFLOW_ENABLE_DB_SDK.get():
from databricks.sdk import WorkspaceClient
profile, key_prefix = get_db_info_from_uri(server_uri)
profile = profile or os.environ.get("DATABRICKS_CONFIG_PROFILE")
if key_prefix is not None:
try:
config = TrackingURIConfigProvider(server_uri).get_config()
WorkspaceClient(host=config.host, token=config.token)
return MlflowHostCreds(
config.host,
token=config.token,
use_databricks_sdk=True,
use_secret_scope_token=True,
)
except Exception as e:
raise MlflowException(
f"The hostname and credentials configured by {server_uri} is invalid. "
"Please create valid hostname secret by command "
f"'databricks secrets put-secret {profile} {key_prefix}-host' and "
"create valid token secret by command "
f"'databricks secrets put-secret {profile} {key_prefix}-token'."
) from e
try:
# Using databricks-sdk to create Databricks WorkspaceClient instance,
# If authentication is failed, MLflow falls back to legacy authentication methods,
# see `SparkTaskContextConfigProvider`, `DatabricksModelServingConfigProvider`,
# and `TrackingURIConfigProvider`.
# databricks-sdk supports many kinds of authentication ways,
# it will try to read authentication information by the following ways:
# 1. Read dynamic generated token via databricks `dbutils`.
# 2. parse relevant environment variables (such as DATABRICKS_HOST + DATABRICKS_TOKEN
# or DATABRICKS_HOST + DATABRICKS_CLIENT_ID + DATABRICKS_CLIENT_SECRET)
# to get authentication information
# 3. parse ~/.databrickscfg file (generated by databricks-CLI command-line tool)
# to get authentication information.
# databricks-sdk is designed to hide authentication details and
# support various authentication ways, so that it does not provide API
# to get credential values. Instead, we can use ``WorkspaceClient``
# API to invoke databricks shard restful APIs.
WorkspaceClient(profile=profile)
use_databricks_sdk = True
databricks_auth_profile = profile
except Exception as e:
_logger.debug(f"Failed to create databricks SDK workspace client, error: {e!r}")
use_databricks_sdk = False
databricks_auth_profile = None
else:
use_databricks_sdk = False
databricks_auth_profile = None
config = _get_databricks_creds_config(server_uri)
if not config:
_fail_malformed_databricks_auth(profile)
return MlflowHostCreds(
config.host,
username=config.username,
password=config.password,
ignore_tls_verification=config.insecure,
token=config.token,
client_id=config.client_id,
client_secret=config.client_secret,
use_databricks_sdk=use_databricks_sdk,
databricks_auth_profile=databricks_auth_profile,
)
def get_databricks_workspace_client_config(server_uri: str):
from databricks.sdk import WorkspaceClient
profile, key_prefix = get_db_info_from_uri(server_uri)
profile = profile or os.environ.get("DATABRICKS_CONFIG_PROFILE")
if key_prefix is not None:
config = TrackingURIConfigProvider(server_uri).get_config()
return WorkspaceClient(host=config.host, token=config.token).config
return WorkspaceClient(profile=profile).config
@_use_repl_context_if_available("mlflowGitRepoUrl")
def get_git_repo_url():
try:
return _get_command_context().mlflowGitRepoUrl().get()
except Exception:
return _get_extra_context("mlflowGitUrl")
@_use_repl_context_if_available("mlflowGitRepoProvider")
def get_git_repo_provider():
try:
return _get_command_context().mlflowGitRepoProvider().get()
except Exception:
return _get_extra_context("mlflowGitProvider")
@_use_repl_context_if_available("mlflowGitRepoCommit")
def get_git_repo_commit():
try:
return _get_command_context().mlflowGitRepoCommit().get()
except Exception:
return _get_extra_context("mlflowGitCommit")
@_use_repl_context_if_available("mlflowGitRelativePath")
def get_git_repo_relative_path():
try:
return _get_command_context().mlflowGitRelativePath().get()
except Exception:
return _get_extra_context("mlflowGitRelativePath")
@_use_repl_context_if_available("mlflowGitRepoReference")
def get_git_repo_reference():
try:
return _get_command_context().mlflowGitRepoReference().get()
except Exception:
return _get_extra_context("mlflowGitReference")
@_use_repl_context_if_available("mlflowGitRepoReferenceType")
def get_git_repo_reference_type():
try:
return _get_command_context().mlflowGitRepoReferenceType().get()
except Exception:
return _get_extra_context("mlflowGitReferenceType")
@_use_repl_context_if_available("mlflowGitRepoStatus")
def get_git_repo_status():
try:
return _get_command_context().mlflowGitRepoStatus().get()
except Exception:
return _get_extra_context("mlflowGitStatus")
def is_running_in_ipython_environment():
try:
from IPython import get_ipython
return get_ipython() is not None
except (ImportError, ModuleNotFoundError):
return False
def get_databricks_run_url(tracking_uri: str, run_id: str, artifact_path=None) -> str | None:
"""
Obtains a Databricks URL corresponding to the specified MLflow Run, optionally referring
to an artifact within the run.
Args:
tracking_uri: The URI of the MLflow Tracking server containing the Run.
run_id: The ID of the MLflow Run for which to obtain a Databricks URL.
artifact_path: An optional relative artifact path within the Run to which the URL
should refer.
Returns:
A Databricks URL corresponding to the specified MLflow Run
(and artifact path, if specified), or None if the MLflow Run does not belong to a
Databricks Workspace.
"""
from mlflow.tracking.client import MlflowClient
try:
workspace_info = (
DatabricksWorkspaceInfo.from_environment()
or get_databricks_workspace_info_from_uri(tracking_uri)
)
if workspace_info is not None:
experiment_id = MlflowClient(tracking_uri).get_run(run_id).info.experiment_id
return _construct_databricks_run_url(
host=workspace_info.host,
experiment_id=experiment_id,
run_id=run_id,
workspace_id=workspace_info.workspace_id,
artifact_path=artifact_path,
)
except Exception:
return None
def get_databricks_model_version_url(registry_uri: str, name: str, version: str) -> str | None:
"""Obtains a Databricks URL corresponding to the specified Model Version.
Args:
registry_uri: The URI of the Model Registry server containing the Model Version.
name: The name of the registered model containing the Model Version.
version: Version number of the Model Version.
Returns:
A Databricks URL corresponding to the specified Model Version, or None if the
Model Version does not belong to a Databricks Workspace.
"""
try:
workspace_info = (
DatabricksWorkspaceInfo.from_environment()
or get_databricks_workspace_info_from_uri(registry_uri)
)
if workspace_info is not None:
return _construct_databricks_model_version_url(
host=workspace_info.host,
name=name,
version=version,
workspace_id=workspace_info.workspace_id,
)
except Exception:
return None
DatabricksWorkspaceInfoType = TypeVar("DatabricksWorkspaceInfo", bound="DatabricksWorkspaceInfo")
| TrackingURIConfigProvider |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 225717,
"end": 227024
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
domain: str,
api_key: str,
requests_per_minute: Optional[int] = None,
start_date: Optional[str] = None,
):
"""Airbyte Source for Freshdesk.
Documentation can be found at https://docs.airbyte.com/integrations/sources/freshdesk
Args:
name (str): The name of the destination.
domain (str): Freshdesk domain
api_key (str): Freshdesk API Key. See the docs for more information on how to obtain this key.
requests_per_minute (Optional[int]): The number of requests per minute that this source allowed to use. There is a rate limit of 50 requests per minute per app per account.
start_date (Optional[str]): UTC date and time. Any data created after this date will be replicated. If this parameter is not set, all data will be replicated.
"""
self.domain = check.str_param(domain, "domain")
self.api_key = check.str_param(api_key, "api_key")
self.requests_per_minute = check.opt_int_param(requests_per_minute, "requests_per_minute")
self.start_date = check.opt_str_param(start_date, "start_date")
super().__init__("Freshdesk", name)
| FreshdeskSource |
python | numba__numba | numba/cuda/tests/cudapy/test_operator.py | {
"start": 1972,
"end": 13295
} | class ____(CUDATestCase):
def setUp(self):
super().setUp()
np.random.seed(0)
"""
Test if operator module is supported by the CUDA target.
"""
def operator_template(self, op):
@cuda.jit
def foo(a, b):
i = 0
a[i] = op(a[i], b[i])
a = np.ones(1)
b = np.ones(1)
res = a.copy()
foo[1, 1](res, b)
np.testing.assert_equal(res, op(a, b))
def test_add(self):
self.operator_template(operator.add)
def test_sub(self):
self.operator_template(operator.sub)
def test_mul(self):
self.operator_template(operator.mul)
def test_truediv(self):
self.operator_template(operator.truediv)
def test_floordiv(self):
self.operator_template(operator.floordiv)
@skip_unless_cc_53
def test_fp16_binary(self):
functions = (simple_fp16add, simple_fp16sub, simple_fp16mul,
simple_fp16_div_scalar)
ops = (operator.add, operator.sub, operator.mul, operator.truediv)
for fn, op in zip(functions, ops):
with self.subTest(op=op):
kernel = cuda.jit("void(f2[:], f2, f2)")(fn)
got = np.zeros(1, dtype=np.float16)
arg1 = np.random.random(1).astype(np.float16)
arg2 = np.random.random(1).astype(np.float16)
kernel[1, 1](got, arg1[0], arg2[0])
expected = op(arg1, arg2)
np.testing.assert_allclose(got, expected)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_binary_ptx(self):
functions = (simple_fp16add, simple_fp16sub, simple_fp16mul)
instrs = ('add.f16', 'sub.f16', 'mul.f16')
args = (f2[:], f2, f2)
for fn, instr in zip(functions, instrs):
with self.subTest(instr=instr):
ptx, _ = compile_ptx(fn, args, cc=(5, 3))
self.assertIn(instr, ptx)
@skip_unless_cc_53
def test_mixed_fp16_binary_arithmetic(self):
functions = (simple_fp16add, simple_fp16sub, simple_fp16mul,
simple_fp16_div_scalar)
ops = (operator.add, operator.sub, operator.mul, operator.truediv)
types = (np.int8, np.int16, np.int32, np.int64,
np.float32, np.float64)
for (fn, op), ty in itertools.product(zip(functions, ops), types):
with self.subTest(op=op, ty=ty):
kernel = cuda.jit(fn)
arg1 = np.random.random(1).astype(np.float16)
arg2 = (np.random.random(1) * 100).astype(ty)
res_ty = np.result_type(np.float16, ty)
got = np.zeros(1, dtype=res_ty)
kernel[1, 1](got, arg1[0], arg2[0])
expected = op(arg1, arg2)
np.testing.assert_allclose(got, expected)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_inplace_binary_ptx(self):
functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul)
instrs = ('add.f16', 'sub.f16', 'mul.f16')
args = (f2[:], f2)
for fn, instr in zip(functions, instrs):
with self.subTest(instr=instr):
ptx, _ = compile_ptx(fn, args, cc=(5, 3))
self.assertIn(instr, ptx)
@skip_unless_cc_53
def test_fp16_inplace_binary(self):
functions = (simple_fp16_iadd, simple_fp16_isub, simple_fp16_imul,
simple_fp16_idiv)
ops = (operator.iadd, operator.isub, operator.imul, operator.itruediv)
for fn, op in zip(functions, ops):
with self.subTest(op=op):
kernel = cuda.jit("void(f2[:], f2)")(fn)
got = np.random.random(1).astype(np.float16)
expected = got.copy()
arg = np.random.random(1).astype(np.float16)[0]
kernel[1, 1](got, arg)
op(expected, arg)
np.testing.assert_allclose(got, expected)
@skip_unless_cc_53
def test_fp16_unary(self):
functions = (simple_fp16neg, simple_fp16abs)
ops = (operator.neg, operator.abs)
for fn, op in zip(functions, ops):
with self.subTest(op=op):
kernel = cuda.jit("void(f2[:], f2)")(fn)
got = np.zeros(1, dtype=np.float16)
arg1 = np.random.random(1).astype(np.float16)
kernel[1, 1](got, arg1[0])
expected = op(arg1)
np.testing.assert_allclose(got, expected)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_neg_ptx(self):
args = (f2[:], f2)
ptx, _ = compile_ptx(simple_fp16neg, args, cc=(5, 3))
self.assertIn('neg.f16', ptx)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_abs_ptx(self):
args = (f2[:], f2)
ptx, _ = compile_ptx(simple_fp16abs, args, cc=(5, 3))
self.assertIn('abs.f16', ptx)
@skip_unless_cc_53
def test_fp16_comparison(self):
functions = (simple_fp16_gt, simple_fp16_ge,
simple_fp16_lt, simple_fp16_le,
simple_fp16_eq, simple_fp16_ne)
ops = (operator.gt, operator.ge, operator.lt, operator.le,
operator.eq, operator.ne)
for fn, op in zip(functions, ops):
with self.subTest(op=op):
kernel = cuda.jit("void(b1[:], f2, f2)")(fn)
got = np.zeros(1, dtype=np.bool_)
arg1 = np.random.random(1).astype(np.float16)
arg2 = np.random.random(1).astype(np.float16)
kernel[1, 1](got, arg1[0], arg2[0])
expected = op(arg1, arg2)
self.assertEqual(got[0], expected)
@skip_unless_cc_53
def test_mixed_fp16_comparison(self):
functions = (simple_fp16_gt, simple_fp16_ge,
simple_fp16_lt, simple_fp16_le,
simple_fp16_eq, simple_fp16_ne)
ops = (operator.gt, operator.ge, operator.lt, operator.le,
operator.eq, operator.ne)
types = (np.int8, np.int16, np.int32, np.int64,
np.float32, np.float64)
for (fn, op), ty in itertools.product(zip(functions, ops),
types):
with self.subTest(op=op, ty=ty):
kernel = cuda.jit(fn)
got = np.zeros(1, dtype=np.bool_)
arg1 = np.random.random(1).astype(np.float16)
arg2 = (np.random.random(1) * 100).astype(ty)
kernel[1, 1](got, arg1[0], arg2[0])
expected = op(arg1, arg2)
self.assertEqual(got[0], expected)
@skip_unless_cc_53
def test_multiple_float16_comparisons(self):
functions = (test_multiple_hcmp_1,
test_multiple_hcmp_2,
test_multiple_hcmp_3,
test_multiple_hcmp_4,
test_multiple_hcmp_5)
for fn in functions:
with self.subTest(fn=fn):
compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn)
ary = np.zeros(1, dtype=np.bool_)
arg1 = np.float16(2.)
arg2 = np.float16(3.)
arg3 = np.float16(4.)
compiled[1, 1](ary, arg1, arg2, arg3)
self.assertTrue(ary[0])
@skip_unless_cc_53
def test_multiple_float16_comparisons_false(self):
functions = (test_multiple_hcmp_1,
test_multiple_hcmp_2,
test_multiple_hcmp_3,
test_multiple_hcmp_4,
test_multiple_hcmp_5)
for fn in functions:
with self.subTest(fn=fn):
compiled = cuda.jit("void(b1[:], f2, f2, f2)")(fn)
ary = np.zeros(1, dtype=np.bool_)
arg1 = np.float16(2.)
arg2 = np.float16(3.)
arg3 = np.float16(1.)
compiled[1, 1](ary, arg1, arg2, arg3)
self.assertFalse(ary[0])
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_comparison_ptx(self):
functions = (simple_fp16_gt, simple_fp16_ge,
simple_fp16_lt, simple_fp16_le,
simple_fp16_eq, simple_fp16_ne)
ops = (operator.gt, operator.ge, operator.lt, operator.le,
operator.eq, operator.ne)
opstring = ('setp.gt.f16', 'setp.ge.f16',
'setp.lt.f16', 'setp.le.f16',
'setp.eq.f16', 'setp.ne.f16')
args = (b1[:], f2, f2)
for fn, op, s in zip(functions, ops, opstring):
with self.subTest(op=op):
ptx, _ = compile_ptx(fn, args, cc=(5, 3))
self.assertIn(s, ptx)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_fp16_int8_comparison_ptx(self):
# Test that int8 can be safely converted to fp16
# in a comparison
functions = (simple_fp16_gt, simple_fp16_ge,
simple_fp16_lt, simple_fp16_le,
simple_fp16_eq, simple_fp16_ne)
ops = (operator.gt, operator.ge, operator.lt, operator.le,
operator.eq, operator.ne)
opstring = {operator.gt:'setp.gt.f16',
operator.ge:'setp.ge.f16',
operator.lt:'setp.lt.f16',
operator.le:'setp.le.f16',
operator.eq:'setp.eq.f16',
operator.ne:'setp.ne.f16'}
for fn, op in zip(functions, ops):
with self.subTest(op=op):
args = (b1[:], f2, from_dtype(np.int8))
ptx, _ = compile_ptx(fn, args, cc=(5, 3))
self.assertIn(opstring[op], ptx)
@skip_on_cudasim('Compilation unsupported in the simulator')
def test_mixed_fp16_comparison_promotion_ptx(self):
functions = (simple_fp16_gt, simple_fp16_ge,
simple_fp16_lt, simple_fp16_le,
simple_fp16_eq, simple_fp16_ne)
ops = (operator.gt, operator.ge, operator.lt, operator.le,
operator.eq, operator.ne)
types_promote = (np.int16, np.int32, np.int64,
np.float32, np.float64)
opstring = {operator.gt:'setp.gt.',
operator.ge:'setp.ge.',
operator.lt:'setp.lt.',
operator.le:'setp.le.',
operator.eq:'setp.eq.',
operator.ne:'setp.neu.'}
opsuffix = {np.dtype('int32'): 'f64',
np.dtype('int64'): 'f64',
np.dtype('float32'): 'f32',
np.dtype('float64'): 'f64'}
for (fn, op), ty in itertools.product(zip(functions, ops),
types_promote):
with self.subTest(op=op, ty=ty):
arg2_ty = np.result_type(np.float16, ty)
args = (b1[:], f2, from_dtype(arg2_ty))
ptx, _ = compile_ptx(fn, args, cc=(5, 3))
ops = opstring[op] + opsuffix[arg2_ty]
self.assertIn(ops, ptx)
if __name__ == '__main__':
unittest.main()
| TestOperatorModule |
python | streamlit__streamlit | lib/streamlit/cursor.py | {
"start": 1681,
"end": 3203
} | class ____:
"""A pointer to a delta location in the app.
When adding an element to the app, you should always call
get_locked_cursor() on that element's respective Cursor.
"""
def __repr__(self) -> str:
return util.repr_(self)
@property
def root_container(self) -> int:
"""The top-level container this cursor lives within - either
RootContainer.MAIN or RootContainer.SIDEBAR.
"""
raise NotImplementedError()
@property
def parent_path(self) -> tuple[int, ...]:
"""The cursor's parent's path within its container."""
raise NotImplementedError()
@property
def index(self) -> int:
"""The index of the Delta within its parent block."""
raise NotImplementedError()
@property
def delta_path(self) -> list[int]:
"""The complete path of the delta pointed to by this cursor - its
container, parent path, and index.
"""
return make_delta_path(self.root_container, self.parent_path, self.index)
@property
def is_locked(self) -> bool:
raise NotImplementedError()
def get_locked_cursor(self, **props: Any) -> LockedCursor:
raise NotImplementedError()
@property
def props(self) -> Any:
"""Other data in this cursor. This is a temporary measure that will go
away when we implement improved return values for elements.
This is only implemented in LockedCursor.
"""
raise NotImplementedError()
| Cursor |
python | PrefectHQ__prefect | tests/_internal/pydantic/test_validated_func.py | {
"start": 16376,
"end": 16788
} | class ____(BaseModel):
a: B = Field()
def process_model(model: A):
return model
""",
namespace,
)
# At this point, B doesn't exist yet. Creating ValidatedFunction should not fail
# (it should defer the model rebuild until validation time)
vf = ValidatedFunction(namespace["process_model"])
# Now define B in the namespace
exec(
"""
| A |
python | python-openxml__python-docx | src/docx/image/jpeg.py | {
"start": 316,
"end": 707
} | class ____(BaseImageHeader):
"""Base class for JFIF and EXIF subclasses."""
@property
def content_type(self):
"""MIME content type for this image, unconditionally `image/jpeg` for JPEG
images."""
return MIME_TYPE.JPEG
@property
def default_ext(self):
"""Default filename extension, always 'jpg' for JPG images."""
return "jpg"
| Jpeg |
python | ray-project__ray | python/ray/tune/context.py | {
"start": 852,
"end": 3887
} | class ____(TrainV1Context):
"""Context to access metadata within Ray Tune functions."""
# NOTE: These methods are deprecated on the TrainContext, but are still
# available on the TuneContext. Re-defining them here to avoid the
# deprecation warnings.
@_copy_doc(session.get_trial_name)
def get_trial_name(self) -> str:
return session.get_trial_name()
@_copy_doc(session.get_trial_id)
def get_trial_id(self) -> str:
return session.get_trial_id()
@_copy_doc(session.get_trial_resources)
def get_trial_resources(self) -> PlacementGroupFactory:
return session.get_trial_resources()
@_copy_doc(session.get_trial_dir)
def get_trial_dir(self) -> str:
return session.get_trial_dir()
# Deprecated APIs
@Deprecated
def get_metadata(self) -> Dict[str, Any]:
raise DeprecationWarning(
"`get_metadata` is deprecated for Ray Tune, as it has never been usable."
)
@Deprecated(
message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_size"),
warning=_v2_migration_warnings_enabled(),
)
@_copy_doc(TrainV1Context.get_world_size)
def get_world_size(self) -> int:
return session.get_world_size()
@Deprecated(
message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_rank"),
warning=_v2_migration_warnings_enabled(),
)
@_copy_doc(TrainV1Context.get_world_rank)
def get_world_rank(self) -> int:
return session.get_world_rank()
@Deprecated(
message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_local_rank"),
warning=_v2_migration_warnings_enabled(),
)
@_copy_doc(TrainV1Context.get_local_rank)
def get_local_rank(self) -> int:
return session.get_local_rank()
@Deprecated(
message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format(
"get_local_world_size"
),
warning=_v2_migration_warnings_enabled(),
)
@_copy_doc(TrainV1Context.get_local_world_size)
def get_local_world_size(self) -> int:
return session.get_local_world_size()
@Deprecated(
message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_node_rank"),
warning=_v2_migration_warnings_enabled(),
)
@_copy_doc(TrainV1Context.get_node_rank)
def get_node_rank(self) -> int:
return session.get_node_rank()
@PublicAPI(stability="beta")
def get_context() -> TuneContext:
"""Get or create a singleton Ray Tune context.
The context is only available in a tune function passed to the `ray.tune.Tuner`.
See the :class:`~ray.tune.TuneContext` API reference to see available methods.
"""
global _tune_context
with _tune_context_lock:
if _tune_context is None:
# TODO(justinvyu): This default should be a dummy context
# that is only used for testing / running outside of Tune.
_tune_context = TuneContext()
return _tune_context
| TuneContext |
python | jina-ai__jina | tests/integration/distributed-replicas/exec.py | {
"start": 51,
"end": 383
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._id = str(uuid.uuid4())
@requests
def foo(self, docs, *args, **kwargs):
for doc in docs:
doc.tags['name'] = self.runtime_args.name
doc.tags['uuid'] = self._id
| MyExternalExecutor |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_rowcount.py | {
"start": 625,
"end": 7900
} | class ____(fixtures.TablesTest):
"""test rowcount functionality"""
__requires__ = ("sane_rowcount",)
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"employees",
metadata,
Column(
"employee_id",
Integer,
autoincrement=False,
primary_key=True,
),
Column("name", String(50)),
Column("department", String(1)),
)
@classmethod
def insert_data(cls, connection):
cls.data = data = [
("Angela", "A"),
("Andrew", "A"),
("Anand", "A"),
("Bob", "B"),
("Bobette", "B"),
("Buffy", "B"),
("Charlie", "C"),
("Cynthia", "C"),
("Chris", "C"),
]
employees_table = cls.tables.employees
connection.execute(
employees_table.insert(),
[
{"employee_id": i, "name": n, "department": d}
for i, (n, d) in enumerate(data)
],
)
def test_basic(self, connection):
employees_table = self.tables.employees
s = select(
employees_table.c.name, employees_table.c.department
).order_by(employees_table.c.employee_id)
rows = connection.execute(s).fetchall()
eq_(rows, self.data)
@testing.variation("statement", ["update", "delete", "insert", "select"])
@testing.variation("close_first", [True, False])
def test_non_rowcount_scenarios_no_raise(
self, connection, statement, close_first
):
employees_table = self.tables.employees
# WHERE matches 3, 3 rows changed
department = employees_table.c.department
if statement.update:
r = connection.execute(
employees_table.update().where(department == "C"),
{"department": "Z"},
)
elif statement.delete:
r = connection.execute(
employees_table.delete().where(department == "C"),
{"department": "Z"},
)
elif statement.insert:
r = connection.execute(
employees_table.insert(),
[
{"employee_id": 25, "name": "none 1", "department": "X"},
{"employee_id": 26, "name": "none 2", "department": "Z"},
{"employee_id": 27, "name": "none 3", "department": "Z"},
],
)
elif statement.select:
s = select(
employees_table.c.name, employees_table.c.department
).where(employees_table.c.department == "C")
r = connection.execute(s)
r.all()
else:
statement.fail()
if close_first:
r.close()
assert r.rowcount in (-1, 3)
def test_update_rowcount1(self, connection):
employees_table = self.tables.employees
# WHERE matches 3, 3 rows changed
department = employees_table.c.department
r = connection.execute(
employees_table.update().where(department == "C"),
{"department": "Z"},
)
assert r.rowcount == 3
def test_update_rowcount2(self, connection):
employees_table = self.tables.employees
# WHERE matches 3, 0 rows changed
department = employees_table.c.department
r = connection.execute(
employees_table.update().where(department == "C"),
{"department": "C"},
)
eq_(r.rowcount, 3)
@testing.variation("implicit_returning", [True, False])
@testing.variation(
"dml",
[
("update", testing.requires.update_returning),
("delete", testing.requires.delete_returning),
],
)
def test_update_delete_rowcount_return_defaults(
self, connection, implicit_returning, dml
):
"""note this test should succeed for all RETURNING backends
as of 2.0. In
Idf28379f8705e403a3c6a937f6a798a042ef2540 we changed rowcount to use
len(rows) when we have implicit returning
"""
if implicit_returning:
employees_table = self.tables.employees
else:
employees_table = Table(
"employees",
MetaData(),
Column(
"employee_id",
Integer,
autoincrement=False,
primary_key=True,
),
Column("name", String(50)),
Column("department", String(1)),
implicit_returning=False,
)
department = employees_table.c.department
if dml.update:
stmt = (
employees_table.update()
.where(department == "C")
.values(name=employees_table.c.department + "Z")
.return_defaults()
)
elif dml.delete:
stmt = (
employees_table.delete()
.where(department == "C")
.return_defaults()
)
else:
dml.fail()
r = connection.execute(stmt)
eq_(r.rowcount, 3)
def test_raw_sql_rowcount(self, connection):
# test issue #3622, make sure eager rowcount is called for text
result = connection.exec_driver_sql(
"update employees set department='Z' where department='C'"
)
eq_(result.rowcount, 3)
def test_text_rowcount(self, connection):
# test issue #3622, make sure eager rowcount is called for text
result = connection.execute(
text("update employees set department='Z' where department='C'")
)
eq_(result.rowcount, 3)
def test_delete_rowcount(self, connection):
employees_table = self.tables.employees
# WHERE matches 3, 3 rows deleted
department = employees_table.c.department
r = connection.execute(
employees_table.delete().where(department == "C")
)
eq_(r.rowcount, 3)
@testing.requires.sane_multi_rowcount
def test_multi_update_rowcount(self, connection):
employees_table = self.tables.employees
stmt = (
employees_table.update()
.where(employees_table.c.name == bindparam("emp_name"))
.values(department="C")
)
r = connection.execute(
stmt,
[
{"emp_name": "Bob"},
{"emp_name": "Cynthia"},
{"emp_name": "nonexistent"},
],
)
eq_(r.rowcount, 2)
@testing.requires.sane_multi_rowcount
def test_multi_delete_rowcount(self, connection):
employees_table = self.tables.employees
stmt = employees_table.delete().where(
employees_table.c.name == bindparam("emp_name")
)
r = connection.execute(
stmt,
[
{"emp_name": "Bob"},
{"emp_name": "Cynthia"},
{"emp_name": "nonexistent"},
],
)
eq_(r.rowcount, 2)
| RowCountTest |
python | Pylons__pyramid | tests/test_config/test_predicates.py | {
"start": 21957,
"end": 22037
} | class ____:
def __init__(self, **kw):
self.__dict__.update(**kw)
| Dummy |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_affinity_term.py | {
"start": 383,
"end": 11726
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'label_selector': 'V1LabelSelector',
'match_label_keys': 'list[str]',
'mismatch_label_keys': 'list[str]',
'namespace_selector': 'V1LabelSelector',
'namespaces': 'list[str]',
'topology_key': 'str'
}
attribute_map = {
'label_selector': 'labelSelector',
'match_label_keys': 'matchLabelKeys',
'mismatch_label_keys': 'mismatchLabelKeys',
'namespace_selector': 'namespaceSelector',
'namespaces': 'namespaces',
'topology_key': 'topologyKey'
}
def __init__(self, label_selector=None, match_label_keys=None, mismatch_label_keys=None, namespace_selector=None, namespaces=None, topology_key=None, local_vars_configuration=None): # noqa: E501
"""V1PodAffinityTerm - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._label_selector = None
self._match_label_keys = None
self._mismatch_label_keys = None
self._namespace_selector = None
self._namespaces = None
self._topology_key = None
self.discriminator = None
if label_selector is not None:
self.label_selector = label_selector
if match_label_keys is not None:
self.match_label_keys = match_label_keys
if mismatch_label_keys is not None:
self.mismatch_label_keys = mismatch_label_keys
if namespace_selector is not None:
self.namespace_selector = namespace_selector
if namespaces is not None:
self.namespaces = namespaces
self.topology_key = topology_key
@property
def label_selector(self):
"""Gets the label_selector of this V1PodAffinityTerm. # noqa: E501
:return: The label_selector of this V1PodAffinityTerm. # noqa: E501
:rtype: V1LabelSelector
"""
return self._label_selector
@label_selector.setter
def label_selector(self, label_selector):
"""Sets the label_selector of this V1PodAffinityTerm.
:param label_selector: The label_selector of this V1PodAffinityTerm. # noqa: E501
:type: V1LabelSelector
"""
self._label_selector = label_selector
@property
def match_label_keys(self):
"""Gets the match_label_keys of this V1PodAffinityTerm. # noqa: E501
MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both matchLabelKeys and labelSelector. Also, matchLabelKeys cannot be set when labelSelector isn't set. # noqa: E501
:return: The match_label_keys of this V1PodAffinityTerm. # noqa: E501
:rtype: list[str]
"""
return self._match_label_keys
@match_label_keys.setter
def match_label_keys(self, match_label_keys):
"""Sets the match_label_keys of this V1PodAffinityTerm.
MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both matchLabelKeys and labelSelector. Also, matchLabelKeys cannot be set when labelSelector isn't set. # noqa: E501
:param match_label_keys: The match_label_keys of this V1PodAffinityTerm. # noqa: E501
:type: list[str]
"""
self._match_label_keys = match_label_keys
@property
def mismatch_label_keys(self):
"""Gets the mismatch_label_keys of this V1PodAffinityTerm. # noqa: E501
MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. Also, mismatchLabelKeys cannot be set when labelSelector isn't set. # noqa: E501
:return: The mismatch_label_keys of this V1PodAffinityTerm. # noqa: E501
:rtype: list[str]
"""
return self._mismatch_label_keys
@mismatch_label_keys.setter
def mismatch_label_keys(self, mismatch_label_keys):
"""Sets the mismatch_label_keys of this V1PodAffinityTerm.
MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. Also, mismatchLabelKeys cannot be set when labelSelector isn't set. # noqa: E501
:param mismatch_label_keys: The mismatch_label_keys of this V1PodAffinityTerm. # noqa: E501
:type: list[str]
"""
self._mismatch_label_keys = mismatch_label_keys
@property
def namespace_selector(self):
"""Gets the namespace_selector of this V1PodAffinityTerm. # noqa: E501
:return: The namespace_selector of this V1PodAffinityTerm. # noqa: E501
:rtype: V1LabelSelector
"""
return self._namespace_selector
@namespace_selector.setter
def namespace_selector(self, namespace_selector):
"""Sets the namespace_selector of this V1PodAffinityTerm.
:param namespace_selector: The namespace_selector of this V1PodAffinityTerm. # noqa: E501
:type: V1LabelSelector
"""
self._namespace_selector = namespace_selector
@property
def namespaces(self):
"""Gets the namespaces of this V1PodAffinityTerm. # noqa: E501
namespaces specifies a static list of namespace names that the term applies to. The term is applied to the union of the namespaces listed in this field and the ones selected by namespaceSelector. null or empty namespaces list and null namespaceSelector means \"this pod's namespace\". # noqa: E501
:return: The namespaces of this V1PodAffinityTerm. # noqa: E501
:rtype: list[str]
"""
return self._namespaces
@namespaces.setter
def namespaces(self, namespaces):
"""Sets the namespaces of this V1PodAffinityTerm.
namespaces specifies a static list of namespace names that the term applies to. The term is applied to the union of the namespaces listed in this field and the ones selected by namespaceSelector. null or empty namespaces list and null namespaceSelector means \"this pod's namespace\". # noqa: E501
:param namespaces: The namespaces of this V1PodAffinityTerm. # noqa: E501
:type: list[str]
"""
self._namespaces = namespaces
@property
def topology_key(self):
"""Gets the topology_key of this V1PodAffinityTerm. # noqa: E501
This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed. # noqa: E501
:return: The topology_key of this V1PodAffinityTerm. # noqa: E501
:rtype: str
"""
return self._topology_key
@topology_key.setter
def topology_key(self, topology_key):
"""Sets the topology_key of this V1PodAffinityTerm.
This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed. # noqa: E501
:param topology_key: The topology_key of this V1PodAffinityTerm. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and topology_key is None: # noqa: E501
raise ValueError("Invalid value for `topology_key`, must not be `None`") # noqa: E501
self._topology_key = topology_key
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1PodAffinityTerm):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1PodAffinityTerm):
return True
return self.to_dict() != other.to_dict()
| V1PodAffinityTerm |
python | keras-team__keras | keras/src/losses/losses.py | {
"start": 52154,
"end": 54512
} | class ____(LossFunctionWrapper):
"""Computes the Tversky loss value between `y_true` and `y_pred`.
This loss function is weighted by the alpha and beta coefficients
that penalize false positives and false negatives.
With `alpha=0.5` and `beta=0.5`, the loss value becomes equivalent to
Dice Loss.
Args:
alpha: The coefficient controlling incidence of false positives.
Defaults to `0.5`.
beta: The coefficient controlling incidence of false negatives.
Defaults to `0.5`.
reduction: Type of reduction to apply to the loss. In almost all cases
this should be `"sum_over_batch_size"`. Supported options are
`"sum"`, `"sum_over_batch_size"`, `"mean"`,
`"mean_with_sample_weight"` or `None`. `"sum"` sums the loss,
`"sum_over_batch_size"` and `"mean"` sum the loss and divide by the
sample size, and `"mean_with_sample_weight"` sums the loss and
divides by the sum of the sample weights. `"none"` and `None`
perform no aggregation. Defaults to `"sum_over_batch_size"`.
name: Optional name for the loss instance.
dtype: The dtype of the loss's computations. Defaults to `None`, which
means using `keras.backend.floatx()`. `keras.backend.floatx()` is a
`"float32"` unless set to different value
(via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is
provided, then the `compute_dtype` will be utilized.
Returns:
Tversky loss value.
Reference:
- [Salehi et al., 2017](https://arxiv.org/abs/1706.05721)
"""
def __init__(
self,
alpha=0.5,
beta=0.5,
reduction="sum_over_batch_size",
name="tversky",
axis=None,
dtype=None,
):
super().__init__(
tversky,
name=name,
reduction=reduction,
dtype=dtype,
alpha=alpha,
beta=beta,
axis=axis,
)
self.alpha = alpha
self.beta = beta
self.axis = axis
def get_config(self):
config = Loss.get_config(self)
config.update(
{"alpha": self.alpha, "beta": self.beta, "axis": self.axis}
)
return config
@keras_export("keras.losses.Circle")
| Tversky |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2_test.py | {
"start": 171109,
"end": 173505
} | class ____(test.TestCase):
# All transform tests are distributed in column test.
# Here we only test multi column case and naming
def transform_multi_column(self):
bucketized_price = fc.bucketized_column(
fc.numeric_column('price'), boundaries=[0, 2, 4, 6])
hashed_sparse = fc.categorical_column_with_hash_bucket('wire', 10)
with ops.Graph().as_default():
features = {
'price': [[-1.], [5.]],
'wire':
sparse_tensor.SparseTensor(
values=['omar', 'stringer', 'marlo'],
indices=[[0, 0], [1, 0], [1, 1]],
dense_shape=[2, 2])
}
transformed = fc._transform_features_v2(
features, [bucketized_price, hashed_sparse], None)
self.evaluate(variables_lib.global_variables_initializer())
self.evaluate(lookup_ops.tables_initializer())
self.assertIn(bucketized_price.name, transformed[bucketized_price].name)
self.assertAllEqual([[0], [3]],
self.evaluate(transformed[bucketized_price]))
self.assertIn(hashed_sparse.name, transformed[hashed_sparse].name)
self.assertAllEqual([6, 4, 1],
self.evaluate(transformed[hashed_sparse].values))
def test_column_order(self):
"""When the column is both dense and sparse, uses sparse tensors."""
class _LoggerColumn(BaseFeatureColumnForTests):
def __init__(self, name):
super(_LoggerColumn, self).__init__()
self._name = name
@property
def _is_v2_column(self):
return True
@property
def name(self):
return self._name
def transform_feature(self, transformation_cache, state_manager):
self.call_order = call_logger['count']
call_logger['count'] += 1
return 'Anything'
@property
def parse_example_spec(self):
pass
with ops.Graph().as_default():
column1 = _LoggerColumn('1')
column2 = _LoggerColumn('2')
call_logger = {'count': 0}
fc._transform_features_v2({}, [column1, column2], None)
self.assertEqual(0, column1.call_order)
self.assertEqual(1, column2.call_order)
call_logger = {'count': 0}
fc._transform_features_v2({}, [column2, column1], None)
self.assertEqual(0, column1.call_order)
self.assertEqual(1, column2.call_order)
| TransformFeaturesTest |
python | Textualize__textual | docs/examples/styles/height.py | {
"start": 64,
"end": 227
} | class ____(App):
CSS_PATH = "height.tcss"
def compose(self):
yield Widget()
if __name__ == "__main__":
app = HeightApp()
app.run()
| HeightApp |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py | {
"start": 35044,
"end": 42630
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def testUpdateAddSub(self):
for dtype in (dtypes.int32, dtypes.float32):
indices = constant_op.constant([[4], [3], [1], [7]])
updates = constant_op.constant([9, 10, 11, 12], dtype=dtype)
t = array_ops.ones([8], dtype=dtype)
assigned = array_ops.tensor_scatter_update(t, indices, updates)
added = array_ops.tensor_scatter_add(t, indices, updates)
subbed = array_ops.tensor_scatter_sub(t, indices, updates)
self.assertAllEqual(assigned,
constant_op.constant([1, 11, 1, 10, 9, 1, 1, 12]))
self.assertAllEqual(added,
constant_op.constant([1, 12, 1, 11, 10, 1, 1, 13]))
self.assertAllEqual(subbed,
constant_op.constant([1, -10, 1, -9, -8, 1, 1, -11]))
def testUpdateAddSubGradients(self):
with self.cached_session():
indices = constant_op.constant([[3], [1]])
updates = constant_op.constant([9, 10], dtype=dtypes.float32)
x = array_ops.ones([4], dtype=dtypes.float32)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda x: array_ops.tensor_scatter_update(x, indices, updates), [x])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda x: array_ops.tensor_scatter_add(x, indices, updates), [x])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda x: array_ops.tensor_scatter_sub(x, indices, updates), [x])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda updates: array_ops.tensor_scatter_update(x, indices, updates),
[updates])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda updates: array_ops.tensor_scatter_add(x, indices, updates),
[updates])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
theoretical, numerical = gradient_checker_v2.compute_gradient(
lambda updates: array_ops.tensor_scatter_sub(x, indices, updates),
[updates])
self.assertAllClose(theoretical, numerical, 5e-4, 5e-4)
@test_util.run_in_graph_and_eager_modes
def testUpdateMinMax(self):
for dtype in (dtypes.int32, dtypes.float32):
indices = constant_op.constant([[4], [3], [1], [7]])
updates = constant_op.constant([0, 2, -1, 2], dtype=dtype)
t = array_ops.ones([8], dtype=dtype)
assigned = array_ops.tensor_scatter_update(t, indices, updates)
min_result = array_ops.tensor_scatter_min(t, indices, updates)
max_result = array_ops.tensor_scatter_max(t, indices, updates)
self.assertAllEqual(assigned,
constant_op.constant([1, -1, 1, 2, 0, 1, 1, 2]))
self.assertAllEqual(min_result,
constant_op.constant([1, -1, 1, 1, 0, 1, 1, 1]))
self.assertAllEqual(max_result,
constant_op.constant([1, 1, 1, 2, 1, 1, 1, 2]))
def testUpdateMinMaxGradients(self):
# Loop body as a function to avoid go/gpylint-faq#cell-var-from-loop.
def _TestFn(dtype):
x = array_ops.ones([4], dtype=dtypes.float32)
indices = constant_op.constant([[1], [2], [3], [3]], dtype=dtype)
updates = constant_op.constant([2.0, 0.5, 1.0, 1.0], dtype=dtypes.float32)
theoretical, _ = gradient_checker_v2.compute_gradient(
lambda x: array_ops.tensor_scatter_max(x, indices, updates), [x])
# Numerical gradient doesn't work for degenerate values because the
# derivative is not continuous. The manually entered gradient divides
# the gradient among all contributing elements at the discontinuity.
manual = array_ops.reshape(
array_ops.matrix_diag([1.0, 0.0, 1.0, 0.3333]), (1, 4, 4))
self.assertAllClose(theoretical, manual, 5e-4, 5e-4)
theoretical, _ = gradient_checker_v2.compute_gradient(
lambda x: array_ops.tensor_scatter_min(x, indices, updates), [x])
manual = array_ops.reshape(
array_ops.matrix_diag([1.0, 1.0, 0.0, 0.3333]), (1, 4, 4))
self.assertAllClose(theoretical, manual, 5e-4, 5e-4)
theoretical, _ = gradient_checker_v2.compute_gradient(
lambda updates: array_ops.tensor_scatter_max(x, indices, updates),
[updates])
manual = constant_op.constant(
[[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.3333, 0.3333]]],
dtype=dtypes.float32)
self.assertAllClose(theoretical, manual, 5e-4, 5e-4)
theoretical, _ = gradient_checker_v2.compute_gradient(
lambda updates: array_ops.tensor_scatter_min(x, indices, updates),
[updates])
manual = constant_op.constant(
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.3333, 0.3333]]],
dtype=dtypes.float32)
self.assertAllClose(theoretical, manual, 5e-4, 5e-4)
with self.cached_session():
for dtype in (dtypes.int32, dtypes.int64):
_TestFn(dtype)
def testTensorScatterUpdateWithForwarding(self):
for dtype in (dtypes.int32, dtypes.float32):
@def_function.function
def _TestFn():
indices = constant_op.constant([[4], [3], [1], [7]])
updates = constant_op.constant([9, 10, 11, 12], dtype=dtype) # pylint: disable=cell-var-from-loop
t = array_ops.ones([8], dtype=dtype) # pylint: disable=cell-var-from-loop
return array_ops.tensor_scatter_update(t, indices, updates)
self.assertAllEqual(_TestFn(), [1, 11, 1, 10, 9, 1, 1, 12])
@test_util.run_in_graph_and_eager_modes
def testTensorScatterUpdateWithStrings(self):
indices = constant_op.constant([[4], [3], [1], [7]])
updates = constant_op.constant(["there", "there", "there", "12"],
dtype=dtypes.string)
tensor = constant_op.constant([
"hello", "hello", "hello", "hello", "hello", "hello", "hello", "hello"
],
dtype=dtypes.string)
updated = array_ops.tensor_scatter_update(tensor, indices, updates)
self.assertAllEqual(
updated,
constant_op.constant([
"hello", "there", "hello", "there", "there", "hello", "hello", "12"
]))
@test_util.run_in_graph_and_eager_modes
def testUpdateRepeatedIndices1D(self):
if test_util.is_gpu_available():
self.skipTest("Duplicate indices scatter is non-deterministic on GPU")
a = array_ops.zeros([10, 1])
b = array_ops.tensor_scatter_update(a, [[5], [5]], [[4], [8]])
self.assertAllEqual(
b,
constant_op.constant([[0.], [0.], [0.], [0.], [0.], [8.], [0.], [0.],
[0.], [0.]]))
@test_util.run_in_graph_and_eager_modes
def testUpdateRepeatedIndices2D(self):
if test_util.is_gpu_available():
self.skipTest("Duplicate indices scatter is non-deterministic on GPU")
a = array_ops.zeros([10, 10])
b = array_ops.tensor_scatter_update(
a, [[5], [6], [6]],
[math_ops.range(10),
math_ops.range(11, 21),
math_ops.range(10, 20)])
self.assertAllEqual(
b[6],
constant_op.constant([10., 11., 12., 13., 14., 15., 16., 17., 18.,
19.]))
| ScatterNdTensorTest |
python | instagram__MonkeyType | tests/test_util.py | {
"start": 1270,
"end": 2667
} | class ____:
def test_get_method(self):
"""Make sure we return the underlying function for boundmethods"""
meth = Dummy.a_class_method
obj = get_func_in_module(meth.__module__, meth.__qualname__)
assert obj == meth.__func__
def test_get_property(self):
"""We should be able to look up properties that are only getters"""
func = Dummy.a_property.fget
obj = get_func_in_module(func.__module__, func.__qualname__)
assert obj == func
def test_get_settable_property(self):
"""We can't disambiguate between getters, setters, and deleters"""
func = Dummy.a_settable_property.fget
with pytest.raises(InvalidTypeError):
get_func_in_module(func.__module__, func.__qualname__)
@skipIf(cached_property is None, "install Django to run this test")
def test_get_cached_property(self):
"""We should be able to look up properties that are decorated
with django.utils.functional.cached_property"""
func = Dummy.a_cached_property.func
obj = get_func_in_module(func.__module__, func.__qualname__)
assert obj == func
def test_get_non_function(self):
"""Raise an error if lookup returns something that isn't a function"""
with pytest.raises(InvalidTypeError):
get_func_in_module(__name__, 'NOT_A_FUNCTION')
| TestGetFuncInModule |
python | mkdocs__mkdocs | mkdocs/tests/config/config_options_tests.py | {
"start": 48687,
"end": 54959
} | class ____(TestCase):
def test_subconfig_wrong_type(self) -> None:
# Test that an error is raised if subconfig does not receive a dict
class Schema(Config):
option = c.SubConfig()
for val in "not_a_dict", ("not_a_dict",), ["not_a_dict"]:
with self.subTest(val):
with self.expect_error(
option=re.compile(
r"The configuration is invalid. Expected a key-value mapping "
r"\(dict\) but received: .+"
)
):
self.get_config(Schema, {'option': val})
def test_subconfig_unknown_option(self) -> None:
class Schema(Config):
option = c.SubConfig(validate=True)
conf = self.get_config(
Schema,
{'option': {'unknown': 0}},
warnings=dict(option="Sub-option 'unknown': Unrecognised configuration name: unknown"),
)
self.assertEqual(conf.option, {"unknown": 0})
def test_subconfig_invalid_option(self) -> None:
class Sub(Config):
cc = c.Choice(('foo', 'bar'))
class Schema(Config):
option = c.SubConfig(Sub)
with self.expect_error(
option="Sub-option 'cc': Expected one of: ('foo', 'bar') but received: True"
):
self.get_config(Schema, {'option': {'cc': True}})
def test_subconfig_normal(self) -> None:
class Sub(Config):
cc = c.Choice(('foo', 'bar'))
class Schema(Config):
option = c.SubConfig(Sub)
conf = self.get_config(Schema, {'option': {'cc': 'foo'}})
assert_type(conf.option, Sub)
self.assertEqual(conf.option, {'cc': 'foo'})
assert_type(conf.option.cc, str)
self.assertEqual(conf.option.cc, 'foo')
def test_subconfig_with_multiple_items(self) -> None:
# This had a bug where subsequent items would get merged into the same dict.
class Sub(Config):
value = c.Type(str)
class Schema(Config):
the_items = c.ListOfItems(c.SubConfig(Sub))
conf = self.get_config(
Schema,
{
'the_items': [
{'value': 'a'},
{'value': 'b'},
]
},
)
assert_type(conf.the_items, List[Sub])
self.assertEqual(conf.the_items, [{'value': 'a'}, {'value': 'b'}])
assert_type(conf.the_items[1].value, str)
self.assertEqual(conf.the_items[1].value, 'b')
def test_optional(self) -> None:
class Sub(Config):
opt = c.Optional(c.Type(int))
class Schema(Config):
sub = c.Optional(c.ListOfItems(c.SubConfig(Sub)))
conf = self.get_config(Schema, {})
self.assertEqual(conf.sub, None)
conf = self.get_config(Schema, {'sub': None})
self.assertEqual(conf.sub, None)
conf = self.get_config(Schema, {'sub': [{'opt': 1}, {}]})
assert_type(conf.sub, Optional[List[Sub]])
self.assertEqual(conf.sub, [{'opt': 1}, {'opt': None}])
assert conf.sub is not None
assert_type(conf.sub[0].opt, Optional[int])
self.assertEqual(conf.sub[0].opt, 1)
conf = self.get_config(Schema, {'sub': []})
conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]})
self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}])
def test_required(self) -> None:
class Sub(Config):
opt = c.Type(int)
class Schema(Config):
sub = c.ListOfItems(c.SubConfig(Sub))
with self.expect_error(sub="Required configuration not provided."):
conf = self.get_config(Schema, {})
with self.expect_error(sub="Required configuration not provided."):
conf = self.get_config(Schema, {'sub': None})
with self.expect_error(
sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'asdf'}, {}]})
conf = self.get_config(Schema, {'sub': []})
conf = self.get_config(Schema, {'sub': [{'opt': 1}, {'opt': 2}]})
assert_type(conf.sub, List[Sub])
self.assertEqual(conf.sub, [{'opt': 1}, {'opt': 2}])
assert_type(conf.sub[0].opt, int)
self.assertEqual(conf.sub[0].opt, 1)
with self.expect_error(
sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
with self.expect_error(
sub="Sub-option 'opt': Expected type: <class 'int'> but received: <class 'str'>"
):
conf = self.get_config(Schema, {'sub': [{'opt': 'z'}, {'opt': 2}]})
with self.expect_error(
sub="The configuration is invalid. Expected a key-value mapping "
"(dict) but received: <class 'int'>"
):
conf = self.get_config(Schema, {'sub': [1, 2]})
def test_default(self) -> None:
class Sub(Config):
opt = c.Type(int)
class Schema(Config):
sub = c.ListOfItems(c.SubConfig(Sub), default=[])
conf = self.get_config(Schema, {})
assert_type(conf.sub, List[Sub])
self.assertEqual(conf.sub, [])
with self.expect_error(sub="Required configuration not provided."):
conf = self.get_config(Schema, {'sub': None})
def test_config_file_path_pass_through(self) -> None:
"""Necessary to ensure FilesystemObject validates the correct path."""
passed_config_path = None
class SubType(c.BaseConfigOption):
def pre_validation(self, config: Config, key_name: str) -> None:
nonlocal passed_config_path
passed_config_path = config.config_file_path
class Sub(Config):
opt = SubType()
class Schema(Config):
sub = c.ListOfItems(c.SubConfig(Sub), default=[])
config_path = "foo/mkdocs.yaml"
self.get_config(Schema, {"sub": [{"opt": "bar"}]}, config_file_path=config_path)
self.assertEqual(passed_config_path, config_path)
| SubConfigTest |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/components/airflow_instance/component.py | {
"start": 2071,
"end": 2226
} | class ____(Resolvable):
type: Literal["basic_auth"]
webserver_url: str
username: str
password: str
@dataclass
| ResolvedAirflowBasicAuthBackend |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 114083,
"end": 144545
} | class ____(fixtures.TestBase):
def _single_fixture(self):
m = MetaData()
t1 = Table("t1", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer, ForeignKey("t1.a")))
t3 = Table("t3", m, Column("a", Integer))
return t1, t2, t3
def _assert_index_col_x(self, t, i, columns=True):
eq_(t.indexes, {i})
if columns:
eq_(list(i.columns), [t.c.x])
else:
eq_(list(i.columns), [])
assert i.table is t
def test_separate_decl_columns(self):
m = MetaData()
t = Table("t", m, Column("x", Integer))
i = Index("i", t.c.x)
self._assert_index_col_x(t, i)
def test_separate_decl_columns_functional(self):
m = MetaData()
t = Table("t", m, Column("x", Integer))
i = Index("i", func.foo(t.c.x))
self._assert_index_col_x(t, i)
def test_index_no_cols_private_table_arg(self):
m = MetaData()
t = Table("t", m, Column("x", Integer))
i = Index("i", _table=t)
is_(i.table, t)
eq_(list(i.columns), [])
def test_index_w_cols_private_table_arg(self):
m = MetaData()
t = Table("t", m, Column("x", Integer))
i = Index("i", t.c.x, _table=t)
is_(i.table, t)
eq_(list(i.columns), [t.c.x])
def test_inline_decl_columns(self):
m = MetaData()
c = Column("x", Integer)
i = Index("i", c)
t = Table("t", m, c, i)
self._assert_index_col_x(t, i)
def test_inline_decl_columns_functional(self):
m = MetaData()
c = Column("x", Integer)
i = Index("i", func.foo(c))
t = Table("t", m, c, i)
self._assert_index_col_x(t, i)
def test_inline_decl_string(self):
m = MetaData()
i = Index("i", "x")
t = Table("t", m, Column("x", Integer), i)
self._assert_index_col_x(t, i)
def test_inline_decl_textonly(self):
m = MetaData()
i = Index("i", text("foobar(x)"))
t = Table("t", m, Column("x", Integer), i)
self._assert_index_col_x(t, i, columns=False)
def test_separate_decl_textonly(self):
m = MetaData()
i = Index("i", text("foobar(x)"))
t = Table("t", m, Column("x", Integer))
t.append_constraint(i)
self._assert_index_col_x(t, i, columns=False)
def test_unnamed_column_exception(self):
# this can occur in some declarative situations
c = Column(Integer)
idx = Index("q", c)
m = MetaData()
t = Table("t", m, Column("q"))
assert_raises_message(
exc.ArgumentError,
"Can't add unnamed column to column collection",
t.append_constraint,
idx,
)
def test_non_attached_col_plus_string_expr(self):
# another one that declarative can lead towards
metadata = MetaData()
t1 = Table("a", metadata, Column("id", Integer))
c2 = Column("x", Integer)
# if we do it here, no problem
# t1.append_column(c2)
idx = Index("foo", c2, desc("foo"))
t1.append_column(c2)
self._assert_index_col_x(t1, idx, columns=True)
def test_column_associated_w_lowercase_table(self):
from sqlalchemy import table
c = Column("x", Integer)
table("foo", c)
idx = Index("q", c)
is_(idx.table, None) # lower-case-T table doesn't have indexes
def test_clauseelement_extraction_one(self):
t = Table("t", MetaData(), Column("x", Integer), Column("y", Integer))
class MyThing:
def __clause_element__(self):
return t.c.x + 5
idx = Index("foo", MyThing())
self._assert_index_col_x(t, idx)
def test_clauseelement_extraction_two(self):
t = Table("t", MetaData(), Column("x", Integer), Column("y", Integer))
class MyThing:
def __clause_element__(self):
return t.c.x + 5
idx = Index("bar", MyThing(), t.c.y)
eq_(set(t.indexes), {idx})
def test_clauseelement_extraction_three(self):
t = Table("t", MetaData(), Column("x", Integer), Column("y", Integer))
expr1 = t.c.x + 5
class MyThing:
def __clause_element__(self):
return expr1
idx = Index("bar", MyThing(), t.c.y)
is_true(idx.expressions[0].compare(expr1))
is_(idx.expressions[1], t.c.y)
def test_table_references(self):
t1, t2, t3 = self._single_fixture()
assert list(t2.c.a.foreign_keys)[0].references(t1)
assert not list(t2.c.a.foreign_keys)[0].references(t3)
def test_column_references(self):
t1, t2, t3 = self._single_fixture()
assert t2.c.a.references(t1.c.a)
assert not t2.c.a.references(t3.c.a)
assert not t2.c.a.references(t1.c.b)
def test_column_references_derived(self):
t1, t2, t3 = self._single_fixture()
s1 = tsa.select(tsa.select(t1).alias()).subquery()
assert t2.c.a.references(s1.c.a)
assert not t2.c.a.references(s1.c.b)
def test_copy_doesnt_reference(self):
t1, t2, t3 = self._single_fixture()
a2 = t2.c.a._copy()
assert not a2.references(t1.c.a)
assert not a2.references(t1.c.b)
def test_derived_column_references(self):
t1, t2, t3 = self._single_fixture()
s1 = tsa.select(tsa.select(t2).alias()).subquery()
assert s1.c.a.references(t1.c.a)
assert not s1.c.a.references(t1.c.b)
def test_referred_table_accessor(self):
t1, t2, t3 = self._single_fixture()
fkc = list(t2.foreign_key_constraints)[0]
is_(fkc.referred_table, t1)
def test_referred_table_accessor_not_available(self):
t1 = Table("t", MetaData(), Column("x", ForeignKey("q.id")))
fkc = list(t1.foreign_key_constraints)[0]
assert_raises_message(
exc.InvalidRequestError,
"Foreign key associated with column 't.x' could not find "
"table 'q' with which to generate a foreign key to target "
"column 'id'",
getattr,
fkc,
"referred_table",
)
def test_related_column_not_present_atfirst_ok(self):
m = MetaData()
base_table = Table("base", m, Column("id", Integer, primary_key=True))
fk = ForeignKey("base.q")
derived_table = Table(
"derived", m, Column("id", None, fk, primary_key=True)
)
base_table.append_column(Column("q", Integer))
assert fk.column is base_table.c.q
assert isinstance(derived_table.c.id.type, Integer)
def test_related_column_not_present_atfirst_ok_onname(self):
m = MetaData()
base_table = Table("base", m, Column("id", Integer, primary_key=True))
fk = ForeignKey("base.q", link_to_name=True)
derived_table = Table(
"derived", m, Column("id", None, fk, primary_key=True)
)
base_table.append_column(Column("q", Integer, key="zz"))
assert fk.column is base_table.c.zz
assert isinstance(derived_table.c.id.type, Integer)
def test_related_column_not_present_atfirst_ok_linktoname_conflict(self):
m = MetaData()
base_table = Table("base", m, Column("id", Integer, primary_key=True))
fk = ForeignKey("base.q", link_to_name=True)
derived_table = Table(
"derived", m, Column("id", None, fk, primary_key=True)
)
base_table.append_column(Column("zz", Integer, key="q"))
base_table.append_column(Column("q", Integer, key="zz"))
assert fk.column is base_table.c.zz
assert isinstance(derived_table.c.id.type, Integer)
def test_invalid_composite_fk_check_strings(self):
m = MetaData()
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
"multiple remote tables: t2 and t3",
Table,
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], ["t2.x", "t3.y"]),
)
def test_invalid_composite_fk_check_columns(self):
m = MetaData()
t2 = Table("t2", m, Column("x", Integer))
t3 = Table("t3", m, Column("y", Integer))
assert_raises_message(
exc.ArgumentError,
r"ForeignKeyConstraint on t1\(x, y\) refers to "
"multiple remote tables: t2 and t3",
Table,
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], [t2.c.x, t3.c.y]),
)
def test_invalid_composite_fk_check_columns_notattached(self):
m = MetaData()
x = Column("x", Integer)
y = Column("y", Integer)
# no error is raised for this one right now.
# which is a minor bug.
Table(
"t1",
m,
Column("x", Integer),
Column("y", Integer),
ForeignKeyConstraint(["x", "y"], [x, y]),
)
Table("t2", m, x)
Table("t3", m, y)
def test_constraint_copied_to_proxy_ok(self):
m = MetaData()
Table("t1", m, Column("id", Integer, primary_key=True))
t2 = Table(
"t2",
m,
Column("id", Integer, ForeignKey("t1.id"), primary_key=True),
)
s = tsa.select(t2).subquery()
t2fk = list(t2.c.id.foreign_keys)[0]
sfk = list(s.c.id.foreign_keys)[0]
# the two FKs share the ForeignKeyConstraint
is_(t2fk.constraint, sfk.constraint)
# but the ForeignKeyConstraint isn't
# aware of the select's FK
eq_(t2fk.constraint.elements, [t2fk])
def test_type_propagate_composite_fk_string(self):
metadata = MetaData()
Table(
"a",
metadata,
Column("key1", Integer, primary_key=True),
Column("key2", String(40), primary_key=True),
)
b = Table(
"b",
metadata,
Column("a_key1", None),
Column("a_key2", None),
Column("id", Integer, primary_key=True),
ForeignKeyConstraint(["a_key1", "a_key2"], ["a.key1", "a.key2"]),
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(b.c.a_key2.type, String)
def test_type_propagate_composite_fk_col(self):
metadata = MetaData()
a = Table(
"a",
metadata,
Column("key1", Integer, primary_key=True),
Column("key2", String(40), primary_key=True),
)
b = Table(
"b",
metadata,
Column("a_key1", None),
Column("a_key2", None),
Column("id", Integer, primary_key=True),
ForeignKeyConstraint(["a_key1", "a_key2"], [a.c.key1, a.c.key2]),
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(b.c.a_key2.type, String)
def test_type_propagate_standalone_fk_string(self):
metadata = MetaData()
Table("a", metadata, Column("key1", Integer, primary_key=True))
b = Table("b", metadata, Column("a_key1", None, ForeignKey("a.key1")))
assert isinstance(b.c.a_key1.type, Integer)
def test_type_propagate_standalone_fk_col(self):
metadata = MetaData()
a = Table("a", metadata, Column("key1", Integer, primary_key=True))
b = Table("b", metadata, Column("a_key1", None, ForeignKey(a.c.key1)))
assert isinstance(b.c.a_key1.type, Integer)
def test_type_propagate_chained_string_source_first(self):
metadata = MetaData()
Table("a", metadata, Column("key1", Integer, primary_key=True))
b = Table("b", metadata, Column("a_key1", None, ForeignKey("a.key1")))
c = Table(
"c", metadata, Column("b_key1", None, ForeignKey("b.a_key1"))
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(c.c.b_key1.type, Integer)
def test_type_propagate_chained_string_source_last(self):
metadata = MetaData()
b = Table("b", metadata, Column("a_key1", None, ForeignKey("a.key1")))
c = Table(
"c", metadata, Column("b_key1", None, ForeignKey("b.a_key1"))
)
Table("a", metadata, Column("key1", Integer, primary_key=True))
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(c.c.b_key1.type, Integer)
def test_type_propagate_chained_string_source_last_onname(self):
metadata = MetaData()
b = Table(
"b",
metadata,
Column(
"a_key1",
None,
ForeignKey("a.key1", link_to_name=True),
key="ak1",
),
)
c = Table(
"c",
metadata,
Column(
"b_key1",
None,
ForeignKey("b.a_key1", link_to_name=True),
key="bk1",
),
)
Table(
"a", metadata, Column("key1", Integer, primary_key=True, key="ak1")
)
assert isinstance(b.c.ak1.type, Integer)
assert isinstance(c.c.bk1.type, Integer)
def test_type_propagate_chained_string_source_last_onname_conflict(self):
metadata = MetaData()
b = Table(
"b",
metadata,
# b.c.key1 -> a.c.key1 -> String
Column(
"ak1",
None,
ForeignKey("a.key1", link_to_name=False),
key="key1",
),
# b.c.ak1 -> a.c.ak1 -> Integer
Column(
"a_key1",
None,
ForeignKey("a.key1", link_to_name=True),
key="ak1",
),
)
c = Table(
"c",
metadata,
# c.c.b_key1 -> b.c.ak1 -> Integer
Column("b_key1", None, ForeignKey("b.ak1", link_to_name=False)),
# c.c.b_ak1 -> b.c.ak1
Column("b_ak1", None, ForeignKey("b.ak1", link_to_name=True)),
)
Table(
"a",
metadata,
# a.c.key1
Column("ak1", String, key="key1"),
# a.c.ak1
Column("key1", Integer, primary_key=True, key="ak1"),
)
assert isinstance(b.c.key1.type, String)
assert isinstance(b.c.ak1.type, Integer)
assert isinstance(c.c.b_ak1.type, String)
assert isinstance(c.c.b_key1.type, Integer)
def test_type_propagate_chained_col_orig_first(self):
metadata = MetaData()
a = Table("a", metadata, Column("key1", Integer, primary_key=True))
b = Table("b", metadata, Column("a_key1", None, ForeignKey(a.c.key1)))
c = Table(
"c", metadata, Column("b_key1", None, ForeignKey(b.c.a_key1))
)
assert isinstance(b.c.a_key1.type, Integer)
assert isinstance(c.c.b_key1.type, Integer)
def test_column_accessor_col(self):
c1 = Column("x", Integer)
fk = ForeignKey(c1)
is_(fk.column, c1)
def test_column_accessor_clause_element(self):
c1 = Column("x", Integer)
class CThing:
def __init__(self, c):
self.c = c
def __clause_element__(self):
return self.c
fk = ForeignKey(CThing(c1))
is_(fk.column, c1)
def test_column_accessor_string_no_parent(self):
fk = ForeignKey("sometable.somecol")
assert_raises_message(
exc.InvalidRequestError,
"this ForeignKey object does not yet have a parent "
"Column associated with it.",
getattr,
fk,
"column",
)
def test_column_accessor_string_no_parent_table(self):
fk = ForeignKey("sometable.somecol")
Column("x", fk)
assert_raises_message(
exc.InvalidRequestError,
"this ForeignKey's parent column is not yet "
"associated with a Table.",
getattr,
fk,
"column",
)
def test_column_accessor_string_no_target_table(self):
fk = ForeignKey("sometable.somecol")
c1 = Column("x", fk)
Table("t", MetaData(), c1)
assert_raises_message(
exc.NoReferencedTableError,
"Foreign key associated with column 't.x' could not find "
"table 'sometable' with which to generate a "
"foreign key to target column 'somecol'",
getattr,
fk,
"column",
)
def test_column_accessor_string_no_target_column(self):
fk = ForeignKey("sometable.somecol")
c1 = Column("x", fk)
m = MetaData()
Table("t", m, c1)
Table("sometable", m, Column("notsomecol", Integer))
assert_raises_message(
exc.NoReferencedColumnError,
"Could not initialize target column for ForeignKey "
"'sometable.somecol' on table 't': "
"table 'sometable' has no column named 'somecol'",
getattr,
fk,
"column",
)
def test_remove_table_fk_bookkeeping(self):
metadata = MetaData()
fk = ForeignKey("t1.x")
t2 = Table("t2", metadata, Column("y", Integer, fk))
t3 = Table("t3", metadata, Column("y", Integer, ForeignKey("t1.x")))
assert t2.key in metadata.tables
assert ("t1", "x") in metadata._fk_memos
metadata.remove(t2)
# key is removed
assert t2.key not in metadata.tables
# the memo for the FK is still there
assert ("t1", "x") in metadata._fk_memos
# fk is not in the collection
assert fk not in metadata._fk_memos[("t1", "x")]
# make the referenced table
t1 = Table("t1", metadata, Column("x", Integer))
# t2 tells us exactly what's wrong
assert_raises_message(
exc.InvalidRequestError,
"Table t2 is no longer associated with its parent MetaData",
getattr,
fk,
"column",
)
# t3 is unaffected
assert t3.c.y.references(t1.c.x)
# remove twice OK
metadata.remove(t2)
def test_double_fk_usage_raises(self):
f = ForeignKey("b.id")
Column("x", Integer, f)
assert_raises(exc.InvalidRequestError, Column, "y", Integer, f)
def test_auto_append_constraint(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
for c in (
UniqueConstraint(t.c.a),
CheckConstraint(t.c.a > 5),
ForeignKeyConstraint([t.c.a], [t2.c.a]),
PrimaryKeyConstraint(t.c.a),
):
assert c in t.constraints
t.append_constraint(c)
assert c in t.constraints
c = Index("foo", t.c.a)
assert c in t.indexes
def test_auto_append_lowercase_table(self):
t = table("t", column("a"))
t2 = table("t2", column("a"))
for c in (
UniqueConstraint(t.c.a),
CheckConstraint(t.c.a > 5),
ForeignKeyConstraint([t.c.a], [t2.c.a]),
PrimaryKeyConstraint(t.c.a),
Index("foo", t.c.a),
):
assert True
def test_to_metadata_ok(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
UniqueConstraint(t.c.a)
CheckConstraint(t.c.a > 5)
ForeignKeyConstraint([t.c.a], [t2.c.a])
PrimaryKeyConstraint(t.c.a)
m2 = MetaData()
t3 = t.to_metadata(m2)
eq_(len(t3.constraints), 4)
for c in t3.constraints:
assert c.table is t3
def test_ColumnCollectionConstraint_copy(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
kw = {
"comment": "baz",
"name": "ccc",
"initially": "foo",
"deferrable": "bar",
}
UniqueConstraint(t.c.a, **kw)
CheckConstraint(t.c.a > 5, **kw)
ForeignKeyConstraint([t.c.a], [t2.c.a], **kw)
PrimaryKeyConstraint(t.c.a, **kw)
m2 = MetaData()
t3 = t.to_metadata(m2)
eq_(len(t3.constraints), 4)
for c in t3.constraints:
assert c.table is t3
for k, v in kw.items():
eq_(getattr(c, k), v)
def test_check_constraint_copy(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
ck = CheckConstraint(t.c.a > 5)
ck2 = ck._copy()
assert ck in t.constraints
assert ck2 not in t.constraints
def test_ambig_check_constraint_auto_append(self):
m = MetaData()
t = Table("tbl", m, Column("a", Integer), Column("b", Integer))
t2 = Table("t2", m, Column("a", Integer), Column("b", Integer))
c = CheckConstraint(t.c.a > t2.c.b)
assert c not in t.constraints
assert c not in t2.constraints
def test_auto_append_ck_on_col_attach_one(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
ck = CheckConstraint(a > b)
t = Table("tbl", m, a, b)
assert ck in t.constraints
def test_auto_append_ck_on_col_attach_two(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
ck = CheckConstraint(a > b + c)
t = Table("tbl", m, a)
assert ck not in t.constraints
t.append_column(b)
assert ck not in t.constraints
t.append_column(c)
assert ck in t.constraints
def test_auto_append_ck_on_col_attach_three(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
ck = CheckConstraint(a > b + c)
t = Table("tbl", m, a)
assert ck not in t.constraints
t.append_column(b)
assert ck not in t.constraints
t2 = Table("t2", m)
t2.append_column(c)
# two different tables, so CheckConstraint does nothing.
assert ck not in t.constraints
def test_auto_append_uq_on_col_attach_one(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
uq = UniqueConstraint(a, b)
t = Table("tbl", m, a, b)
assert uq in t.constraints
def test_auto_append_uq_on_col_attach_two(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
uq = UniqueConstraint(a, b, c)
t = Table("tbl", m, a)
assert uq not in t.constraints
t.append_column(b)
assert uq not in t.constraints
t.append_column(c)
assert uq in t.constraints
def test_auto_append_uq_on_col_attach_three(self):
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
uq = UniqueConstraint(a, b, c)
t = Table("tbl", m, a)
assert uq not in t.constraints
t.append_column(b)
assert uq not in t.constraints
t2 = Table("t2", m)
# two different tables, so UniqueConstraint raises
assert_raises_message(
exc.ArgumentError,
r"Column\(s\) 't2\.c' are not part of table 'tbl'\.",
t2.append_column,
c,
)
def test_auto_append_uq_on_col_attach_four(self):
"""Test that a uniqueconstraint that names Column and string names
won't autoattach using deferred column attachment.
"""
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
uq = UniqueConstraint(a, "b", "c")
t = Table("tbl", m, a)
assert uq not in t.constraints
t.append_column(b)
assert uq not in t.constraints
t.append_column(c)
# we don't track events for previously unknown columns
# named 'c' to be attached
assert uq not in t.constraints
t.append_constraint(uq)
assert uq in t.constraints
eq_(
[cn for cn in t.constraints if isinstance(cn, UniqueConstraint)],
[uq],
)
def test_auto_append_uq_on_col_attach_five(self):
"""Test that a uniqueconstraint that names Column and string names
*will* autoattach if the table has all those names up front.
"""
m = MetaData()
a = Column("a", Integer)
b = Column("b", Integer)
c = Column("c", Integer)
t = Table("tbl", m, a, c, b)
uq = UniqueConstraint(a, "b", "c")
assert uq in t.constraints
t.append_constraint(uq)
assert uq in t.constraints
eq_(
[cn for cn in t.constraints if isinstance(cn, UniqueConstraint)],
[uq],
)
def test_index_asserts_cols_standalone(self):
metadata = MetaData()
t1 = Table("t1", metadata, Column("x", Integer))
t2 = Table("t2", metadata, Column("y", Integer))
assert_raises_message(
exc.ArgumentError,
r"Column\(s\) 't2.y' are not part of table 't1'.",
Index,
"bar",
t1.c.x,
t2.c.y,
)
def test_index_asserts_cols_inline(self):
metadata = MetaData()
t1 = Table("t1", metadata, Column("x", Integer))
assert_raises_message(
exc.ArgumentError,
"Index 'bar' is against table 't1', and "
"cannot be associated with table 't2'.",
Table,
"t2",
metadata,
Column("y", Integer),
Index("bar", t1.c.x),
)
def test_raise_index_nonexistent_name(self):
m = MetaData()
with expect_raises_message(
exc.ConstraintColumnNotFoundError,
"Can't create Index on table 't': no column named 'q' is present.",
):
Table("t", m, Column("x", Integer), Index("foo", "q"))
def test_raise_not_a_column(self):
assert_raises(exc.ArgumentError, Index, "foo", 5)
def test_raise_expr_no_column(self):
idx = Index("foo", func.lower(5))
assert_raises_message(
exc.CompileError,
"Index 'foo' is not associated with any table.",
schema.CreateIndex(idx).compile,
dialect=testing.db.dialect,
)
assert_raises_message(
exc.CompileError,
"Index 'foo' is not associated with any table.",
schema.CreateIndex(idx).compile,
)
def test_no_warning_w_no_columns(self):
idx = Index(name="foo")
assert_raises_message(
exc.CompileError,
"Index 'foo' is not associated with any table.",
schema.CreateIndex(idx).compile,
dialect=testing.db.dialect,
)
assert_raises_message(
exc.CompileError,
"Index 'foo' is not associated with any table.",
schema.CreateIndex(idx).compile,
)
def test_raise_clauseelement_not_a_column(self):
m = MetaData()
t2 = Table("t2", m, Column("x", Integer))
class SomeClass:
def __clause_element__(self):
return t2
assert_raises_message(
exc.ArgumentError,
r"String column name or column expression for DDL constraint "
r"expected, got .*SomeClass",
Index,
"foo",
SomeClass(),
)
@testing.fixture
def no_pickle_annotated(self):
class NoPickle:
def __reduce__(self):
raise NotImplementedError()
class ClauseElement(operators.ColumnOperators):
def __init__(self, col):
self.col = col._annotate({"bar": NoPickle()})
def __clause_element__(self):
return self.col
def operate(self, op, *other, **kwargs):
return self.col.operate(op, *other, **kwargs)
m = MetaData()
t = Table("t", m, Column("q", Integer))
return t, ClauseElement(t.c.q)
def test_pickle_fk_annotated_col(self, no_pickle_annotated):
t, q_col = no_pickle_annotated
t2 = Table("t2", t.metadata, Column("p", ForeignKey(q_col)))
assert t2.c.p.references(t.c.q)
m2 = pickle.loads(pickle.dumps(t.metadata))
m2_t, m2_t2 = m2.tables["t"], m2.tables["t2"]
is_true(m2_t2.c.p.references(m2_t.c.q))
def test_pickle_uq_annotated_col(self, no_pickle_annotated):
t, q_col = no_pickle_annotated
t.append_constraint(UniqueConstraint(q_col))
m2 = pickle.loads(pickle.dumps(t.metadata))
const = [
c
for c in m2.tables["t"].constraints
if isinstance(c, UniqueConstraint)
][0]
is_true(const.columns[0].compare(t.c.q))
def test_pickle_idx_expr_annotated_col(self, no_pickle_annotated):
t, q_col = no_pickle_annotated
expr = q_col > 5
t.append_constraint(Index("conditional_index", expr))
m2 = pickle.loads(pickle.dumps(t.metadata))
const = list(m2.tables["t"].indexes)[0]
is_true(const.expressions[0].compare(expr))
def test_pickle_ck_binary_annotated_col(self, no_pickle_annotated):
t, q_col = no_pickle_annotated
ck = CheckConstraint(q_col > 5)
t.append_constraint(ck)
m2 = pickle.loads(pickle.dumps(t.metadata))
const = [
c
for c in m2.tables["t"].constraints
if isinstance(c, CheckConstraint)
][0]
is_true(const.sqltext.compare(ck.sqltext))
| ConstraintTest |
python | huggingface__transformers | src/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py | {
"start": 10909,
"end": 11965
} | class ____(GradientCheckpointingLayer):
def __init__(self, config, attn_implementation: str = "sdpa") -> None:
super().__init__()
self.norm1 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.norm2 = Qwen2RMSNorm(config.hidden_size, eps=1e-6)
self.attn = Qwen2_5_VLVisionAttention(config=config)
self.mlp = Qwen2_5_VLMLP(config, bias=True)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
rotary_pos_emb: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs,
) -> torch.Tensor:
hidden_states = hidden_states + self.attn(
self.norm1(hidden_states),
cu_seqlens=cu_seqlens,
rotary_pos_emb=rotary_pos_emb,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
return hidden_states
@auto_docstring
| Qwen2_5_VLVisionBlock |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_context_editing.py | {
"start": 519,
"end": 14686
} | class ____(FakeChatModel):
"""Fake chat model that counts tokens deterministically for tests."""
def get_num_tokens_from_messages(
self,
messages: list[MessageLikeRepresentation],
tools: Iterable | None = None, # noqa: ARG002
) -> int:
return sum(_count_message_tokens(message) for message in messages)
def _count_message_tokens(message: MessageLikeRepresentation) -> int:
if isinstance(message, (AIMessage, ToolMessage)):
return _count_content(message.content)
if isinstance(message, str):
return len(message)
return len(str(message))
def _count_content(content: MessageLikeRepresentation) -> int:
if isinstance(content, str):
return len(content)
if isinstance(content, list):
return sum(_count_content(block) for block in content) # type: ignore[arg-type]
if isinstance(content, dict):
return len(str(content))
return len(str(content))
def _make_state_and_request(
messages: list[AIMessage | ToolMessage],
*,
system_prompt: str | None = None,
) -> tuple[AgentState, ModelRequest]:
model = _TokenCountingChatModel()
conversation = list(messages)
state = cast(AgentState, {"messages": conversation})
request = ModelRequest(
model=model,
system_prompt=system_prompt,
messages=conversation,
tool_choice=None,
tools=[],
response_format=None,
state=state,
runtime=_fake_runtime(),
model_settings={},
)
return state, request
def test_no_edit_when_below_trigger() -> None:
tool_call_id = "call-1"
ai_message = AIMessage(
content="",
tool_calls=[{"id": tool_call_id, "name": "search", "args": {}}],
)
tool_message = ToolMessage(content="12345", tool_call_id=tool_call_id)
state, request = _make_state_and_request([ai_message, tool_message])
middleware = ContextEditingMiddleware(
edits=[ClearToolUsesEdit(trigger=50)],
)
modified_request = None
def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call wrap_model_call which creates a new request
middleware.wrap_model_call(request, mock_handler)
# The modified request passed to handler should be the same since no edits applied
assert modified_request is not None
assert modified_request.messages[0].content == ""
assert modified_request.messages[1].content == "12345"
# Original request should be unchanged
assert request.messages[0].content == ""
assert request.messages[1].content == "12345"
def test_clear_tool_outputs_and_inputs() -> None:
tool_call_id = "call-2"
ai_message = AIMessage(
content=[
{"type": "tool_call", "id": tool_call_id, "name": "search", "args": {"query": "foo"}}
],
tool_calls=[{"id": tool_call_id, "name": "search", "args": {"query": "foo"}}],
)
tool_message = ToolMessage(content="x" * 200, tool_call_id=tool_call_id)
state, request = _make_state_and_request([ai_message, tool_message])
edit = ClearToolUsesEdit(
trigger=50,
clear_at_least=10,
clear_tool_inputs=True,
keep=0,
placeholder="[cleared output]",
)
middleware = ContextEditingMiddleware(edits=[edit])
modified_request = None
def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call wrap_model_call which creates a new request with edits
middleware.wrap_model_call(request, mock_handler)
assert modified_request is not None
cleared_ai = modified_request.messages[0]
cleared_tool = modified_request.messages[1]
assert isinstance(cleared_tool, ToolMessage)
assert cleared_tool.content == "[cleared output]"
assert cleared_tool.response_metadata["context_editing"]["cleared"] is True
assert isinstance(cleared_ai, AIMessage)
assert cleared_ai.tool_calls[0]["args"] == {}
context_meta = cleared_ai.response_metadata.get("context_editing")
assert context_meta is not None
assert context_meta["cleared_tool_inputs"] == [tool_call_id]
# Original request should be unchanged
assert request.messages[0].tool_calls[0]["args"] == {"query": "foo"}
assert request.messages[1].content == "x" * 200
def test_respects_keep_last_tool_results() -> None:
conversation: list[AIMessage | ToolMessage] = []
edits = [
("call-a", "tool-output-a" * 5),
("call-b", "tool-output-b" * 5),
("call-c", "tool-output-c" * 5),
]
for call_id, text in edits:
conversation.append(
AIMessage(
content="",
tool_calls=[{"id": call_id, "name": "tool", "args": {"input": call_id}}],
)
)
conversation.append(ToolMessage(content=text, tool_call_id=call_id))
state, request = _make_state_and_request(conversation)
middleware = ContextEditingMiddleware(
edits=[
ClearToolUsesEdit(
trigger=50,
keep=1,
placeholder="[cleared]",
)
],
token_count_method="model",
)
modified_request = None
def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call wrap_model_call which creates a new request with edits
middleware.wrap_model_call(request, mock_handler)
assert modified_request is not None
cleared_messages = [
msg
for msg in modified_request.messages
if isinstance(msg, ToolMessage) and msg.content == "[cleared]"
]
assert len(cleared_messages) == 2
assert isinstance(modified_request.messages[-1], ToolMessage)
assert modified_request.messages[-1].content != "[cleared]"
def test_exclude_tools_prevents_clearing() -> None:
search_call = "call-search"
calc_call = "call-calc"
state, request = _make_state_and_request(
[
AIMessage(
content="",
tool_calls=[{"id": search_call, "name": "search", "args": {"query": "foo"}}],
),
ToolMessage(content="search-results" * 20, tool_call_id=search_call),
AIMessage(
content="",
tool_calls=[{"id": calc_call, "name": "calculator", "args": {"a": 1, "b": 2}}],
),
ToolMessage(content="42", tool_call_id=calc_call),
]
)
middleware = ContextEditingMiddleware(
edits=[
ClearToolUsesEdit(
trigger=50,
clear_at_least=10,
keep=0,
exclude_tools=("search",),
placeholder="[cleared]",
)
],
)
modified_request = None
def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call wrap_model_call which creates a new request with edits
middleware.wrap_model_call(request, mock_handler)
assert modified_request is not None
search_tool = modified_request.messages[1]
calc_tool = modified_request.messages[3]
assert isinstance(search_tool, ToolMessage)
assert search_tool.content == "search-results" * 20
assert isinstance(calc_tool, ToolMessage)
assert calc_tool.content == "[cleared]"
def _fake_runtime() -> Runtime:
return cast(Runtime, object())
async def test_no_edit_when_below_trigger_async() -> None:
"""Test async version of context editing with no edit when below trigger."""
tool_call_id = "call-1"
ai_message = AIMessage(
content="",
tool_calls=[{"id": tool_call_id, "name": "search", "args": {}}],
)
tool_message = ToolMessage(content="12345", tool_call_id=tool_call_id)
state, request = _make_state_and_request([ai_message, tool_message])
middleware = ContextEditingMiddleware(
edits=[ClearToolUsesEdit(trigger=50)],
)
modified_request = None
async def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call awrap_model_call which creates a new request
await middleware.awrap_model_call(request, mock_handler)
# The modified request passed to handler should be the same since no edits applied
assert modified_request is not None
assert modified_request.messages[0].content == ""
assert modified_request.messages[1].content == "12345"
# Original request should be unchanged
assert request.messages[0].content == ""
assert request.messages[1].content == "12345"
async def test_clear_tool_outputs_and_inputs_async() -> None:
"""Test async version of clearing tool outputs and inputs."""
tool_call_id = "call-2"
ai_message = AIMessage(
content=[
{"type": "tool_call", "id": tool_call_id, "name": "search", "args": {"query": "foo"}}
],
tool_calls=[{"id": tool_call_id, "name": "search", "args": {"query": "foo"}}],
)
tool_message = ToolMessage(content="x" * 200, tool_call_id=tool_call_id)
state, request = _make_state_and_request([ai_message, tool_message])
edit = ClearToolUsesEdit(
trigger=50,
clear_at_least=10,
clear_tool_inputs=True,
keep=0,
placeholder="[cleared output]",
)
middleware = ContextEditingMiddleware(edits=[edit])
modified_request = None
async def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call awrap_model_call which creates a new request with edits
await middleware.awrap_model_call(request, mock_handler)
assert modified_request is not None
cleared_ai = modified_request.messages[0]
cleared_tool = modified_request.messages[1]
assert isinstance(cleared_tool, ToolMessage)
assert cleared_tool.content == "[cleared output]"
assert cleared_tool.response_metadata["context_editing"]["cleared"] is True
assert isinstance(cleared_ai, AIMessage)
assert cleared_ai.tool_calls[0]["args"] == {}
context_meta = cleared_ai.response_metadata.get("context_editing")
assert context_meta is not None
assert context_meta["cleared_tool_inputs"] == [tool_call_id]
# Original request should be unchanged
assert request.messages[0].tool_calls[0]["args"] == {"query": "foo"}
assert request.messages[1].content == "x" * 200
async def test_respects_keep_last_tool_results_async() -> None:
"""Test async version respects keep parameter for last tool results."""
conversation: list[AIMessage | ToolMessage] = []
edits = [
("call-a", "tool-output-a" * 5),
("call-b", "tool-output-b" * 5),
("call-c", "tool-output-c" * 5),
]
for call_id, text in edits:
conversation.append(
AIMessage(
content="",
tool_calls=[{"id": call_id, "name": "tool", "args": {"input": call_id}}],
)
)
conversation.append(ToolMessage(content=text, tool_call_id=call_id))
state, request = _make_state_and_request(conversation)
middleware = ContextEditingMiddleware(
edits=[
ClearToolUsesEdit(
trigger=50,
keep=1,
placeholder="[cleared]",
)
],
token_count_method="model",
)
modified_request = None
async def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call awrap_model_call which creates a new request with edits
await middleware.awrap_model_call(request, mock_handler)
assert modified_request is not None
cleared_messages = [
msg
for msg in modified_request.messages
if isinstance(msg, ToolMessage) and msg.content == "[cleared]"
]
assert len(cleared_messages) == 2
assert isinstance(modified_request.messages[-1], ToolMessage)
assert modified_request.messages[-1].content != "[cleared]"
async def test_exclude_tools_prevents_clearing_async() -> None:
"""Test async version of excluding tools from clearing."""
search_call = "call-search"
calc_call = "call-calc"
state, request = _make_state_and_request(
[
AIMessage(
content="",
tool_calls=[{"id": search_call, "name": "search", "args": {"query": "foo"}}],
),
ToolMessage(content="search-results" * 20, tool_call_id=search_call),
AIMessage(
content="",
tool_calls=[{"id": calc_call, "name": "calculator", "args": {"a": 1, "b": 2}}],
),
ToolMessage(content="42", tool_call_id=calc_call),
]
)
middleware = ContextEditingMiddleware(
edits=[
ClearToolUsesEdit(
trigger=50,
clear_at_least=10,
keep=0,
exclude_tools=("search",),
placeholder="[cleared]",
)
],
)
modified_request = None
async def mock_handler(req: ModelRequest) -> AIMessage:
nonlocal modified_request
modified_request = req
return AIMessage(content="mock response")
# Call awrap_model_call which creates a new request with edits
await middleware.awrap_model_call(request, mock_handler)
assert modified_request is not None
search_tool = modified_request.messages[1]
calc_tool = modified_request.messages[3]
assert isinstance(search_tool, ToolMessage)
assert search_tool.content == "search-results" * 20
assert isinstance(calc_tool, ToolMessage)
assert calc_tool.content == "[cleared]"
| _TokenCountingChatModel |
python | huggingface__transformers | src/transformers/models/lfm2/modular_lfm2.py | {
"start": 20152,
"end": 20270
} | class ____(LlamaForCausalLM):
pass
__all__ = ["Lfm2ForCausalLM", "Lfm2Model", "Lfm2PreTrainedModel"]
| Lfm2ForCausalLM |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/solarization_test.py | {
"start": 189,
"end": 2574
} | class ____(testing.TestCase):
def _test_input_output(self, layer, input_value, expected_value, dtype):
input = np.ones(shape=(2, 224, 224, 3), dtype=dtype) * input_value
expected_output = ops.clip(
(
np.ones(shape=(2, 224, 224, 3), dtype=layer.compute_dtype)
* expected_value
),
0,
255,
)
output = layer(input)
self.assertAllClose(output, expected_output)
@pytest.mark.requires_trainable_backend
def test_layer(self):
self.run_layer_test(
layers.Solarization,
init_kwargs={
"addition_factor": 0.75,
"value_range": (20, 200),
"threshold_factor": (0, 1),
"seed": 1,
},
input_shape=(8, 3, 4, 3),
supports_masking=False,
expected_output_shape=(8, 3, 4, 3),
)
@parameterized.named_parameters(
("0_255", 0, 255),
("64_191", 64, 191),
("127_128", 127, 128),
("191_64", 191, 64),
("255_0", 255, 0),
)
def test_output_values(self, input_value, expected_value):
solarization = layers.Solarization(value_range=(0, 255))
self._test_input_output(
layer=solarization,
input_value=input_value,
expected_value=expected_value,
dtype="uint8",
)
@parameterized.named_parameters(
("0_0", 0, 0),
("191_64", 191, 64),
("255_0", 255, 0),
)
def test_only_values_above_threshold_are_solarized(
self, input_value, output_value
):
solarization = layers.Solarization(
threshold_factor=(128.0 / 255.0, 128.0 / 255.0),
value_range=(0, 255),
)
self._test_input_output(
layer=solarization,
input_value=input_value,
expected_value=output_value,
dtype="uint8",
)
def test_random_augmentation_applied_per_sample(self):
image = random.uniform((16, 16, 3), minval=0, maxval=255)
images = ops.stack([image, image])
layer = layers.Solarization(
value_range=(0, 255), threshold_factor=0.5, addition_factor=0.5
)
outputs = layer(images)
self.assertNotAllClose(outputs[0], outputs[1])
| SolarizationTest |
python | huggingface__transformers | src/transformers/models/rag/modeling_rag.py | {
"start": 22328,
"end": 37484
} | class ____(RagPreTrainedModel):
def __init__(
self,
config: Optional[PreTrainedConfig] = None,
question_encoder: Optional[PreTrainedModel] = None,
generator: Optional[PreTrainedModel] = None,
retriever: Optional[RagRetriever] = None, # or maybe just use a `set_retriever(...)` method
**kwargs,
):
r"""
question_encoder (`PreTrainedModel`, *optional*):
The model responsible for encoding the question into hidden states for retrieval.
generator (`PreTrainedModel`, *optional*):
The model responsible for generating text based on retrieved documents.
retriever (`RagRetriever`, *optional*):
The component responsible for retrieving documents from a knowledge base given the encoded question.
"""
assert config is not None or (question_encoder is not None and generator is not None), (
"Either a configuration or an question_encoder and a generator has to be provided."
)
if config is None:
config = RagConfig.from_question_encoder_generator_configs(
question_encoder.config, generator.config, **kwargs
)
else:
assert isinstance(config, self.config_class), f"config: {config} has to be of type {self.config_class}"
super().__init__(config)
if question_encoder is None:
from ..auto.modeling_auto import AutoModel
question_encoder = AutoModel.from_config(config.question_encoder)
if generator is None:
from ..auto.modeling_auto import AutoModelForSeq2SeqLM
generator = AutoModelForSeq2SeqLM.from_config(config.generator)
self.retriever = retriever
if self.retriever is not None:
assert isinstance(retriever, RagRetriever), (
f"`self.retriever` is of type {type(self.retriever)}, but should be of type `RagRetriever`"
)
self.retriever = retriever
self.question_encoder = question_encoder
self.generator = generator
self.ctx_encoder = None
self.context_encoder_training = False
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
encoder_outputs: Optional[tuple[tuple[torch.FloatTensor]]] = None,
decoder_input_ids: Optional[torch.LongTensor] = None,
decoder_attention_mask: Optional[torch.BoolTensor] = None,
past_key_values: Optional[Cache] = None,
doc_scores: Optional[torch.FloatTensor] = None,
context_input_ids: Optional[torch.LongTensor] = None,
context_attention_mask: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
output_retrieved: Optional[bool] = None,
n_docs: Optional[int] = None,
) -> Union[tuple[torch.Tensor], RetrievAugLMOutput]:
r"""
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
obtain the indices.
[What are input IDs?](../glossary#input-ids)
encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*)
Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
*optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
generator's encoder.
Used by the ([`RagModel`]) model during decoding.
decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Provide for generation tasks. `None` by default, construct as per instructions for the generator model
you're using with your RAG instance.
decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
be used by default.
doc_scores (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`):
Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
`question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
has to be provided to the forward pass. `doc_scores` can be computed via
`question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
context_input_ids (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
retriever. If the model was not initialized with a `retriever` ``context_input_ids` has to be provided to
the forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
context_attention_mask (`torch.LongTensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`,*optional*, returned when *output_retrieved=True*):
Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
retriever. If the model has is not initialized with a `retriever` `context_attention_mask` has to be
provided to the forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
output_retrieved (`bool`, *optional*):
Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
`context_attention_mask`. See returned tensors for more detail.
n_docs (`int`, *optional*):
The number of documents to retrieve.
Example:
```python
>>> from transformers import AutoTokenizer, RagRetriever, RagModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
>>> retriever = RagRetriever.from_pretrained(
... "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
... )
>>> # initialize with RagRetriever to do everything in one forward call
>>> model = RagModel.from_pretrained("facebook/rag-token-base", retriever=retriever)
>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> outputs = model(input_ids=inputs["input_ids"])
```"""
n_docs = n_docs if n_docs is not None else self.config.n_docs
use_cache = use_cache if use_cache is not None else self.config.use_cache
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
output_retrieved = output_retrieved if output_retrieved is not None else self.config.output_retrieved
# whether retriever has to be used
has_to_retrieve = (
self.retriever is not None
and (context_input_ids is None or context_attention_mask is None or doc_scores is None)
and encoder_outputs is None
)
# encoder_outputs are pre-computed during RAG-token generation
if encoder_outputs is None:
if has_to_retrieve:
question_enc_outputs = self.question_encoder(
input_ids, attention_mask=attention_mask, return_dict=True
)
question_encoder_last_hidden_state = question_enc_outputs[0] # hidden states of question encoder
retriever_outputs = self.retriever(
input_ids,
question_encoder_last_hidden_state.detach().to(device="cpu", dtype=torch.float32).numpy(),
prefix=self.generator.config.prefix,
n_docs=n_docs,
return_tensors="pt",
)
if self.context_encoder_training:
(
context_input_ids,
context_attention_mask,
retrieved_doc_embeds,
retrieved_doc_input_ids,
retrieved_doc_attention_mask,
retrieved_doc_ids,
) = (
retriever_outputs["context_input_ids"],
retriever_outputs["context_attention_mask"],
retriever_outputs["retrieved_doc_embeds"],
retriever_outputs["tokenized_doc_ids"],
retriever_outputs["tokenized_doc_attention_mask"],
retriever_outputs["doc_ids"],
)
context_input_ids = context_input_ids.to(input_ids)
context_attention_mask = context_attention_mask.to(input_ids)
retrieved_doc_input_ids = retrieved_doc_input_ids.to(input_ids)
retrieved_doc_attention_mask = retrieved_doc_attention_mask.to(input_ids)
retrieved_doc_embeds = self.ctx_encoder(
retrieved_doc_input_ids, attention_mask=retrieved_doc_attention_mask, return_dict=True
).pooler_output
retrieved_doc_embeds = retrieved_doc_embeds.view(
-1, n_docs, question_encoder_last_hidden_state.shape[1]
) # reshaping
# compute doc_scores involving ctx_encoder
doc_scores = torch.bmm(
question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
).squeeze(1)
else:
context_input_ids, context_attention_mask, retrieved_doc_embeds, retrieved_doc_ids = (
retriever_outputs["context_input_ids"],
retriever_outputs["context_attention_mask"],
retriever_outputs["retrieved_doc_embeds"],
retriever_outputs["doc_ids"],
)
# set to correct device
retrieved_doc_embeds = retrieved_doc_embeds.to(question_encoder_last_hidden_state)
context_input_ids = context_input_ids.to(input_ids)
context_attention_mask = context_attention_mask.to(input_ids)
# compute doc_scores
doc_scores = torch.bmm(
question_encoder_last_hidden_state.unsqueeze(1), retrieved_doc_embeds.transpose(1, 2)
).squeeze(1)
else:
assert context_input_ids is not None, (
"Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can"
" set a retriever using the `set_retriever(...)` function."
)
assert context_attention_mask is not None, (
"Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you"
" can set a retriever using the `set_retriever(...)` function."
)
assert doc_scores is not None, (
"Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a"
" retriever using the `set_retriever(...)` function."
)
assert doc_scores is not None, (
"Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function."
)
assert (doc_scores.shape[1] % n_docs) == 0, (
f" The first dimension of `context_input_ids` should be a multiple of `n_docs`={n_docs}, but is"
f" {context_input_ids.shape[0]}."
)
# Decoder input without context documents
if decoder_input_ids is not None:
decoder_input_ids = decoder_input_ids.repeat_interleave(n_docs, dim=0)
if decoder_attention_mask is not None:
decoder_attention_mask = decoder_attention_mask.repeat_interleave(n_docs, dim=0)
gen_outputs = self.generator(
input_ids=context_input_ids,
attention_mask=context_attention_mask,
encoder_outputs=encoder_outputs,
decoder_input_ids=decoder_input_ids,
decoder_attention_mask=decoder_attention_mask,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
return_dict=True,
)
if not has_to_retrieve:
question_encoder_last_hidden_state = None
question_enc_hidden_states = None
question_enc_attentions = None
retrieved_doc_embeds = None
retrieved_doc_ids = None
else:
question_enc_hidden_states = question_enc_outputs.hidden_states
question_enc_attentions = question_enc_outputs.attentions
if not has_to_retrieve or not output_retrieved:
# don't output retrieved docs
context_input_ids = (None,)
context_attention_mask = None
retrieved_doc_embeds = None
retrieved_doc_ids = None
return RetrievAugLMOutput(
logits=gen_outputs.logits,
doc_scores=doc_scores,
past_key_values=gen_outputs.past_key_values,
context_input_ids=context_input_ids,
context_attention_mask=context_attention_mask,
retrieved_doc_embeds=retrieved_doc_embeds,
retrieved_doc_ids=retrieved_doc_ids,
question_encoder_last_hidden_state=question_encoder_last_hidden_state,
question_enc_hidden_states=question_enc_hidden_states,
question_enc_attentions=question_enc_attentions,
generator_enc_last_hidden_state=gen_outputs.encoder_last_hidden_state,
generator_enc_hidden_states=gen_outputs.encoder_hidden_states,
generator_enc_attentions=gen_outputs.encoder_attentions,
generator_dec_hidden_states=gen_outputs.decoder_hidden_states,
generator_dec_attentions=gen_outputs.decoder_attentions,
generator_cross_attentions=gen_outputs.cross_attentions,
)
@auto_docstring(
custom_intro="""
A RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.
"""
)
| RagModel |
python | pytorch__pytorch | test/typing/reveal/module_list.py | {
"start": 102,
"end": 293
} | class ____(torch.nn.Module):
pass
ml: torch.nn.ModuleList = torch.nn.ModuleList([FooModule(), BarModule()])
ml[0].children() == [] # noqa: B015
reveal_type(ml) # E: {ModuleList}
| BarModule |
python | google__jax | jax/_src/core.py | {
"start": 48012,
"end": 48484
} | class ____:
__slots__ = ['prev', 'name_size_pairs']
def __init__(self, name_size_pairs: Iterable[tuple[AxisName, int]]):
self.name_size_pairs = name_size_pairs
def __enter__(self):
self.prev = trace_ctx.axis_env
trace_ctx.set_axis_env(self.prev.extend_pure(self.name_size_pairs))
def __exit__(self, exc_type, exc_value, traceback):
trace_ctx.set_axis_env(self.prev)
extend_axis_env_nd = ExtendAxisEnvNdContextManager
| ExtendAxisEnvNdContextManager |
python | joke2k__faker | faker/proxy.py | {
"start": 12759,
"end": 14007
} | class ____:
"""
Return either a fake value or None, with a customizable probability.
"""
def __init__(self, proxy: Faker):
self._proxy = proxy
def __getattr__(self, name: str) -> Any:
obj = getattr(self._proxy, name)
if callable(obj):
return self._wrap(name, obj)
else:
raise TypeError("Accessing non-functions through .optional is not supported.")
def __getstate__(self):
# Copy the object's state from self.__dict__ which contains
# all our instance attributes. Always use the dict.copy()
# method to avoid modifying the original state.
state = self.__dict__.copy()
return state
def __setstate__(self, state):
self.__dict__.update(state)
def _wrap(self, name: str, function: Callable[..., RetType]) -> Callable[..., RetType | None]:
@functools.wraps(function)
def wrapper(*args: Any, prob: float = 0.5, **kwargs: Any) -> RetType | None:
if not 0 < prob <= 1.0:
raise ValueError("prob must be between 0 and 1")
return function(*args, **kwargs) if self._proxy.boolean(chance_of_getting_true=int(prob * 100)) else None
return wrapper
| OptionalProxy |
python | lepture__authlib | authlib/jose/rfc7518/oct_key.py | {
"start": 388,
"end": 2744
} | class ____(Key):
"""Key class of the ``oct`` key type."""
kty = "oct"
REQUIRED_JSON_FIELDS = ["k"]
def __init__(self, raw_key=None, options=None):
super().__init__(options)
self.raw_key = raw_key
@property
def public_only(self):
return False
def get_op_key(self, operation):
"""Get the raw key for the given key_op. This method will also
check if the given key_op is supported by this key.
:param operation: key operation value, such as "sign", "encrypt".
:return: raw key
"""
self.check_key_op(operation)
if not self.raw_key:
self.load_raw_key()
return self.raw_key
def load_raw_key(self):
self.raw_key = urlsafe_b64decode(to_bytes(self.tokens["k"]))
def load_dict_key(self):
k = to_unicode(urlsafe_b64encode(self.raw_key))
self._dict_data = {"kty": self.kty, "k": k}
def as_dict(self, is_private=False, **params):
tokens = self.tokens
if "kid" not in tokens:
tokens["kid"] = self.thumbprint()
tokens.update(params)
return tokens
@classmethod
def validate_raw_key(cls, key):
return isinstance(key, bytes)
@classmethod
def import_key(cls, raw, options=None):
"""Import a key from bytes, string, or dict data."""
if isinstance(raw, cls):
if options is not None:
raw.options.update(options)
return raw
if isinstance(raw, dict):
cls.check_required_fields(raw)
key = cls(options=options)
key._dict_data = raw
else:
raw_key = to_bytes(raw)
# security check
if raw_key.startswith(POSSIBLE_UNSAFE_KEYS):
raise ValueError("This key may not be safe to import")
key = cls(raw_key=raw_key, options=options)
return key
@classmethod
def generate_key(cls, key_size=256, options=None, is_private=True):
"""Generate a ``OctKey`` with the given bit size."""
if not is_private:
raise ValueError("oct key can not be generated as public")
if key_size % 8 != 0:
raise ValueError("Invalid bit size for oct key")
return cls.import_key(secrets.token_bytes(int(key_size / 8)), options)
| OctKey |
python | walkccc__LeetCode | solutions/786. K-th Smallest Prime Fraction/786.py | {
"start": 0,
"end": 575
} | class ____:
def kthSmallestPrimeFraction(self, arr: list[int], k: int) -> list[int]:
n = len(arr)
ans = [0, 1]
l = 0
r = 1
while True:
m = (l + r) / 2
ans[0] = 0
count = 0
j = 1
for i in range(n):
while j < n and arr[i] > m * arr[j]:
j += 1
count += n - j
if j == n:
break
if ans[0] * arr[j] < ans[1] * arr[i]:
ans[0] = arr[i]
ans[1] = arr[j]
if count < k:
l = m
elif count > k:
r = m
else:
return ans
| Solution |
python | pytorch__pytorch | torch/_decomp/decompositions_for_rng.py | {
"start": 2051,
"end": 3558
} | class ____:
"""
Represents a PhiloxRngState - (seed, offset) where offset = base_offset +
relative_offset. seed and base_offset basically point to the rng state just
before tracing starts. relative offset tracks the totally consumed offset at
trace time.
"""
def __init__(self) -> None:
self.reset()
def reset(self):
self.seed = torch.tensor(())
self.base_offset = torch.tensor(())
self.relative_offset = 0
self.offset_advanced_alteast_once = False
def validate_state(self):
assert self.seed.numel() != 0 and self.base_offset.numel() != 0
def advance_offset(self, consumed_offset):
self.offset_advanced_alteast_once = True
self.relative_offset = self.relative_offset + consumed_offset
def set_state(self, seed, base_offset, relative_offset=0):
self.seed = seed
self.base_offset = base_offset
self.relative_offset = relative_offset
def get_state_as_tuple(self):
self.validate_state()
return (self.seed, self.base_offset + self.relative_offset)
def get_state_as_tensor(self):
# Only needed because we override get_rng_state.
self.validate_state()
return torch.stack([self.seed, self.base_offset + self.relative_offset])
def set_state_from_tensor(self, state):
# Only needed because we override set_rng_state.
self.seed, self.base_offset = torch.unbind(state)
self.relative_offset = 0
| PhiloxState |
python | sqlalchemy__sqlalchemy | test/base/test_events.py | {
"start": 9616,
"end": 12560
} | class ____(TearDownLocalEventsFixture, fixtures.TestBase):
def _fixture(self):
class TargetEventsOne(event.Events):
def event_one(self, x, y):
pass
def event_two(self, x, y, **kw):
pass
def event_five(self, x, y, z, q):
pass
class TargetOne:
dispatch = event.dispatcher(TargetEventsOne)
return TargetOne
def _wrapped_fixture(self):
class TargetEvents(event.Events):
@classmethod
def _listen(cls, event_key):
fn = event_key._listen_fn
def adapt(*args):
fn(*["adapted %s" % arg for arg in args])
event_key = event_key.with_wrapper(adapt)
event_key.base_listen()
def event_one(self, x, y):
pass
def event_five(self, x, y, z, q):
pass
class Target:
dispatch = event.dispatcher(TargetEvents)
return Target
def test_kw_accept(self):
TargetOne = self._fixture()
canary = Mock()
@event.listens_for(TargetOne, "event_one", named=True)
def handler1(**kw):
canary(kw)
TargetOne().dispatch.event_one(4, 5)
eq_(canary.mock_calls, [call({"x": 4, "y": 5})])
def test_kw_accept_wrapped(self):
TargetOne = self._wrapped_fixture()
canary = Mock()
@event.listens_for(TargetOne, "event_one", named=True)
def handler1(**kw):
canary(kw)
TargetOne().dispatch.event_one(4, 5)
eq_(canary.mock_calls, [call({"y": "adapted 5", "x": "adapted 4"})])
def test_partial_kw_accept(self):
TargetOne = self._fixture()
canary = Mock()
@event.listens_for(TargetOne, "event_five", named=True)
def handler1(z, y, **kw):
canary(z, y, kw)
TargetOne().dispatch.event_five(4, 5, 6, 7)
eq_(canary.mock_calls, [call(6, 5, {"x": 4, "q": 7})])
def test_partial_kw_accept_wrapped(self):
TargetOne = self._wrapped_fixture()
canary = Mock()
@event.listens_for(TargetOne, "event_five", named=True)
def handler1(z, y, **kw):
canary(z, y, kw)
TargetOne().dispatch.event_five(4, 5, 6, 7)
eq_(
canary.mock_calls,
[
call(
"adapted 6",
"adapted 5",
{"q": "adapted 7", "x": "adapted 4"},
)
],
)
def test_kw_accept_plus_kw(self):
TargetOne = self._fixture()
canary = Mock()
@event.listens_for(TargetOne, "event_two", named=True)
def handler1(**kw):
canary(kw)
TargetOne().dispatch.event_two(4, 5, z=8, q=5)
eq_(canary.mock_calls, [call({"x": 4, "y": 5, "z": 8, "q": 5})])
| NamedCallTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_protect03.py | {
"start": 315,
"end": 1067
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("protect03.xlsx")
def test_create_file(self):
"""Test the a simple XlsxWriter file with worksheet protection."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
unlocked = workbook.add_format({"locked": 0, "hidden": 0})
hidden = workbook.add_format({"locked": 0, "hidden": 1})
worksheet.protect("password")
worksheet.write("A1", 1)
worksheet.write("A2", 2, unlocked)
worksheet.write("A3", 3, hidden)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/storage_tests/branching_io_manager_tests/utils.py | {
"start": 4437,
"end": 6636
} | class ____(dg.ConfigurableIOManager):
"""ConfigurableResource version of the above. This is useful for testing
that the config system is working correctly & to test the setup/teardown logic.
"""
name: str
_values: dict = PrivateAttr(default={})
def setup_for_execution(self, context: InitResourceContext) -> None:
self._values = {}
LOG.append(f"setup_for_execution {self.name}")
def teardown_after_execution(self, context: InitResourceContext) -> None:
LOG.append(f"teardown_after_execution {self.name}")
def handle_output(self, context: OutputContext, obj: Any):
keys = self._keys_from_context(context)
if keys is None:
self._values[None] = obj
else:
for key in keys:
self._values[key] = obj
def load_input(self, context: InputContext) -> Any:
keys = self._keys_from_context(context)
if keys is None:
return self.values[None]
else:
return (
{key[-1]: self._values[key] for key in keys}
if len(keys) > 1
else self._values[keys[0]]
)
def has_value(
self, asset_key: CoercibleToAssetKey, partition_key: Optional[str] = None
) -> bool:
return self._get_key(AssetKey.from_coercible(asset_key), partition_key) in self._values
def get_value(self, asset_key: CoercibleToAssetKey, partition_key: Optional[str] = None) -> Any:
return self._values.get(self._get_key(AssetKey.from_coercible(asset_key), partition_key))
def _keys_from_context(
self, context: Union[dg.InputContext, dg.OutputContext]
) -> Optional[Sequence[tuple[str, ...]]]:
if not context.has_asset_key:
return None
partition_keys = context.asset_partition_keys if context.has_asset_partitions else [None]
return [self._get_key(context.asset_key, partition_key) for partition_key in partition_keys]
def _get_key(self, asset_key: AssetKey, partition_key: Optional[str]) -> tuple:
return tuple([*asset_key.path] + [partition_key] if partition_key is not None else [])
| ConfigurableAssetBasedInMemoryIOManager |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 35573,
"end": 36108
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.conv = nn.Conv1d(
config.output_hidden_size,
2 * config.output_hidden_size,
config.adapter_kernel_size,
stride=config.adapter_stride,
padding=1,
)
def forward(self, hidden_states):
hidden_states = self.conv(hidden_states)
hidden_states = nn.functional.glu(hidden_states, dim=1)
return hidden_states
@auto_docstring
| Wav2Vec2ConformerAdapterLayer |
python | numba__numba | numba/experimental/jitclass/base.py | {
"start": 655,
"end": 1325
} | class ____(models.StructModel):
def __init__(self, dmm, fe_typ):
cls_data_ty = types.ClassDataType(fe_typ)
# MemInfoPointer uses the `dtype` attribute to traverse for nested
# NRT MemInfo. Since we handle nested NRT MemInfo ourselves,
# we will replace provide MemInfoPointer with an opaque type
# so that it does not raise exception for nested meminfo.
dtype = types.Opaque('Opaque.' + str(cls_data_ty))
members = [
('meminfo', types.MemInfoPointer(dtype)),
('data', types.CPointer(cls_data_ty)),
]
super(InstanceModel, self).__init__(dmm, fe_typ, members)
| InstanceModel |
python | hynek__structlog | tests/test_testing.py | {
"start": 4930,
"end": 5587
} | class ____:
def test_builds_returnloggers(self):
"""
Factory returns ReturnLoggers.
"""
f = ReturnLoggerFactory()
assert isinstance(f(), ReturnLogger)
def test_caches(self):
"""
There's no need to have several loggers so we return the same one on
each call.
"""
f = ReturnLoggerFactory()
assert f() is f()
def test_ignores_args(self):
"""
ReturnLogger doesn't take positional arguments. If any are passed to
the factory, they are not passed to the logger.
"""
ReturnLoggerFactory()(1, 2, 3)
| TestReturnLoggerFactory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1530256,
"end": 1530681
} | class ____(
sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData, TeamAuditEntryData
):
"""Audit log entry for a team.remove_repository event."""
__schema__ = github_schema
__field_names__ = ("is_ldap_mapped",)
is_ldap_mapped = sgqlc.types.Field(Boolean, graphql_name="isLdapMapped")
"""Whether the team was mapped to an LDAP Group."""
| TeamRemoveRepositoryAuditEntry |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_authorizations.py | {
"start": 9495,
"end": 15181
} | class ____(TestCase):
@HttpMocker()
def test_given_no_state_when_read_then_use_authorizations_endpoint(self, http_mocker: HttpMocker) -> None:
cursor_value = int(_A_START_DATE.timestamp()) + 1
http_mocker.get(
_authorizations_request().with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(),
_authorizations_response().with_record(_an_authorization().with_cursor(cursor_value)).build(),
)
output = self._read(_config().with_start_date(_A_START_DATE), _NO_STATE)
most_recent_state = output.most_recent_state
assert most_recent_state.stream_descriptor == StreamDescriptor(name=_STREAM_NAME)
assert most_recent_state.stream_state.updated == str(cursor_value)
@HttpMocker()
def test_given_state_when_read_then_query_events_using_types_and_state_value_plus_1(self, http_mocker: HttpMocker) -> None:
start_date = _NOW - timedelta(days=40)
state_datetime = _NOW - timedelta(days=5)
cursor_value = int(state_datetime.timestamp()) + 1
http_mocker.get(
_events_request().with_created_gte(state_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response()
.with_record(_an_event().with_cursor(cursor_value).with_field(_DATA_FIELD, _an_authorization().build()))
.build(),
)
output = self._read(
_config().with_start_date(start_date),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
most_recent_state = output.most_recent_state
assert most_recent_state.stream_descriptor == StreamDescriptor(name=_STREAM_NAME)
assert most_recent_state.stream_state.updated == str(cursor_value)
@HttpMocker()
def test_given_state_and_pagination_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
state_datetime = _NOW - timedelta(days=5)
http_mocker.get(
_events_request().with_created_gte(state_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response()
.with_pagination()
.with_record(_an_event().with_id("last_record_id_from_first_page").with_field(_DATA_FIELD, _an_authorization().build()))
.build(),
)
http_mocker.get(
_events_request()
.with_starting_after("last_record_id_from_first_page")
.with_created_gte(state_datetime)
.with_created_lte(_NOW)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._an_authorization_event()).build(),
)
output = self._read(
_config(),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
assert len(output.records) == 2
@HttpMocker()
def test_given_state_and_small_slice_range_when_read_then_perform_multiple_queries(self, http_mocker: HttpMocker) -> None:
state_datetime = _NOW - timedelta(days=5)
slice_range = timedelta(days=3)
slice_datetime = state_datetime + slice_range
http_mocker.get(
_events_request()
.with_created_gte(state_datetime)
.with_created_lte(slice_datetime - _AVOIDING_INCLUSIVE_BOUNDARIES)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._an_authorization_event()).build(),
)
http_mocker.get(
_events_request().with_created_gte(slice_datetime).with_created_lte(_NOW).with_limit(100).with_types(_EVENT_TYPES).build(),
_events_response().with_record(self._an_authorization_event()).with_record(self._an_authorization_event()).build(),
)
output = self._read(
_config().with_start_date(_NOW - timedelta(days=30)).with_slice_range_in_days(slice_range.days),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_datetime.timestamp())}).build(),
)
assert len(output.records) == 3
@HttpMocker()
def test_given_state_earlier_than_30_days_when_read_then_query_events_using_types_and_event_lower_boundary(
self, http_mocker: HttpMocker
) -> None:
# this seems odd as we would miss some data between start_date and events_lower_boundary. In that case, we should hit the
# authorizations endpoint
start_date = _NOW - timedelta(days=40)
state_value = _NOW - timedelta(days=39)
events_lower_boundary = _NOW - timedelta(days=30)
http_mocker.get(
_events_request()
.with_created_gte(events_lower_boundary)
.with_created_lte(_NOW)
.with_limit(100)
.with_types(_EVENT_TYPES)
.build(),
_events_response().with_record(self._an_authorization_event()).build(),
)
self._read(
_config().with_start_date(start_date),
StateBuilder().with_stream_state(_STREAM_NAME, {"updated": int(state_value.timestamp())}).build(),
)
# request matched http_mocker
def _an_authorization_event(self) -> RecordBuilder:
return _an_event().with_field(_DATA_FIELD, _an_authorization().build())
def _read(self, config: ConfigBuilder, state: Optional[Dict[str, Any]], expecting_exception: bool = False) -> EntrypointOutput:
return _read(config, SyncMode.incremental, state, expecting_exception)
| IncrementalTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadOverride1.py | {
"start": 458,
"end": 536
} | class ____:
def foo(self, x: int | str) -> int | str:
return x
| Base2 |
python | numpy__numpy | numpy/_core/_exceptions.py | {
"start": 1871,
"end": 2095
} | class ____(UFuncTypeError):
def __init__(self, ufunc, casting, from_, to):
super().__init__(ufunc)
self.casting = casting
self.from_ = from_
self.to = to
@_display_as_base
| _UFuncCastingError |
python | pypa__packaging | tests/test_tags.py | {
"start": 5765,
"end": 7233
} | class ____:
def test_warn(self, monkeypatch: pytest.MonkeyPatch) -> None:
class MockConfigVar:
def __init__(self, return_: str) -> None:
self.warn: bool | None = None
self._return = return_
def __call__(self, _name: str, warn: bool = False) -> str:
self.warn = warn
return self._return
mock_config_var = MockConfigVar("38")
monkeypatch.setattr(tags, "_get_config_var", mock_config_var)
tags.interpreter_version(warn=True)
assert mock_config_var.warn
def test_python_version_nodot(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(tags, "_get_config_var", lambda _var, warn: "NN") # noqa: ARG005
assert tags.interpreter_version() == "NN"
@pytest.mark.parametrize(
("version_info", "version_str"),
[
((1, 2, 3), "12"),
((1, 12, 3), "112"),
((11, 2, 3), "112"),
((11, 12, 3), "1112"),
((1, 2, 13), "12"),
],
)
def test_sys_version_info(
self,
version_info: tuple[int, int, int],
version_str: str,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(tags, "_get_config_var", lambda *args, **kwargs: None)
monkeypatch.setattr(sys, "version_info", version_info)
assert tags.interpreter_version() == version_str
| TestInterpreterVersion |
python | python-pillow__Pillow | src/PIL/PngImagePlugin.py | {
"start": 23999,
"end": 37117
} | class ____(ImageFile.ImageFile):
format = "PNG"
format_description = "Portable network graphics"
def _open(self) -> None:
if not _accept(self.fp.read(8)):
msg = "not a PNG file"
raise SyntaxError(msg)
self._fp = self.fp
self.__frame = 0
#
# Parse headers up to the first IDAT or fDAT chunk
self.private_chunks: list[tuple[bytes, bytes] | tuple[bytes, bytes, bool]] = []
self.png: PngStream | None = PngStream(self.fp)
while True:
#
# get next chunk
cid, pos, length = self.png.read()
try:
s = self.png.call(cid, pos, length)
except EOFError:
break
except AttributeError:
logger.debug("%r %s %s (unknown)", cid, pos, length)
s = ImageFile._safe_read(self.fp, length)
if cid[1:2].islower():
self.private_chunks.append((cid, s))
self.png.crc(cid, s)
#
# Copy relevant attributes from the PngStream. An alternative
# would be to let the PngStream class modify these attributes
# directly, but that introduces circular references which are
# difficult to break if things go wrong in the decoder...
# (believe me, I've tried ;-)
self._mode = self.png.im_mode
self._size = self.png.im_size
self.info = self.png.im_info
self._text: dict[str, str | iTXt] | None = None
self.tile = self.png.im_tile
self.custom_mimetype = self.png.im_custom_mimetype
self.n_frames = self.png.im_n_frames or 1
self.default_image = self.info.get("default_image", False)
if self.png.im_palette:
rawmode, data = self.png.im_palette
self.palette = ImagePalette.raw(rawmode, data)
if cid == b"fdAT":
self.__prepare_idat = length - 4
else:
self.__prepare_idat = length # used by load_prepare()
if self.png.im_n_frames is not None:
self._close_exclusive_fp_after_loading = False
self.png.save_rewind()
self.__rewind_idat = self.__prepare_idat
self.__rewind = self._fp.tell()
if self.default_image:
# IDAT chunk contains default image and not first animation frame
self.n_frames += 1
self._seek(0)
self.is_animated = self.n_frames > 1
@property
def text(self) -> dict[str, str | iTXt]:
# experimental
if self._text is None:
# iTxt, tEXt and zTXt chunks may appear at the end of the file
# So load the file to ensure that they are read
if self.is_animated:
frame = self.__frame
# for APNG, seek to the final frame before loading
self.seek(self.n_frames - 1)
self.load()
if self.is_animated:
self.seek(frame)
assert self._text is not None
return self._text
def verify(self) -> None:
"""Verify PNG file"""
if self.fp is None:
msg = "verify must be called directly after open"
raise RuntimeError(msg)
# back up to beginning of IDAT block
self.fp.seek(self.tile[0][2] - 8)
assert self.png is not None
self.png.verify()
self.png.close()
if self._exclusive_fp:
self.fp.close()
self.fp = None
def seek(self, frame: int) -> None:
if not self._seek_check(frame):
return
if frame < self.__frame:
self._seek(0, True)
last_frame = self.__frame
for f in range(self.__frame + 1, frame + 1):
try:
self._seek(f)
except EOFError as e:
self.seek(last_frame)
msg = "no more images in APNG file"
raise EOFError(msg) from e
def _seek(self, frame: int, rewind: bool = False) -> None:
assert self.png is not None
if isinstance(self._fp, DeferredError):
raise self._fp.ex
self.dispose: _imaging.ImagingCore | None
dispose_extent = None
if frame == 0:
if rewind:
self._fp.seek(self.__rewind)
self.png.rewind()
self.__prepare_idat = self.__rewind_idat
self._im = None
self.info = self.png.im_info
self.tile = self.png.im_tile
self.fp = self._fp
self._prev_im = None
self.dispose = None
self.default_image = self.info.get("default_image", False)
self.dispose_op = self.info.get("disposal")
self.blend_op = self.info.get("blend")
dispose_extent = self.info.get("bbox")
self.__frame = 0
else:
if frame != self.__frame + 1:
msg = f"cannot seek to frame {frame}"
raise ValueError(msg)
# ensure previous frame was loaded
self.load()
if self.dispose:
self.im.paste(self.dispose, self.dispose_extent)
self._prev_im = self.im.copy()
self.fp = self._fp
# advance to the next frame
if self.__prepare_idat:
ImageFile._safe_read(self.fp, self.__prepare_idat)
self.__prepare_idat = 0
frame_start = False
while True:
self.fp.read(4) # CRC
try:
cid, pos, length = self.png.read()
except (struct.error, SyntaxError):
break
if cid == b"IEND":
msg = "No more images in APNG file"
raise EOFError(msg)
if cid == b"fcTL":
if frame_start:
# there must be at least one fdAT chunk between fcTL chunks
msg = "APNG missing frame data"
raise SyntaxError(msg)
frame_start = True
try:
self.png.call(cid, pos, length)
except UnicodeDecodeError:
break
except EOFError:
if cid == b"fdAT":
length -= 4
if frame_start:
self.__prepare_idat = length
break
ImageFile._safe_read(self.fp, length)
except AttributeError:
logger.debug("%r %s %s (unknown)", cid, pos, length)
ImageFile._safe_read(self.fp, length)
self.__frame = frame
self.tile = self.png.im_tile
self.dispose_op = self.info.get("disposal")
self.blend_op = self.info.get("blend")
dispose_extent = self.info.get("bbox")
if not self.tile:
msg = "image not found in APNG frame"
raise EOFError(msg)
if dispose_extent:
self.dispose_extent: tuple[float, float, float, float] = dispose_extent
# setup frame disposal (actual disposal done when needed in the next _seek())
if self._prev_im is None and self.dispose_op == Disposal.OP_PREVIOUS:
self.dispose_op = Disposal.OP_BACKGROUND
self.dispose = None
if self.dispose_op == Disposal.OP_PREVIOUS:
if self._prev_im:
self.dispose = self._prev_im.copy()
self.dispose = self._crop(self.dispose, self.dispose_extent)
elif self.dispose_op == Disposal.OP_BACKGROUND:
self.dispose = Image.core.fill(self.mode, self.size)
self.dispose = self._crop(self.dispose, self.dispose_extent)
def tell(self) -> int:
return self.__frame
def load_prepare(self) -> None:
"""internal: prepare to read PNG file"""
if self.info.get("interlace"):
self.decoderconfig = self.decoderconfig + (1,)
self.__idat = self.__prepare_idat # used by load_read()
ImageFile.ImageFile.load_prepare(self)
def load_read(self, read_bytes: int) -> bytes:
"""internal: read more image data"""
assert self.png is not None
while self.__idat == 0:
# end of chunk, skip forward to next one
self.fp.read(4) # CRC
cid, pos, length = self.png.read()
if cid not in [b"IDAT", b"DDAT", b"fdAT"]:
self.png.push(cid, pos, length)
return b""
if cid == b"fdAT":
try:
self.png.call(cid, pos, length)
except EOFError:
pass
self.__idat = length - 4 # sequence_num has already been read
else:
self.__idat = length # empty chunks are allowed
# read more data from this chunk
if read_bytes <= 0:
read_bytes = self.__idat
else:
read_bytes = min(read_bytes, self.__idat)
self.__idat = self.__idat - read_bytes
return self.fp.read(read_bytes)
def load_end(self) -> None:
"""internal: finished reading image data"""
assert self.png is not None
if self.__idat != 0:
self.fp.read(self.__idat)
while True:
self.fp.read(4) # CRC
try:
cid, pos, length = self.png.read()
except (struct.error, SyntaxError):
break
if cid == b"IEND":
break
elif cid == b"fcTL" and self.is_animated:
# start of the next frame, stop reading
self.__prepare_idat = 0
self.png.push(cid, pos, length)
break
try:
self.png.call(cid, pos, length)
except UnicodeDecodeError:
break
except EOFError:
if cid == b"fdAT":
length -= 4
try:
ImageFile._safe_read(self.fp, length)
except OSError as e:
if ImageFile.LOAD_TRUNCATED_IMAGES:
break
else:
raise e
except AttributeError:
logger.debug("%r %s %s (unknown)", cid, pos, length)
s = ImageFile._safe_read(self.fp, length)
if cid[1:2].islower():
self.private_chunks.append((cid, s, True))
self._text = self.png.im_text
if not self.is_animated:
self.png.close()
self.png = None
else:
if self._prev_im and self.blend_op == Blend.OP_OVER:
updated = self._crop(self.im, self.dispose_extent)
if self.im.mode == "RGB" and "transparency" in self.info:
mask = updated.convert_transparent(
"RGBA", self.info["transparency"]
)
else:
if self.im.mode == "P" and "transparency" in self.info:
t = self.info["transparency"]
if isinstance(t, bytes):
updated.putpalettealphas(t)
elif isinstance(t, int):
updated.putpalettealpha(t)
mask = updated.convert("RGBA")
self._prev_im.paste(updated, self.dispose_extent, mask)
self.im = self._prev_im
def _getexif(self) -> dict[int, Any] | None:
if "exif" not in self.info:
self.load()
if "exif" not in self.info and "Raw profile type exif" not in self.info:
return None
return self.getexif()._get_merged_dict()
def getexif(self) -> Image.Exif:
if "exif" not in self.info:
self.load()
return super().getexif()
# --------------------------------------------------------------------
# PNG writer
_OUTMODES = {
# supported PIL modes, and corresponding rawmode, bit depth and color type
"1": ("1", b"\x01", b"\x00"),
"L;1": ("L;1", b"\x01", b"\x00"),
"L;2": ("L;2", b"\x02", b"\x00"),
"L;4": ("L;4", b"\x04", b"\x00"),
"L": ("L", b"\x08", b"\x00"),
"LA": ("LA", b"\x08", b"\x04"),
"I": ("I;16B", b"\x10", b"\x00"),
"I;16": ("I;16B", b"\x10", b"\x00"),
"I;16B": ("I;16B", b"\x10", b"\x00"),
"P;1": ("P;1", b"\x01", b"\x03"),
"P;2": ("P;2", b"\x02", b"\x03"),
"P;4": ("P;4", b"\x04", b"\x03"),
"P": ("P", b"\x08", b"\x03"),
"RGB": ("RGB", b"\x08", b"\x02"),
"RGBA": ("RGBA", b"\x08", b"\x06"),
}
def putchunk(fp: IO[bytes], cid: bytes, *data: bytes) -> None:
"""Write a PNG chunk (including CRC field)"""
byte_data = b"".join(data)
fp.write(o32(len(byte_data)) + cid)
fp.write(byte_data)
crc = _crc32(byte_data, _crc32(cid))
fp.write(o32(crc))
| PngImageFile |
python | sphinx-doc__sphinx | sphinx/transforms/post_transforms/__init__.py | {
"start": 834,
"end": 1848
} | class ____(SphinxTransform):
"""A base class of post-transforms.
Post transforms are invoked to modify the document to restructure it for outputting.
They resolve references, convert images, do special transformation for each output
formats and so on. This class helps to implement these post transforms.
"""
builders: tuple[str, ...] = ()
formats: tuple[str, ...] = ()
def apply(self, **kwargs: Any) -> None:
if self.is_supported():
self.run(**kwargs)
def is_supported(self) -> bool:
"""Check this transform working for current builder."""
if self.builders and self.env._builder_cls.name not in self.builders:
return False
return not self.formats or self.env._builder_cls.format in self.formats
def run(self, **kwargs: Any) -> None:
"""Main method of post transforms.
Subclasses should override this method instead of ``apply()``.
"""
raise NotImplementedError
| SphinxPostTransform |
python | astropy__astropy | astropy/utils/masked/core.py | {
"start": 20210,
"end": 52751
} | class ____(Masked, np.ndarray, base_cls=np.ndarray, data_cls=np.ndarray):
_mask = None
info = MaskedNDArrayInfo()
def __new__(cls, *args, mask=None, **kwargs):
"""Get data class instance from arguments and then set mask."""
self = super().__new__(cls, *args, **kwargs)
if mask is not None:
self.mask = mask
elif self._mask is None:
self.mask = False
return self
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(cls, **kwargs)
# For all subclasses we should set a default __new__ that passes on
# arguments other than mask to the data class, and then sets the mask.
if "__new__" not in cls.__dict__:
def __new__(newcls, *args, mask=None, **kwargs):
"""Get data class instance from arguments and then set mask."""
# Need to explicitly mention classes outside of class definition.
self = super(cls, newcls).__new__(newcls, *args, **kwargs)
if mask is not None:
self.mask = mask
elif self._mask is None:
self.mask = False
return self
cls.__new__ = __new__
if "info" not in cls.__dict__ and hasattr(cls._data_cls, "info"):
data_info = cls._data_cls.info
attr_names = data_info.attr_names | {"serialize_method"}
new_info = type(
cls.__name__ + "Info",
(MaskedArraySubclassInfo, data_info.__class__),
dict(attr_names=attr_names),
)
cls.info = new_info()
# The two pieces typically overridden.
@classmethod
def from_unmasked(cls, data, mask=None, copy=COPY_IF_NEEDED):
# Note: have to override since __new__ would use ndarray.__new__
# which expects the shape as its first argument, not an array.
data = np.array(data, subok=True, copy=copy)
self = data.view(cls)
self._set_mask(mask, copy=copy)
return self
@property
def unmasked(self):
return super().view(self._data_cls)
@classmethod
def _get_masked_cls(cls, data_cls):
# Short-cuts
if data_cls is np.ndarray:
return MaskedNDArray
elif data_cls is None: # for .view()
return cls
return super()._get_masked_cls(data_cls)
@property
def flat(self):
"""A 1-D iterator over the Masked array.
This returns a ``MaskedIterator`` instance, which behaves the same
as the `~numpy.flatiter` instance returned by `~numpy.ndarray.flat`,
and is similar to Python's built-in iterator, except that it also
allows assignment.
"""
return MaskedIterator(self)
@property
def _baseclass(self):
"""Work-around for MaskedArray initialization.
Allows the base class to be inferred correctly when a masked instance
is used to initialize (or viewed as) a `~numpy.ma.MaskedArray`.
"""
return self._data_cls
def view(self, dtype=None, type=None):
"""New view of the masked array.
Like `numpy.ndarray.view`, but always returning a masked array subclass.
"""
if type is None and (
isinstance(dtype, builtins.type) and issubclass(dtype, np.ndarray)
):
return super().view(self._get_masked_cls(dtype))
if dtype is None:
return super().view(self._get_masked_cls(type))
dtype = np.dtype(dtype)
result = super().view(dtype, self._get_masked_cls(type))
# Mask should be viewed in all but simplest case.
if (
dtype.itemsize != self.dtype.itemsize
or dtype.names
or dtype.shape
or self.dtype.names
or self.dtype.shape
):
try:
result.mask = self.mask.view(np.ma.make_mask_descr(dtype))
except Exception as exc:
raise NotImplementedError(
f"{self.__class__} cannot be viewed with a dtype "
"with a different number of fields or size."
) from None
return result
def __array_finalize__(self, obj):
# If we're a new object or viewing an ndarray, nothing has to be done.
if obj is None or obj.__class__ is np.ndarray:
return
# Logically, this should come from ndarray and hence do nothing, but
# just in case someone creates a new mixin, we run it.
super().__array_finalize__(obj)
if self._mask is None:
# Got here after, e.g., a view of another masked class.
# Get its mask, or initialize ours.
self._set_mask(getattr(obj, "_mask", False))
if "info" in obj.__dict__:
self.info = obj.info
@property
def shape(self):
"""The shape of the data and the mask.
Usually used to get the current shape of an array, but may also be
used to reshape the array in-place by assigning a tuple of array
dimensions to it. As with `numpy.reshape`, one of the new shape
dimensions can be -1, in which case its value is inferred from the
size of the array and the remaining dimensions.
Raises
------
AttributeError
If a copy is required, of either the data or the mask.
"""
# Redefinition to allow defining a setter and add a docstring.
return super().shape
@shape.setter
def shape(self, shape):
old_shape = self.shape
self._mask.shape = shape
# Reshape array proper in try/except just in case some broadcasting
# or so causes it to fail.
try:
super(MaskedNDArray, type(self)).shape.__set__(self, shape)
except Exception as exc:
self._mask.shape = old_shape
# Given that the mask reshaping succeeded, the only logical
# reason for an exception is something like a broadcast error in
# in __array_finalize__, or a different memory ordering between
# mask and data. For those, give a more useful error message;
# otherwise just raise the error.
if "could not broadcast" in exc.args[0]:
raise AttributeError(
"Incompatible shape for in-place modification. "
"Use `.reshape()` to make a copy with the desired "
"shape."
) from None
else: # pragma: no cover
raise
_eq_simple = _comparison_method("__eq__")
_ne_simple = _comparison_method("__ne__")
__lt__ = _comparison_method("__lt__")
__le__ = _comparison_method("__le__")
__gt__ = _comparison_method("__gt__")
__ge__ = _comparison_method("__ge__")
def __eq__(self, other):
if not self.dtype.names:
return self._eq_simple(other)
# For structured arrays, we treat this as a reduction over the fields,
# where masked fields are skipped and thus do not influence the result.
other = np.asanyarray(other, dtype=self.dtype)
result = np.stack(
[self[field] == other[field] for field in self.dtype.names], axis=-1
)
return result.all(axis=-1)
def __ne__(self, other):
if not self.dtype.names:
return self._ne_simple(other)
# For structured arrays, we treat this as a reduction over the fields,
# where masked fields are skipped and thus do not influence the result.
other = np.asanyarray(other, dtype=self.dtype)
result = np.stack(
[self[field] != other[field] for field in self.dtype.names], axis=-1
)
return result.any(axis=-1)
@staticmethod
def _get_data_and_masks(arrays):
"""Extracts the data and masks from the given arrays.
Parameters
----------
arrays : iterable of array
An iterable of arrays, possibly masked.
Returns
-------
datas, masks: tuple of array
Extracted data and mask arrays. For any input array without
a mask, the corresponding entry in ``masks`` is `None`.
"""
data_masks = [get_data_and_mask(array) for array in arrays]
return tuple(zip(*data_masks))
def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
# Get inputs and there masks.
unmasked, masks = self._get_data_and_masks(inputs)
# Deal with possible outputs and their masks.
out = kwargs.get("out")
out_mask = None
if out is None:
out_masks = [None] * ufunc.nout
else:
out_unmasked, out_masks = self._get_data_and_masks(out)
kwargs["out"] = out_unmasked
for d, m in zip(out_unmasked, out_masks):
if m is None:
# TODO: allow writing to unmasked output if nothing is masked?
if d is not None:
raise TypeError("cannot write to unmasked output")
elif out_mask is None:
out_mask = m
# TODO: where is only needed for __call__ and reduce;
# this is very fast, but still worth separating out?
where = kwargs.get("where", True)
if where is True:
where_unmasked = True
where_mask = None
else:
where_unmasked, where_mask = get_data_and_mask(where)
kwargs["where"] = where_unmasked
# First calculate the unmasked result. This will also verify kwargs.
# It will raise if the arguments do not know how to deal with each other.
result = getattr(ufunc, method)(*unmasked, **kwargs)
if ufunc.signature:
# We're dealing with a gufunc. For now, only deal with
# np.matmul and gufuncs for which the mask of any output always
# depends on all core dimension values of all inputs.
# TODO: in principle, it should be possible to generate the mask
# purely based on the signature.
if ufunc is np.matmul:
# np.matmul is tricky and its signature cannot be parsed by
# _parse_gufunc_signature. But we can calculate the mask
# with matmul by using that nan will propagate correctly.
# We use float16 to minimize the memory requirements.
nan_masks = []
for a, m in zip(unmasked, masks):
nan_mask = np.zeros(a.shape, dtype=np.float16)
if m is not None:
nan_mask[m] = np.nan
nan_masks.append(nan_mask)
m_kwargs = {
k: v for k, v in kwargs.items() if k not in ("out", "where")
}
t = ufunc(*nan_masks, **m_kwargs)
mask = np.isnan(t, out=out_mask)
else:
# Parse signature with private numpy function. Note it
# cannot handle spaces in tuples, so remove those.
if NUMPY_LT_2_0:
in_sig, out_sig = np.lib.function_base._parse_gufunc_signature(
ufunc.signature.replace(" ", "")
)
else:
(
in_sig,
out_sig,
) = np.lib._function_base_impl._parse_gufunc_signature(
ufunc.signature.replace(" ", "")
)
axes = kwargs.get("axes")
if axes is None:
# Maybe axis was given? (Note: ufunc will not take both.)
axes = [kwargs.get("axis")] * ufunc.nargs
elif len(axes) < ufunc.nargs:
# All outputs have no core dimensions, which means axes
# is not needed, but add None's for the zip below.
axes = axes + [None] * (ufunc.nargs - len(axes)) # not inplace!
keepdims = kwargs.get("keepdims", False)
in_masks = []
for sig, mask, axis in zip(in_sig, masks, axes[: ufunc.nin]):
if mask is not None:
if sig:
if axis is None:
axis = tuple(range(-1, -1 - len(sig), -1))
# Input has core dimensions. Assume that if any
# value in those is masked, the output will be
# masked too (TODO: for multiple core dimensions
# this may be too strong).
mask = np.logical_or.reduce(
mask, axis=axis, keepdims=keepdims
)
in_masks.append(mask)
if ufunc.nout == 1 and out_sig[0] == ():
# Special-case where possible in-place is easy.
mask = combine_masks(in_masks, out=out_mask, copy=False)
else:
# Here, some masks may need expansion, so we forego in-place.
mask = combine_masks(in_masks, copy=False)
result_masks = []
for os, omask, axis in zip(out_sig, out_masks, axes[ufunc.nin :]):
if os:
# Output has core dimensions. Assume all those
# get the same mask.
if axis is None:
axis = tuple(range(-1, -1 - len(os), -1))
result_mask = np.expand_dims(mask, axis)
else:
result_mask = mask
if omask is not None:
omask[...] = result_mask
result_masks.append(result_mask)
mask = result_masks if ufunc.nout > 1 else result_masks[0]
elif method == "__call__":
# Regular ufunc call.
# Combine the masks from the input, possibly selecting elements.
mask = combine_masks(masks, out=out_mask, where=where_unmasked)
# If relevant, also mask output elements for which where was masked.
if where_mask is not None:
mask |= where_mask
if out_mask is not None:
# Check for any additional explicitly given outputs.
for m in out_masks[1:]:
if m is not None and m is not out_mask:
m[...] = mask
elif method == "outer":
# Must have two inputs and one output, so also only one output mask.
# Adjust masks as will be done for data.
m0, m1 = masks
if m0 is not None and m0.ndim > 0:
m0 = m0[(...,) + (np.newaxis,) * np.ndim(unmasked[1])]
mask = combine_masks((m0, m1), out=out_mask)
elif method in {"reduce", "accumulate"}:
# Reductions like np.add.reduce (sum).
# Treat any masked where as if the input element was masked.
mask = combine_masks((masks[0], where_mask), copy=False)
if mask is False and out_mask is not None:
if where_unmasked is True:
out_mask[...] = False
else:
# This is too complicated, just fall through to below.
mask = np.broadcast_to(False, inputs[0].shape)
if mask is not False:
# By default, we simply propagate masks, since for
# things like np.sum, it makes no sense to do otherwise.
# Individual methods need to override as needed.
if method == "reduce":
axis = kwargs.get("axis")
keepdims = kwargs.get("keepdims", False)
mask = np.logical_or.reduce(
mask,
where=where_unmasked,
axis=axis,
keepdims=keepdims,
out=out_mask,
)
if where_unmasked is not True:
# Mask also whole rows in which no elements were selected;
# those will have been left as unmasked above.
mask |= ~np.logical_or.reduce(
where_unmasked, axis=axis, keepdims=keepdims
)
else:
# Accumulate
axis = kwargs.get("axis", 0)
mask = np.logical_or.accumulate(mask, axis=axis, out=out_mask)
elif method in {"reduceat", "at"}: # pragma: no cover
raise NotImplementedError(
"masked instances cannot yet deal with 'reduceat' or 'at'."
)
if result is None: # pragma: no cover
# This happens for the "at" method.
return result
if out is not None and ufunc.nout == 1:
out = out[0]
return self._masked_result(result, mask, out)
def __array_function__(self, function, types, args, kwargs):
# TODO: go through functions systematically to see which ones
# work and/or can be supported.
if function in MASKED_SAFE_FUNCTIONS:
return super().__array_function__(function, types, args, kwargs)
elif function in APPLY_TO_BOTH_FUNCTIONS:
helper = APPLY_TO_BOTH_FUNCTIONS[function]
try:
helper_result = helper(*args, **kwargs)
except NotImplementedError:
return self._not_implemented_or_raise(function, types)
data_args, mask_args, kwargs, out = helper_result
if out is not None:
if not isinstance(out, Masked):
return self._not_implemented_or_raise(function, types)
function(*mask_args, out=out.mask, **kwargs)
function(*data_args, out=out.unmasked, **kwargs)
return out
mask = function(*mask_args, **kwargs)
result = function(*data_args, **kwargs)
elif function in DISPATCHED_FUNCTIONS:
dispatched_function = DISPATCHED_FUNCTIONS[function]
try:
dispatched_result = dispatched_function(*args, **kwargs)
except NotImplementedError:
return self._not_implemented_or_raise(function, types)
if dispatched_result is None:
return None
result, mask, out = dispatched_result
elif function in UNSUPPORTED_FUNCTIONS:
return NotImplemented
else: # pragma: no cover
# By default, just pass it through for now.
return super().__array_function__(function, types, args, kwargs)
if mask is None:
return result
else:
return self._masked_result(result, mask, out)
def _not_implemented_or_raise(self, function, types):
# Our function helper or dispatcher found that the function does not
# work with Masked. In principle, there may be another class that
# knows what to do with us, for which we should return NotImplemented.
# But if there is ndarray (or a non-Masked subclass of it) around,
# it quite likely coerces, so we should just break.
if any(issubclass(t, np.ndarray) and not issubclass(t, Masked) for t in types):
raise TypeError(
f"the MaskedNDArray implementation cannot handle {function} "
"with the given arguments."
) from None
else:
return NotImplemented
def _masked_result(self, result, mask, out):
if isinstance(result, tuple):
if out is None:
out = (None,) * len(result)
if not isinstance(mask, (list, tuple)):
mask = (mask,) * len(result)
return tuple(
self._masked_result(result_, mask_, out_)
for (result_, mask_, out_) in zip(result, mask, out)
)
if out is None:
# Note that we cannot count on result being the same class as
# 'self' (e.g., comparison of quantity results in an ndarray, most
# operations on Longitude and Latitude result in Angle or
# Quantity), so use Masked to determine the appropriate class.
return Masked(result, mask)
# TODO: remove this sanity check once test cases are more complete.
assert isinstance(out, Masked)
# For inplace, the mask will have been set already.
return out
def __array_wrap__(self, obj, context=None, return_scalar=False):
if context is None:
# Functions like np.ediff1d call __array_wrap__ to turn the array
# into self's subclass.
return self.from_unmasked(*get_data_and_mask(obj))
raise NotImplementedError(
"__array_wrap__ should not be used with a context any more since all use "
"should go through array_function. Please raise an issue on "
"https://github.com/astropy/astropy"
)
# Below are ndarray methods that need to be overridden as masked elements
# need to be skipped and/or an initial value needs to be set.
def _reduce_defaults(self, kwargs, initial_func=None):
"""Get default where and initial for masked reductions.
Generally, the default should be to skip all masked elements. For
reductions such as np.minimum.reduce, we also need an initial value,
which can be determined using ``initial_func``.
"""
if "where" not in kwargs:
kwargs["where"] = ~self.mask
if initial_func is not None and "initial" not in kwargs:
kwargs["initial"] = initial_func(self.unmasked)
return kwargs
def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
# Unfortunately, cannot override the call to diagonal inside trace, so
# duplicate implementation in numpy/core/src/multiarray/calculation.c.
diagonal = self.diagonal(offset=offset, axis1=axis1, axis2=axis2)
return diagonal.sum(-1, dtype=dtype, out=out)
def min(self, axis=None, out=None, **kwargs):
return super().min(
axis=axis, out=out, **self._reduce_defaults(kwargs, np.nanmax)
)
def max(self, axis=None, out=None, **kwargs):
return super().max(
axis=axis, out=out, **self._reduce_defaults(kwargs, np.nanmin)
)
def ptp(self, axis=None, out=None, **kwargs):
result = self.max(axis=axis, out=out, **kwargs)
result -= self.min(axis=axis, **kwargs)
return result
def nonzero(self):
unmasked_nonzero = self.unmasked.nonzero()
if self.ndim >= 1:
not_masked = ~self.mask[unmasked_nonzero]
return tuple(u[not_masked] for u in unmasked_nonzero)
else:
return unmasked_nonzero if not self.mask else np.nonzero([0])
def compress(self, condition, axis=None, out=None):
if out is not None:
raise NotImplementedError("cannot yet give output")
return self._apply("compress", condition, axis=axis)
def repeat(self, repeats, axis=None):
return self._apply("repeat", repeats, axis=axis)
def choose(self, choices, out=None, mode="raise"):
# Let __array_function__ take care since choices can be masked too.
return np.choose(self, choices, out=out, mode=mode)
def argmin(self, axis=None, out=None, *, keepdims=False):
# TODO: should this return a masked integer array, with masks
# if all elements were masked?
at_min = self == self.min(axis=axis, keepdims=True)
return at_min.filled(False).argmax(axis=axis, out=out, keepdims=keepdims)
def argmax(self, axis=None, out=None, *, keepdims=False):
at_max = self == self.max(axis=axis, keepdims=True)
return at_max.filled(False).argmax(axis=axis, out=out, keepdims=keepdims)
def argsort(self, axis=-1, kind=None, order=None, *, stable=None):
"""Returns the indices that would sort an array.
Perform an indirect sort along the given axis on both the array
and the mask, with masked items being sorted to the end.
Parameters
----------
axis : int or None, optional
Axis along which to sort. The default is -1 (the last axis).
If None, the flattened array is used.
kind : str or None, ignored.
The kind of sort. Present only to allow subclasses to work.
order : str or list of str.
For an array with fields defined, the fields to compare first,
second, etc. A single field can be specified as a string, and not
all fields need be specified, but unspecified fields will still be
used, in dtype order, to break ties.
stable: bool, keyword-only, ignored
Sort stability. Present only to allow subclasses to work.
Returns
-------
index_array : ndarray, int
Array of indices that sorts along the specified ``axis``. Use
``np.take_along_axis(self, index_array, axis=axis)`` to obtain
the sorted array.
"""
if axis is None:
data = self.ravel()
axis = -1
else:
data = self
if self.dtype.names:
# As done inside the argsort implementation in multiarray/methods.c.
if order is None:
order = self.dtype.names
elif NUMPY_LT_2_0:
order = np.core._internal._newnames(self.dtype, order)
else:
order = np._core._internal._newnames(self.dtype, order)
keys = tuple(data[name] for name in order[::-1])
elif order is not None:
raise ValueError("Cannot specify order when the array has no fields.")
else:
keys = (data,)
return np.lexsort(keys, axis=axis)
def sort(self, axis=-1, kind=None, order=None, *, stable=False):
"""Sort an array in-place. Refer to `numpy.sort` for full documentation.
Notes
-----
Masked items will be sorted to the end. The implementation
is via `numpy.lexsort` and thus ignores the ``kind`` and ``stable`` arguments;
they are present only so that subclasses can pass them on.
"""
# TODO: probably possible to do this faster than going through argsort!
argsort_kwargs = dict(kind=kind, order=order)
if not NUMPY_LT_2_0:
argsort_kwargs["stable"] = stable
indices = self.argsort(axis, **argsort_kwargs)
self[:] = np.take_along_axis(self, indices, axis=axis)
def argpartition(self, kth, axis=-1, kind="introselect", order=None):
# TODO: should be possible to do this faster than with a full argsort!
return self.argsort(axis=axis, order=order)
def partition(self, kth, axis=-1, kind="introselect", order=None):
# TODO: should be possible to do this faster than with a full argsort!
return self.sort(axis=axis, order=None)
def cumsum(self, axis=None, dtype=None, out=None):
if axis is None:
self = self.ravel()
axis = 0
return np.add.accumulate(self, axis=axis, dtype=dtype, out=out)
def cumprod(self, axis=None, dtype=None, out=None):
if axis is None:
self = self.ravel()
axis = 0
return np.multiply.accumulate(self, axis=axis, dtype=dtype, out=out)
def clip(self, min=None, max=None, out=None, **kwargs):
"""Return an array whose values are limited to ``[min, max]``.
Like `~numpy.clip`, but any masked values in ``min`` and ``max``
are ignored for clipping. The mask of the input array is propagated.
"""
# TODO: implement this at the ufunc level.
dmin, mmin = get_data_and_mask(min)
dmax, mmax = get_data_and_mask(max)
if mmin is None and mmax is None:
# Fast path for unmasked max, min.
return super().clip(min, max, out=out, **kwargs)
masked_out = np.positive(self, out=out)
out = masked_out.unmasked
if dmin is not None:
np.maximum(out, dmin, out=out, where=True if mmin is None else ~mmin)
if dmax is not None:
np.minimum(out, dmax, out=out, where=True if mmax is None else ~mmax)
return masked_out
def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True):
# Implementation based on that in numpy/core/_methods.py
# Cast bool, unsigned int, and int to float64 by default,
# and do float16 at higher precision.
is_float16_result = False
if dtype is None:
if issubclass(self.dtype.type, (np.integer, np.bool_)):
dtype = np.dtype("f8")
elif issubclass(self.dtype.type, np.float16):
dtype = np.dtype("f4")
is_float16_result = out is None
where = ~self.mask & where
result = self.sum(
axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where
)
n = np.add.reduce(where, axis=axis, keepdims=keepdims)
# catch the case when an axis is fully masked to prevent div by zero:
neq0 = n == 0
n += neq0
result /= n
# correct fully-masked slice results to what is expected for 0/0 division
result.unmasked[neq0] = np.nan
if is_float16_result:
result = result.astype(self.dtype)
return result
def var(
self, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True
):
where_final = ~self.mask & where
# Simplified implementation based on that in numpy/core/_methods.py
n = np.add.reduce(where_final, axis=axis, keepdims=keepdims)[...]
# Cast bool, unsigned int, and int to float64 by default.
if dtype is None and issubclass(self.dtype.type, (np.integer, np.bool_)):
dtype = np.dtype("f8")
mean = self.mean(axis=axis, dtype=dtype, keepdims=True, where=where)
x = self - mean
x *= x.conjugate() # Conjugate just returns x if not complex.
result = x.sum(
axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where_final
)
n -= ddof
n = np.maximum(n, 0, out=n)
result /= n
result._mask |= n == 0
return result
def std(
self, axis=None, dtype=None, out=None, ddof=0, keepdims=False, *, where=True
):
result = self.var(
axis=axis, dtype=dtype, out=out, ddof=ddof, keepdims=keepdims, where=where
)
return np.sqrt(result, out=result)
def __bool__(self):
# First get result from array itself; this will error if not a scalar.
result = super().__bool__()
return result and not self.mask
def any(self, axis=None, out=None, keepdims=False, *, where=True):
return np.logical_or.reduce(
self, axis=axis, out=out, keepdims=keepdims, where=~self.mask & where
)
def all(self, axis=None, out=None, keepdims=False, *, where=True):
return np.logical_and.reduce(
self, axis=axis, out=out, keepdims=keepdims, where=~self.mask & where
)
# Following overrides needed since somehow the ndarray implementation
# does not actually call these.
def __str__(self):
return np.array_str(self)
def __repr__(self):
return np.array_repr(self)
def __format__(self, format_spec):
string = super().__format__(format_spec)
if self.shape == () and self.mask:
n = min(3, max(1, len(string)))
return " " * (len(string) - n) + "\u2014" * n
else:
return string
def __hash__(self):
# Try to be somewhat like a numpy array scalar if possible.
if self.ndim == 0 and not self.mask:
return hash(self.unmasked[()])
# Will raise regular ndarray error.
return hash((self.unmasked, self.mask))
| MaskedNDArray |
python | django__django | tests/admin_views/models.py | {
"start": 6748,
"end": 7089
} | class ____(models.Model):
GENDER_CHOICES = (
(1, "Male"),
(2, "Female"),
)
name = models.CharField(max_length=100)
gender = models.IntegerField(choices=GENDER_CHOICES)
age = models.IntegerField(default=21)
alive = models.BooleanField(default=True)
def __str__(self):
return self.name
| Person |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 17320,
"end": 19206
} | class ____(graphene.Mutation):
"""Re-executes a job run."""
Output = graphene.NonNull(GrapheneLaunchRunReexecutionResult)
class Arguments:
executionParams = graphene.Argument(GrapheneExecutionParams)
reexecutionParams = graphene.Argument(GrapheneReexecutionParams)
class Meta:
name = "LaunchRunReexecutionMutation"
@capture_error
@require_permission_check(Permissions.LAUNCH_PIPELINE_REEXECUTION)
async def mutate(
self,
graphene_info: ResolveInfo,
executionParams: Optional[GrapheneExecutionParams] = None,
reexecutionParams: Optional[GrapheneReexecutionParams] = None,
):
if bool(executionParams) == bool(reexecutionParams):
raise DagsterInvariantViolationError(
"Must only provide one of either executionParams or reexecutionParams"
)
if executionParams:
return await create_execution_params_and_launch_pipeline_reexec(
graphene_info,
execution_params_dict=executionParams,
)
elif reexecutionParams:
extra_tags = None
if reexecutionParams.get("extraTags"):
extra_tags = {t["key"]: t["value"] for t in reexecutionParams["extraTags"]}
use_parent_run_tags = None
if reexecutionParams.get("useParentRunTags") is not None:
use_parent_run_tags = reexecutionParams["useParentRunTags"]
return await launch_reexecution_from_parent_run(
graphene_info,
parent_run_id=reexecutionParams["parentRunId"],
strategy=reexecutionParams["strategy"],
extra_tags=extra_tags,
use_parent_run_tags=use_parent_run_tags,
)
else:
check.failed("Unreachable")
| GrapheneLaunchRunReexecutionMutation |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/sglang_engine_stage.py | {
"start": 1273,
"end": 2687
} | class ____(BaseModel):
"""The output of the SGLang engine."""
prompt: Optional[str]
prompt_token_ids: Optional[List[int]]
num_input_tokens: int
# Generate fields.
generated_tokens: Optional[List[int]]
generated_text: Optional[str]
num_generated_tokens: int
# Metrics fields.
metrics: Optional[Dict[str, Any]] = None
@classmethod
def from_sglang_engine_output(cls, output: Dict[str, Any]) -> "SGLangOutputData":
"""Create a SGLangOutputData from a SGLang engine output."""
# Set by `_generate_async`.
assert "prompt" in output
assert "prompt_token_ids" in output
# Returned in the native output of the SGLang engine.
assert "meta_info" in output
assert "prompt_tokens" in output["meta_info"]
assert "completion_tokens" in output["meta_info"]
data = cls(
prompt=output["prompt"],
prompt_token_ids=output["prompt_token_ids"],
num_input_tokens=output["meta_info"]["prompt_tokens"],
generated_tokens=output["output_ids"] if "output_ids" in output else None,
generated_text=output["text"] if "text" in output else None,
num_generated_tokens=output["meta_info"]["completion_tokens"],
)
return data
class Config:
validate_assignment = True
arbitrary_types_allowed = True
| SGLangOutputData |
python | ipython__ipython | IPython/core/display_trap.py | {
"start": 915,
"end": 2185
} | class ____(Configurable):
"""Object to manage sys.displayhook.
This came from IPython.core.kernel.display_hook, but is simplified
(no callbacks or formatters) until more of the core is refactored.
"""
hook = Any()
def __init__(self, hook=None):
super(DisplayTrap, self).__init__(hook=hook, config=None)
self.old_hook = None
# We define this to track if a single BuiltinTrap is nested.
# Only turn off the trap when the outermost call to __exit__ is made.
self._nested_level = 0
def __enter__(self):
if self._nested_level == 0:
self.set()
self._nested_level += 1
return self
def __exit__(self, type, value, traceback):
if self._nested_level == 1:
self.unset()
self._nested_level -= 1
# Returning False will cause exceptions to propagate
return False
@property
def is_active(self) -> bool:
return self._nested_level != 0
def set(self):
"""Set the hook."""
if sys.displayhook is not self.hook:
self.old_hook = sys.displayhook
sys.displayhook = self.hook
def unset(self):
"""Unset the hook."""
sys.displayhook = self.old_hook
| DisplayTrap |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/pipelines/pipeline.py | {
"start": 6247,
"end": 6606
} | class ____(graphene.ObjectType):
materializedPartitions = non_null_list(graphene.String)
failedPartitions = non_null_list(graphene.String)
unmaterializedPartitions = non_null_list(graphene.String)
materializingPartitions = non_null_list(graphene.String)
class Meta:
name = "DefaultPartitionStatuses"
| GrapheneDefaultPartitionStatuses |
python | spyder-ide__spyder | spyder/utils/external/lockfile.py | {
"start": 3856,
"end": 8268
} | class ____:
"""
A mutex.
This relies on the filesystem property that creating
a symlink is an atomic operation and that it will
fail if the symlink already exists. Deleting the
symlink will release the lock.
@ivar name: The name of the file associated with this lock.
@ivar clean: Indicates whether this lock was released cleanly by its
last owner. Only meaningful after C{lock} has been called and
returns True.
@ivar locked: Indicates whether the lock is currently held by this
object.
"""
clean = None
locked = False
def __init__(self, name):
self.name = name
def lock(self):
"""
Acquire this lock.
@rtype: C{bool}
@return: True if the lock is acquired, false otherwise.
@raise: Any exception os.symlink() may raise, other than
EEXIST.
"""
clean = True
while True:
try:
symlink(str(os.getpid()), self.name)
except OSError as e:
if _windows and e.errno in (errno.EACCES, errno.EIO):
# The lock is in the middle of being deleted because we're
# on Windows where lock removal isn't atomic. Give up, we
# don't know how long this is going to take.
return False
if e.errno == errno.EEXIST:
try:
pid = readlink(self.name)
except OSError as e:
if e.errno == errno.ENOENT:
# The lock has vanished, try to claim it in the
# next iteration through the loop.
continue
raise
except IOError as e:
if _windows and e.errno == errno.EACCES:
# The lock is in the middle of being
# deleted because we're on Windows where
# lock removal isn't atomic. Give up, we
# don't know how long this is going to
# take.
return False
raise
try:
if kill is not None:
kill(int(pid), 0)
if not is_spyder_process(int(pid)):
raise(OSError(errno.ESRCH, 'No such process'))
except OSError as e:
if e.errno == errno.ESRCH:
# The owner has vanished, try to claim it in the
# next iteration through the loop.
try:
rmlink(self.name)
except OSError as e:
if e.errno == errno.ENOENT:
# Another process cleaned up the lock.
# Race them to acquire it in the next
# iteration through the loop.
continue
raise
clean = False
continue
raise
return False
raise
self.locked = True
self.clean = clean
return True
def unlock(self):
"""
Release this lock.
This deletes the directory with the given name.
@raise: Any exception os.readlink() may raise, or
ValueError if the lock is not owned by this process.
"""
pid = readlink(self.name)
if int(pid) != os.getpid():
raise ValueError("Lock %r not owned by this process" % (self.name,))
rmlink(self.name)
self.locked = False
def isLocked(name):
"""Determine if the lock of the given name is held or not.
@type name: C{str}
@param name: The filesystem path to the lock to test
@rtype: C{bool}
@return: True if the lock is held, False otherwise.
"""
l = FilesystemLock(name)
result = None
try:
result = l.lock()
finally:
if result:
l.unlock()
return not result
__all__ = ['FilesystemLock', 'isLocked']
| FilesystemLock |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 27830,
"end": 28944
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
mems (`list[torch.FloatTensor]` of length `config.n_layers`):
Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
token ids which have their past given to this model should not be passed as `input_ids` as they have
already been computed.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
mems: Optional[list[torch.FloatTensor]] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`XLNetForTokenClassificationOutput`].
"""
)
| XLNetForSequenceClassificationOutput |
python | langchain-ai__langchain | libs/core/langchain_core/callbacks/base.py | {
"start": 3440,
"end": 5443
} | class ____:
"""Mixin for chain callbacks."""
def on_chain_end(
self,
outputs: dict[str, Any],
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run when chain ends running.
Args:
outputs: The outputs of the chain.
run_id: The run ID. This is the ID of the current run.
parent_run_id: The parent run ID. This is the ID of the parent run.
**kwargs: Additional keyword arguments.
"""
def on_chain_error(
self,
error: BaseException,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run when chain errors.
Args:
error: The error that occurred.
run_id: The run ID. This is the ID of the current run.
parent_run_id: The parent run ID. This is the ID of the parent run.
**kwargs: Additional keyword arguments.
"""
def on_agent_action(
self,
action: AgentAction,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run on agent action.
Args:
action: The agent action.
run_id: The run ID. This is the ID of the current run.
parent_run_id: The parent run ID. This is the ID of the parent run.
**kwargs: Additional keyword arguments.
"""
def on_agent_finish(
self,
finish: AgentFinish,
*,
run_id: UUID,
parent_run_id: UUID | None = None,
**kwargs: Any,
) -> Any:
"""Run on the agent end.
Args:
finish: The agent finish.
run_id: The run ID. This is the ID of the current run.
parent_run_id: The parent run ID. This is the ID of the parent run.
**kwargs: Additional keyword arguments.
"""
| ChainManagerMixin |
python | encode__django-rest-framework | tests/test_negotiation.py | {
"start": 606,
"end": 675
} | class ____(BaseRenderer):
media_type = 'text/html'
| MockHTMLRenderer |
python | huggingface__transformers | src/transformers/models/gpt_oss/modular_gpt_oss.py | {
"start": 19452,
"end": 19508
} | class ____(MixtralForCausalLM):
pass
| GptOssForCausalLM |
python | apache__airflow | airflow-core/tests/unit/utils/test_event_scheduler.py | {
"start": 909,
"end": 1477
} | class ____:
def test_call_regular_interval(self):
somefunction = mock.MagicMock()
timers = EventScheduler()
timers.call_regular_interval(30, somefunction)
assert len(timers.queue) == 1
somefunction.assert_not_called()
# Fake a run (it won't actually pop from the queue):
timers.queue[0].action()
# Make sure it added another event to the queue
assert len(timers.queue) == 2
somefunction.assert_called_once()
assert timers.queue[0].time < timers.queue[1].time
| TestEventScheduler |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 41897,
"end": 58342
} | class ____(pa.ExtensionArray):
"""
An array of heterogeneous-shaped, homogeneous-typed tensors.
This is the Arrow side of TensorArray for tensor elements that have differing
shapes. Note that this extension only supports non-ragged tensor elements; i.e.,
when considering each tensor element in isolation, they must have a well-defined
shape. This extension also only supports tensor elements that all have the same
number of dimensions.
See Arrow docs for customizing extension arrays:
https://arrow.apache.org/docs/python/extending_types.html#custom-extension-array-class
"""
SHAPES_ARRAY_TYPE = pa.list_(pa.int64())
@classmethod
def from_numpy(
cls, arr: Union[np.ndarray, List[np.ndarray], Tuple[np.ndarray]]
) -> "ArrowVariableShapedTensorArray":
"""
Convert an ndarray or an iterable of heterogeneous-shaped ndarrays to an array
of heterogeneous-shaped, homogeneous-typed tensors.
Args:
arr: An ndarray or an iterable of heterogeneous-shaped ndarrays.
Returns:
An ArrowVariableShapedTensorArray containing len(arr) tensors of
heterogeneous shape.
"""
# Implementation note - Arrow representation of ragged tensors:
#
# We represent an array of ragged tensors using a struct array containing two
# fields:
# - data: a variable-sized list array, where each element in the array is a
# tensor element stored in a 1D (raveled) variable-sized list of the
# underlying scalar data type.
# - shape: a variable-sized list array containing the shapes of each tensor
# element.
if not isinstance(arr, (list, tuple, np.ndarray)):
raise ValueError(
"ArrowVariableShapedTensorArray can only be constructed from an "
f"ndarray or a list/tuple of ndarrays, but got: {type(arr)}"
)
if len(arr) == 0:
# Empty ragged tensor arrays are not supported.
raise ValueError("Creating empty ragged tensor arrays is not supported.")
# Pre-allocate lists for better performance
raveled = np.empty(len(arr), dtype=np.object_)
shapes = np.empty(len(arr), dtype=np.object_)
sizes = np.arange(len(arr), dtype=np.int64)
ndim = None
for i, a in enumerate(arr):
a = np.asarray(a)
if ndim is not None and a.ndim != ndim:
raise ValueError(
"ArrowVariableShapedTensorArray only supports tensor elements that "
"all have the same number of dimensions, but got tensor elements "
f"with dimensions: {ndim}, {a.ndim}"
)
ndim = a.ndim
shapes[i] = a.shape
sizes[i] = a.size
# Convert to 1D array view; this should be zero-copy in the common case.
# NOTE: If array is not in C-contiguous order, this will convert it to
# C-contiguous order, incurring a copy.
raveled[i] = np.ravel(a, order="C")
# Get size offsets and total size.
size_offsets = np.cumsum(sizes)
total_size = size_offsets[-1]
# An optimized zero-copy path if raveled tensor elements are already
# contiguous in memory, e.g. if this tensor array has already done a
# roundtrip through our Arrow representation.
data_buffer = _concat_ndarrays(raveled)
dtype = data_buffer.dtype
pa_scalar_type = pa.from_numpy_dtype(dtype)
if pa.types.is_string(pa_scalar_type):
if dtype.byteorder == ">" or (
dtype.byteorder == "=" and sys.byteorder == "big"
):
raise ValueError(
"Only little-endian string tensors are supported, "
f"but got: {dtype}"
)
pa_scalar_type = pa.binary(dtype.itemsize)
if dtype.type is np.bool_ and data_buffer.size > 0:
# NumPy doesn't represent boolean arrays as bit-packed, so we manually
# bit-pack the booleans before handing the buffer off to Arrow.
# NOTE: Arrow expects LSB bit-packed ordering.
# NOTE: This creates a copy.
data_buffer = np.packbits(data_buffer, bitorder="little")
# Use foreign_buffer for better performance when possible
data_buffer = pa.py_buffer(data_buffer)
# Construct underlying data array.
data_array = pa.Array.from_buffers(
pa_scalar_type, total_size, [None, data_buffer]
)
# Construct array for offsets into the 1D data array, where each offset
# corresponds to a tensor element.
size_offsets = np.insert(size_offsets, 0, 0)
offset_array = pa.array(size_offsets)
data_storage_array = pa.LargeListArray.from_arrays(offset_array, data_array)
# We store the tensor element shapes so we can reconstruct each tensor when
# converting back to NumPy ndarrays.
shape_array = pa.array(shapes)
# Build storage array containing tensor data and the tensor element shapes.
storage = pa.StructArray.from_arrays(
[data_storage_array, shape_array],
["data", "shape"],
)
type_ = ArrowVariableShapedTensorType(pa_scalar_type, ndim)
return type_.wrap_array(storage)
def to_numpy(self, zero_copy_only: bool = True):
"""
Convert the entire array of tensors into a single ndarray.
Args:
zero_copy_only: If True, an exception will be raised if the conversion to a
NumPy array would require copying the underlying data (e.g. in presence
of nulls, or for non-primitive types). This argument is currently
ignored, so zero-copy isn't enforced even if this argument is true.
Returns:
A single ndarray representing the entire array of tensors.
"""
data_array = self.storage.field("data")
shapes_array = self.storage.field("shape")
data_value_type = data_array.type.value_type
data_array_buffer = data_array.buffers()[3]
shapes = shapes_array.to_pylist()
offsets = data_array.offsets.to_pylist()
return create_ragged_ndarray(
[
_to_ndarray_helper(shape, data_value_type, offset, data_array_buffer)
for shape, offset in zip(shapes, offsets)
]
)
def to_var_shaped_tensor_array(self, ndim: int) -> "ArrowVariableShapedTensorArray":
if ndim == self.type.ndim:
return self
elif ndim < self.type.ndim:
raise ValueError(
f"Can't convert {self.type} to var-shaped tensor type with {ndim=}"
)
target_type = ArrowVariableShapedTensorType(self.type.scalar_type, ndim)
# Unpack source tensor array into internal data storage and shapes
# array
data_array = self.storage.field("data")
shapes_array = self.storage.field("shape")
# Pad individual shapes with singleton axes to match target number of
# dimensions
#
# TODO avoid python loop
expanded_shapes_array = pa.array(
[_pad_shape_with_singleton_axes(s, ndim) for s in shapes_array.to_pylist()]
)
storage = pa.StructArray.from_arrays([data_array, expanded_shapes_array])
return target_type.wrap_array(storage)
def _pad_shape_with_singleton_axes(
shape: Tuple[int, ...], ndim: int
) -> Tuple[int, ...]:
assert ndim >= len(shape)
return (1,) * (ndim - len(shape)) + shape
AnyArrowExtTensorType = Union[
ArrowTensorType, ArrowTensorTypeV2, ArrowVariableShapedTensorType
]
@DeveloperAPI(stability="alpha")
def unify_tensor_types(
types: Collection[AnyArrowExtTensorType],
) -> AnyArrowExtTensorType:
"""Unifies provided tensor types if compatible.
Otherwise raises a ``ValueError``.
"""
assert types, "List of tensor types may not be empty"
if len(types) == 1:
return types[0]
shapes = {t.shape for t in types}
scalar_types = {t.scalar_type for t in types}
# Only tensors with homogenous scalar types and shape dimensions
# are currently supported
if len(scalar_types) > 1:
raise pa.lib.ArrowTypeError(
f"Can't unify tensor types with divergent scalar types: {types}"
)
# If all shapes are identical, it's a single tensor type
if len(shapes) == 1:
return next(iter(types))
return ArrowVariableShapedTensorType(
dtype=scalar_types.pop(),
# NOTE: Cardinality of variable-shaped tensor type's (``ndims``) is
# derived as the max length of the shapes that are making it up
ndim=max(len(s) for s in shapes),
)
@DeveloperAPI(stability="alpha")
def unify_tensor_arrays(
arrs: List[Union[ArrowTensorArray, ArrowVariableShapedTensorArray]]
) -> List[Union[ArrowTensorArray, ArrowVariableShapedTensorArray]]:
supported_tensor_types = get_arrow_extension_tensor_types()
# Derive number of distinct tensor types
distinct_types_ = set()
for arr in arrs:
if isinstance(arr.type, supported_tensor_types):
distinct_types_.add(arr.type)
else:
raise ValueError(
f"Trying to unify unsupported tensor type: {arr.type} (supported types: {supported_tensor_types})"
)
if len(distinct_types_) == 1:
return arrs
# Verify provided tensor arrays could be unified
#
# NOTE: If there's more than 1 distinct tensor types, then unified
# type will be variable-shaped
unified_tensor_type = unify_tensor_types(distinct_types_)
assert isinstance(unified_tensor_type, ArrowVariableShapedTensorType)
unified_arrs = []
for arr in arrs:
unified_arrs.append(
arr.to_var_shaped_tensor_array(ndim=unified_tensor_type.ndim)
)
return unified_arrs
@DeveloperAPI(stability="alpha")
def concat_tensor_arrays(
arrays: List[Union["ArrowTensorArray", "ArrowVariableShapedTensorArray"]],
ensure_copy: bool = False,
) -> Union["ArrowTensorArray", "ArrowVariableShapedTensorArray"]:
"""
Concatenates multiple tensor arrays.
NOTE: If one or more of the tensor arrays are variable-shaped and/or any
of the tensor arrays have a different shape than the others, a variable-shaped
tensor array will be returned.
Args:
arrays: Tensor arrays to concat
ensure_copy: Skip copying when ensure_copy is False and there is exactly 1 chunk.
Returns:
Either ``ArrowTensorArray`` or ``ArrowVariableShapedTensorArray`` holding
all of the given tensor arrays concatenated.
"""
assert arrays, "List of tensor arrays may not be empty"
if len(arrays) == 1 and not ensure_copy:
# Short-circuit
return arrays[0]
# First, unify provided tensor arrays
unified_arrays = unify_tensor_arrays(arrays)
# Then, simply concat underlying internal storage
storage = pa.concat_arrays([c.storage for c in unified_arrays])
unified_array_type = unified_arrays[0].type
return unified_array_type.wrap_array(storage)
def _concat_ndarrays(arrs: Union[np.ndarray, List[np.ndarray]]) -> np.ndarray:
"""Concatenates provided collection of ``np.ndarray``s in either of the following
ways:
- If provided ndarrays are contiguous, 1D views sharing the same dtype,
living w/in the same base view, these will be concatenated zero-copy
by reusing underlying view
- Otherwise, ``np.concatenate(arrays)`` will be invoked
"""
assert len(arrs) > 0, "Provided collection of ndarrays may not be empty"
if len(arrs) == 1:
# Short-circuit
return arrs[0]
elif not _are_contiguous_1d_views(arrs):
return np.concatenate(arrs)
dtype = arrs[0].dtype
base = _get_root_base(arrs[0])
base_ptr = _get_buffer_address(base)
start_byte = _get_buffer_address(arrs[0]) - base_ptr
end_byte = start_byte + sum(a.nbytes for a in arrs)
# Build the view from the base, using byte offsets for generality
byte_view = base.view(np.uint8).reshape(-1)
out = byte_view[start_byte:end_byte].view(dtype)
return out
def _are_contiguous_1d_views(arrs: Union[np.ndarray, List[np.ndarray]]) -> bool:
dtype = arrs[0].dtype
base = _get_root_base(arrs[0])
expected_addr = _get_base_ptr(arrs[0])
for a in arrs:
# Assert all provided arrays are
# - Raveled (1D)
# - Share dtype
# - Contiguous
# - Share the same `base` view (this is crucial to make sure
# that all provided ndarrays live w/in the same allocation and
# share its lifecycle)
if (
a.ndim != 1
or a.dtype != dtype
or not a.flags.c_contiguous
or _get_root_base(a) is not base
):
return False
# Skip empty ndarrays
if a.size == 0:
continue
buffer_addr = _get_base_ptr(a)
if buffer_addr != expected_addr:
return False
expected_addr = buffer_addr + a.size * dtype.itemsize
return True
def _get_base_ptr(a: np.ndarray) -> int:
# same as a.ctypes.data, but robust for views
return _get_buffer_address(a)
def _get_root_base(a: np.ndarray) -> np.ndarray:
b = a
while isinstance(b.base, np.ndarray):
b = b.base
return b if b.base is not None else b # owner if base is None
def _get_buffer_address(arr: np.ndarray) -> int:
"""Get the address of the buffer underlying the provided NumPy ndarray."""
return arr.__array_interface__["data"][0]
def _to_ndarray_helper(shape, value_type, offset, data_buffer):
if pa.types.is_boolean(value_type):
# Arrow boolean array buffers are bit-packed, with 8 entries per byte,
# and are accessed via bit offsets.
buffer_item_width = value_type.bit_width
else:
# We assume all other array types are accessed via byte array
# offsets.
buffer_item_width = value_type.bit_width // 8
data_offset = buffer_item_width * offset
if pa.types.is_boolean(value_type):
# Special handling for boolean arrays, since Arrow
# bit-packs boolean arrays while NumPy does not.
# Cast as uint8 array and let NumPy unpack into a boolean view.
# Offset into uint8 array, where each element is
# a bucket for 8 booleans.
byte_bucket_offset = data_offset // 8
# Offset for a specific boolean, within a uint8 array element.
bool_offset = data_offset % 8
# The number of uint8 array elements (buckets) that our slice spans.
# Note that, due to the offset for a specific boolean,
# the slice can span byte boundaries even if it contains
# less than 8 booleans.
num_boolean_byte_buckets = 1 + ((bool_offset + np.prod(shape) - 1) // 8)
# Construct the uint8 array view on the buffer.
arr = np.ndarray(
(num_boolean_byte_buckets,),
dtype=np.uint8,
buffer=data_buffer,
offset=byte_bucket_offset,
)
# Unpack into a byte per boolean, using LSB bit-packed ordering.
arr = np.unpackbits(arr, bitorder="little")
# Interpret buffer as boolean array.
return np.ndarray(shape, dtype=np.bool_, buffer=arr, offset=bool_offset)
ext_dtype = value_type.to_pandas_dtype()
# Special handling of ragged string tensors
if pa.types.is_fixed_size_binary(value_type):
ext_dtype = np.dtype(f"<U{value_type.byte_width // NUM_BYTES_PER_UNICODE_CHAR}")
return np.ndarray(shape, dtype=ext_dtype, buffer=data_buffer, offset=data_offset)
try:
# Registration needs an extension type instance, but then works for any instance of
# the same subclass regardless of parametrization of the type.
pa.register_extension_type(ArrowTensorType((0,), pa.int64()))
pa.register_extension_type(ArrowTensorTypeV2((0,), pa.int64()))
pa.register_extension_type(ArrowVariableShapedTensorType(pa.int64(), 0))
except pa.ArrowKeyError:
# Extension types are already registered.
pass
| ArrowVariableShapedTensorArray |
python | getsentry__sentry | src/sentry/processing/backpressure/memory.py | {
"start": 203,
"end": 553
} | class ____:
name: str
used: int
available: int
percentage: float
host: str | None = None
port: int | None = None
def __init__(self, name: str, used: int, available: int):
self.name = name
self.used = used
self.available = available
self.percentage = used / available
@dataclass
| ServiceMemory |
python | doocs__leetcode | solution/2000-2099/2003.Smallest Missing Genetic Value in Each Subtree/Solution.py | {
"start": 0,
"end": 867
} | class ____:
def smallestMissingValueSubtree(
self, parents: List[int], nums: List[int]
) -> List[int]:
def dfs(i: int):
if vis[i]:
return
vis[i] = True
if nums[i] < len(has):
has[nums[i]] = True
for j in g[i]:
dfs(j)
n = len(nums)
ans = [1] * n
g = [[] for _ in range(n)]
idx = -1
for i, p in enumerate(parents):
if i:
g[p].append(i)
if nums[i] == 1:
idx = i
if idx == -1:
return ans
vis = [False] * n
has = [False] * (n + 2)
i = 2
while idx != -1:
dfs(idx)
while has[i]:
i += 1
ans[idx] = i
idx = parents[idx]
return ans
| Solution |
python | ray-project__ray | python/ray/train/v2/_internal/state/schema.py | {
"start": 7399,
"end": 8584
} | class ____(BaseModel):
"""Metadata for a Ray Train run, including its details and status."""
id: str = Field(description="Unique identifier for the Train run.")
name: str = Field(description="Human-readable name assigned to the Train run.")
job_id: str = Field(description="The Ray Job ID associated with this Train run.")
controller_actor_id: str = Field(
description="Unique ID of the actor managing the Train run."
)
status: RunStatus = Field(
description="The current execution status of the Train run."
)
status_detail: Optional[str] = Field(
description="Additional details about the current status, "
"including error messages if applicable."
)
start_time_ns: int = Field(
description="The UNIX timestamp (in nanoseconds) when the Train run started."
)
end_time_ns: Optional[int] = Field(
description="The UNIX timestamp (in nanoseconds) when the Train run ended. "
"If null, the run is still in progress."
)
controller_log_file_path: Optional[str] = Field(
description="The path to the log file for the Train run controller."
)
@DeveloperAPI
| TrainRun |
python | numpy__numpy | numpy/_core/tests/test_ufunc.py | {
"start": 131541,
"end": 137219
} | class ____:
def test_resolve_dtypes_basic(self):
# Basic test for dtype resolution:
i4 = np.dtype("i4")
f4 = np.dtype("f4")
f8 = np.dtype("f8")
r = np.add.resolve_dtypes((i4, f4, None))
assert r == (f8, f8, f8)
# Signature uses the same logic to parse as ufunc (less strict)
# the following is "same-kind" casting so works:
r = np.add.resolve_dtypes((
i4, i4, None), signature=(None, None, "f4"))
assert r == (f4, f4, f4)
# Check NEP 50 "weak" promotion also:
r = np.add.resolve_dtypes((f4, int, None))
assert r == (f4, f4, f4)
with pytest.raises(TypeError):
np.add.resolve_dtypes((i4, f4, None), casting="no")
def test_resolve_dtypes_comparison(self):
i4 = np.dtype("i4")
i8 = np.dtype("i8")
b = np.dtype("?")
r = np.equal.resolve_dtypes((i4, i8, None))
assert r == (i8, i8, b)
def test_weird_dtypes(self):
S0 = np.dtype("S0")
# S0 is often converted by NumPy to S1, but not here:
r = np.equal.resolve_dtypes((S0, S0, None))
assert r == (S0, S0, np.dtype(bool))
# Subarray dtypes are weird and may not work fully, we preserve them
# leading to a TypeError (currently no equal loop for void/structured)
dts = np.dtype("10i")
with pytest.raises(TypeError):
np.equal.resolve_dtypes((dts, dts, None))
def test_resolve_dtypes_reduction(self):
i2 = np.dtype("i2")
default_int_ = np.dtype(np.int_)
# Check special addition resolution:
res = np.add.resolve_dtypes((None, i2, None), reduction=True)
assert res == (default_int_, default_int_, default_int_)
def test_resolve_dtypes_reduction_no_output(self):
i4 = np.dtype("i4")
with pytest.raises(TypeError):
# May be allowable at some point?
np.add.resolve_dtypes((i4, i4, i4), reduction=True)
@pytest.mark.parametrize("dtypes", [
(np.dtype("i"), np.dtype("i")),
(None, np.dtype("i"), np.dtype("f")),
(np.dtype("i"), None, np.dtype("f")),
("i4", "i4", None)])
def test_resolve_dtypes_errors(self, dtypes):
with pytest.raises(TypeError):
np.add.resolve_dtypes(dtypes)
def test_resolve_dtypes_reduction_errors(self):
i2 = np.dtype("i2")
with pytest.raises(TypeError):
np.add.resolve_dtypes((None, i2, i2))
with pytest.raises(TypeError):
np.add.signature((None, None, "i4"))
@pytest.mark.skipif(not hasattr(ct, "pythonapi"),
reason="`ctypes.pythonapi` required for capsule unpacking.")
@pytest.mark.thread_unsafe(reason="modifies global object in the ctypes API")
def test_loop_access(self):
# This is a basic test for the full strided loop access
data_t = ct.c_char_p * 2
dim_t = ct.c_ssize_t * 1
strides_t = ct.c_ssize_t * 2
strided_loop_t = ct.CFUNCTYPE(
ct.c_int, ct.c_void_p, data_t, dim_t, strides_t, ct.c_void_p)
class call_info_t(ct.Structure):
_fields_ = [
("strided_loop", strided_loop_t),
("context", ct.c_void_p),
("auxdata", ct.c_void_p),
("requires_pyapi", ct.c_byte),
("no_floatingpoint_errors", ct.c_byte),
]
i4 = np.dtype("i4")
dt, call_info_obj = np.negative._resolve_dtypes_and_context((i4, i4))
assert dt == (i4, i4) # can be used without casting
# Fill in the rest of the information:
np.negative._get_strided_loop(call_info_obj)
ct.pythonapi.PyCapsule_GetPointer.restype = ct.c_void_p
call_info = ct.pythonapi.PyCapsule_GetPointer(
ct.py_object(call_info_obj),
ct.c_char_p(b"numpy_1.24_ufunc_call_info"))
call_info = ct.cast(call_info, ct.POINTER(call_info_t)).contents
arr = np.arange(10, dtype=i4)
call_info.strided_loop(
call_info.context,
data_t(arr.ctypes.data, arr.ctypes.data),
arr.ctypes.shape, # is a C-array with 10 here
strides_t(arr.ctypes.strides[0], arr.ctypes.strides[0]),
call_info.auxdata)
# We just directly called the negative inner-loop in-place:
assert_array_equal(arr, -np.arange(10, dtype=i4))
@pytest.mark.parametrize("strides", [1, (1, 2, 3), (1, "2")])
def test__get_strided_loop_errors_bad_strides(self, strides):
i4 = np.dtype("i4")
dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
with pytest.raises(TypeError, match="fixed_strides.*tuple.*or None"):
np.negative._get_strided_loop(call_info, fixed_strides=strides)
def test__get_strided_loop_errors_bad_call_info(self):
i4 = np.dtype("i4")
dt, call_info = np.negative._resolve_dtypes_and_context((i4, i4))
with pytest.raises(ValueError, match="PyCapsule"):
np.negative._get_strided_loop("not the capsule!")
with pytest.raises(TypeError, match=".*incompatible context"):
np.add._get_strided_loop(call_info)
np.negative._get_strided_loop(call_info)
with pytest.raises(TypeError):
# cannot call it a second time:
np.negative._get_strided_loop(call_info)
def test_long_arrays(self):
t = np.zeros((1029, 917), dtype=np.single)
t[0][0] = 1
t[28][414] = 1
tc = np.cos(t)
assert_equal(tc[0][0], tc[28][414])
| TestLowlevelAPIAccess |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-oci-genai/llama_index/embeddings/oci_genai/base.py | {
"start": 761,
"end": 10750
} | class ____(BaseEmbedding):
"""
OCI embedding models.
To authenticate, the OCI client uses the methods described in
https://docs.oracle.com/en-us/iaas/Content/API/Concepts/sdk_authentication_methods.htm
The authentifcation method is passed through auth_type and should be one of:
API_KEY (default), SECURITY_TOKEN, INSTANCE_PRINCIPAL, RESOURCE_PRINCIPAL
Make sure you have the required policies (profile/roles) to
access the OCI Generative AI service. If a specific config profile is used,
you must pass the name of the profile (~/.oci/config) through auth_profile.
If a specific config file location is used, you must pass
the file location where profile name configs present
through auth_file_location
To use, you must provide the compartment id
along with the endpoint url, and model id
as named parameters to the constructor.
Example:
.. code-block:: python
from llama_index.embeddings.oci_genai import OCIGenAIEmbeddings
embeddings = OCIGenAIEmbeddings(
model_name="MY_EMBEDDING_MODEL",
service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com",
compartment_id="MY_OCID"
)
"""
model_name: str = Field(
description="ID or Name of the OCI Generative AI embedding model to use."
)
truncate: str = Field(
description="Truncate embeddings that are too long from start or end, values START/ END/ NONE",
default="END",
)
input_type: Optional[str] = Field(
description="Model Input type. If not provided, search_document and search_query are used when needed.",
default=None,
)
service_endpoint: Optional[str] = Field(
description="service endpoint url.",
default=None,
)
compartment_id: Optional[str] = Field(
description="OCID of compartment.",
default=None,
)
auth_type: Optional[str] = Field(
description="Authentication type, can be: API_KEY, SECURITY_TOKEN, INSTANCE_PRINCIPAL, RESOURCE_PRINCIPAL. If not specified, API_KEY will be used",
default="API_KEY",
)
auth_profile: Optional[str] = Field(
description="The name of the profile in ~/.oci/config. If not specified , DEFAULT will be used",
default="DEFAULT",
)
auth_file_location: Optional[str] = Field(
description="Path to the config file. If not specified, ~/.oci/config will be used",
default="~/.oci/config",
)
_client: Any = PrivateAttr()
def __init__(
self,
model_name: str,
truncate: str = "END",
input_type: Optional[str] = None,
service_endpoint: Optional[str] = None,
compartment_id: Optional[str] = None,
auth_type: Optional[str] = "API_KEY",
auth_profile: Optional[str] = "DEFAULT",
auth_file_location: Optional[str] = "~/.oci/config",
client: Optional[Any] = None,
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
callback_manager: Optional[CallbackManager] = None,
):
"""
Initializes the OCIGenAIEmbeddings class.
Args:
model_name (str): The name or ID of the model to be used for generating embeddings, e.g., "cohere.embed-english-light-v3.0".
truncate (str): A string indicating the truncation strategy for long input text. Possible values
are 'START', 'END', or 'NONE'.
input_type (Optional[str]): An optional string that specifies the type of input provided to the model.
This is model-dependent and could be one of the following: "search_query",
"search_document", "classification", or "clustering".
service_endpoint (str): service endpoint url, e.g., "https://inference.generativeai.us-chicago-1.oci.oraclecloud.com"
compartment_id (str): OCID of the compartment.
auth_type (Optional[str]): Authentication type, can be: API_KEY (default), SECURITY_TOKEN, INSTANCEAL, RESOURCE_PRINCIPAL. If not specified, API_KEY will be used
auth_profile (Optional[str]): The name of the profile in ~/.oci/config. If not specified , DEFAULT will be used
auth_file_location (Optional[str]): Path to the config file, If not specified, ~/.oci/config will be used.
client (Optional[Any]): An optional OCI client object. If not provided, the client will be created using the
provided service endpoint and authentifcation method.
"""
super().__init__(
model_name=model_name,
truncate=truncate,
input_type=input_type,
service_endpoint=service_endpoint,
compartment_id=compartment_id,
auth_type=auth_type,
auth_profile=auth_profile,
auth_file_location=auth_file_location,
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
)
if client is not None:
self._client = client
else:
try:
import oci
client_kwargs = {
"config": {},
"signer": None,
"service_endpoint": service_endpoint,
"retry_strategy": oci.retry.DEFAULT_RETRY_STRATEGY,
"timeout": (
10,
240,
), # default timeout config for OCI Gen AI service
}
if auth_type == OCIAuthType(1).name:
client_kwargs["config"] = oci.config.from_file(
file_location=auth_file_location, profile_name=auth_profile
)
client_kwargs.pop("signer", None)
elif auth_type == OCIAuthType(2).name:
def make_security_token_signer(oci_config): # type: ignore[no-untyped-def]
pk = oci.signer.load_private_key_from_file(
oci_config.get("key_file"), None
)
with open(
oci_config.get("security_token_file"), encoding="utf-8"
) as f:
st_string = f.read()
return oci.auth.signers.SecurityTokenSigner(st_string, pk)
client_kwargs["config"] = oci.config.from_file(
file_location=auth_file_location, profile_name=auth_profile
)
client_kwargs["signer"] = make_security_token_signer(
oci_config=client_kwargs["config"]
)
elif auth_type == OCIAuthType(3).name:
client_kwargs["signer"] = (
oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
)
elif auth_type == OCIAuthType(4).name:
client_kwargs["signer"] = (
oci.auth.signers.get_resource_principals_signer()
)
else:
raise ValueError(
f"Please provide valid value to auth_type, {auth_type} is not valid."
)
self._client = oci.generative_ai_inference.GenerativeAiInferenceClient(
**client_kwargs
)
except ImportError as ex:
raise ModuleNotFoundError(
"Could not import oci python package. "
"Please make sure you have the oci package installed."
) from ex
except Exception as e:
raise ValueError(
"""Could not authenticate with OCI client.
If INSTANCE_PRINCIPAL or RESOURCE_PRINCIPAL is used, please check the specified
auth_profile, auth_file_location and auth_type are valid.""",
e,
) from e
@classmethod
def class_name(self) -> str:
return "OCIGenAIEmbeddings"
@staticmethod
def list_supported_models() -> List[str]:
return list(SUPPORTED_MODELS)
def _embed(self, texts: List[str], input_type: str) -> List[List[float]]:
try:
from oci.generative_ai_inference import models
except ImportError as ex:
raise ModuleNotFoundError(
"Could not import oci python package. "
"Please make sure you have the oci package installed."
) from ex
if self.model_name.startswith(CUSTOM_ENDPOINT_PREFIX):
serving_mode = models.DedicatedServingMode(endpoint_id=self.model_name)
else:
serving_mode = models.OnDemandServingMode(model_id=self.model_name)
request = models.EmbedTextDetails(
serving_mode=serving_mode,
compartment_id=self.compartment_id,
input_type=self.input_type or input_type,
truncate=self.truncate,
inputs=texts,
)
response = self._client.embed_text(request)
return response.data.embeddings
def _get_query_embedding(self, query: str) -> List[float]:
return self._embed([query], input_type="SEARCH_QUERY")[0]
def _get_text_embedding(self, text: str) -> List[float]:
return self._embed([text], input_type="SEARCH_DOCUMENT")[0]
def _get_text_embeddings(self, text: str) -> List[List[float]]:
return self._embed(text, input_type="SEARCH_DOCUMENT")
async def _aget_text_embedding(self, text: str) -> List[float]:
return self._get_text_embedding(text)
async def _aget_query_embedding(self, query: str) -> List[float]:
return self._get_query_embedding(query)
| OCIGenAIEmbeddings |
python | apache__airflow | airflow-ctl/tests/airflow_ctl/api/test_operations.py | {
"start": 44307,
"end": 47980
} | class ____:
key = "key"
value = "val"
description = "description"
variable = VariableBody.model_validate(
{
"key": key,
"value": value,
"description": description,
}
)
variable_response = VariableResponse(
key=key,
value=value,
description=description,
is_encrypted=False,
)
variable_collection_response = VariableCollectionResponse(
variables=[variable_response],
total_entries=1,
)
variable_bulk = BulkBodyVariableBody(
actions=[
BulkCreateActionVariableBody(
action="create",
entities=[variable],
action_on_existence=BulkActionOnExistence.FAIL,
)
]
)
variable_bulk_response = BulkResponse(
create=BulkActionResponse(success=[key], errors=[]),
update=None,
delete=None,
)
def test_get(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == f"/api/v2/variables/{self.key}"
return httpx.Response(200, json=json.loads(self.variable_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.get(self.key)
assert response == self.variable_response
def test_list(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/api/v2/variables"
return httpx.Response(200, json=json.loads(self.variable_collection_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.list()
assert response == self.variable_collection_response
def test_create(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/api/v2/variables"
return httpx.Response(200, json=json.loads(self.variable_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.create(variable=self.variable)
assert response == self.variable_response
def test_bulk(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/api/v2/variables"
return httpx.Response(200, json=json.loads(self.variable_bulk_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.bulk(variables=self.variable_bulk)
assert response == self.variable_bulk_response
def test_delete(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == f"/api/v2/variables/{self.key}"
return httpx.Response(200, json=json.loads(self.variable_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.delete(self.key)
assert response == self.key
def test_update(self):
def handle_request(request: httpx.Request) -> httpx.Response:
assert request.url.path == f"/api/v2/variables/{self.key}"
return httpx.Response(200, json=json.loads(self.variable_response.model_dump_json()))
client = make_api_client(transport=httpx.MockTransport(handle_request))
response = client.variables.update(variable=self.variable)
assert response == self.variable_response
| TestVariablesOperations |
python | huggingface__transformers | src/transformers/models/gemma3/modular_gemma3.py | {
"start": 17292,
"end": 21340
} | class ____(Gemma2RotaryEmbedding):
def __init__(self, config: Gemma3TextConfig, device=None, layer_type=None):
nn.Module.__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.layer_types = list(set(config.layer_types))
self.rope_type = {}
for layer_type in self.layer_types:
rope_params = self.config.rope_parameters[layer_type]
if rope_params is None:
continue
self.rope_type[layer_type] = rope_params["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type[layer_type] != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)
self.register_buffer(f"{layer_type}_inv_freq", curr_inv_freq, persistent=False)
setattr(self, f"{layer_type}_original_inv_freq", curr_inv_freq)
setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
@staticmethod
def compute_default_rope_parameters(
config: Optional[Gemma3TextConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
layer_type: Optional[str] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
layer_type (`str`, *optional*):
The current layer type if the model has different RoPE parameters per type.
Should not be used unless `config.layer_types is not None`
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
# For backward compatibility standardize the `rope_parameters_dict` if it uses old format
base = config.rope_parameters[layer_type]["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids, layer_type=None):
inv_freq = getattr(self, f"{layer_type}_inv_freq")
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * attention_scaling
sin = emb.sin() * attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
# Weird way to inherit but otherwise the sliding window gets defined first and can't access `is_sliding`
| Gemma3RotaryEmbedding |
python | numpy__numpy | numpy/_core/tests/test_umath_complex.py | {
"start": 16208,
"end": 19658
} | class ____:
def test_simple(self):
check_real_value(ncu._arg, 1, 0, 0, False)
check_real_value(ncu._arg, 0, 1, 0.5 * np.pi, False)
check_real_value(ncu._arg, 1, 1, 0.25 * np.pi, False)
check_real_value(ncu._arg, ncu.PZERO, ncu.PZERO, ncu.PZERO)
# TODO This can be xfail when the generator functions are got rid of.
@pytest.mark.skip(
reason="Complex arithmetic with signed zero fails on most platforms")
def test_zero(self):
# carg(-0 +- 0i) returns +- pi
check_real_value(ncu._arg, ncu.NZERO, ncu.PZERO, np.pi, False)
check_real_value(ncu._arg, ncu.NZERO, ncu.NZERO, -np.pi, False)
# carg(+0 +- 0i) returns +- 0
check_real_value(ncu._arg, ncu.PZERO, ncu.PZERO, ncu.PZERO)
check_real_value(ncu._arg, ncu.PZERO, ncu.NZERO, ncu.NZERO)
# carg(x +- 0i) returns +- 0 for x > 0
check_real_value(ncu._arg, 1, ncu.PZERO, ncu.PZERO, False)
check_real_value(ncu._arg, 1, ncu.NZERO, ncu.NZERO, False)
# carg(x +- 0i) returns +- pi for x < 0
check_real_value(ncu._arg, -1, ncu.PZERO, np.pi, False)
check_real_value(ncu._arg, -1, ncu.NZERO, -np.pi, False)
# carg(+- 0 + yi) returns pi/2 for y > 0
check_real_value(ncu._arg, ncu.PZERO, 1, 0.5 * np.pi, False)
check_real_value(ncu._arg, ncu.NZERO, 1, 0.5 * np.pi, False)
# carg(+- 0 + yi) returns -pi/2 for y < 0
check_real_value(ncu._arg, ncu.PZERO, -1, 0.5 * np.pi, False)
check_real_value(ncu._arg, ncu.NZERO, -1, -0.5 * np.pi, False)
#def test_branch_cuts(self):
# _check_branch_cut(ncu._arg, -1, 1j, -1, 1)
def test_special_values(self):
# carg(-np.inf +- yi) returns +-pi for finite y > 0
check_real_value(ncu._arg, -np.inf, 1, np.pi, False)
check_real_value(ncu._arg, -np.inf, -1, -np.pi, False)
# carg(np.inf +- yi) returns +-0 for finite y > 0
check_real_value(ncu._arg, np.inf, 1, ncu.PZERO, False)
check_real_value(ncu._arg, np.inf, -1, ncu.NZERO, False)
# carg(x +- np.infi) returns +-pi/2 for finite x
check_real_value(ncu._arg, 1, np.inf, 0.5 * np.pi, False)
check_real_value(ncu._arg, 1, -np.inf, -0.5 * np.pi, False)
# carg(-np.inf +- np.infi) returns +-3pi/4
check_real_value(ncu._arg, -np.inf, np.inf, 0.75 * np.pi, False)
check_real_value(ncu._arg, -np.inf, -np.inf, -0.75 * np.pi, False)
# carg(np.inf +- np.infi) returns +-pi/4
check_real_value(ncu._arg, np.inf, np.inf, 0.25 * np.pi, False)
check_real_value(ncu._arg, np.inf, -np.inf, -0.25 * np.pi, False)
# carg(x + yi) returns np.nan if x or y is nan
check_real_value(ncu._arg, np.nan, 0, np.nan, False)
check_real_value(ncu._arg, 0, np.nan, np.nan, False)
check_real_value(ncu._arg, np.nan, np.inf, np.nan, False)
check_real_value(ncu._arg, np.inf, np.nan, np.nan, False)
def check_real_value(f, x1, y1, x, exact=True):
z1 = np.array([complex(x1, y1)])
if exact:
assert_equal(f(z1), x)
else:
assert_almost_equal(f(z1), x)
def check_complex_value(f, x1, y1, x2, y2, exact=True):
z1 = np.array([complex(x1, y1)])
z2 = complex(x2, y2)
with np.errstate(invalid='ignore'):
if exact:
assert_equal(f(z1), z2)
else:
assert_almost_equal(f(z1), z2)
| TestCarg |
python | openai__openai-python | src/openai/resources/beta/realtime/realtime.py | {
"start": 35836,
"end": 38225
} | class ____(BaseAsyncRealtimeConnectionResource):
async def clear(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None:
"""Send this event to clear the audio bytes in the buffer.
The server will
respond with an `input_audio_buffer.cleared` event.
"""
await self._connection.send(
cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.clear", "event_id": event_id}))
)
async def commit(self, *, event_id: str | NotGiven = NOT_GIVEN) -> None:
"""
Send this event to commit the user input audio buffer, which will create a
new user message item in the conversation. This event will produce an error
if the input audio buffer is empty. When in Server VAD mode, the client does
not need to send this event, the server will commit the audio buffer
automatically.
Committing the input audio buffer will trigger input audio transcription
(if enabled in session configuration), but it will not create a response
from the model. The server will respond with an `input_audio_buffer.committed`
event.
"""
await self._connection.send(
cast(RealtimeClientEventParam, strip_not_given({"type": "input_audio_buffer.commit", "event_id": event_id}))
)
async def append(self, *, audio: str, event_id: str | NotGiven = NOT_GIVEN) -> None:
"""Send this event to append audio bytes to the input audio buffer.
The audio
buffer is temporary storage you can write to and later commit. In Server VAD
mode, the audio buffer is used to detect speech and the server will decide
when to commit. When Server VAD is disabled, you must commit the audio buffer
manually.
The client may choose how much audio to place in each event up to a maximum
of 15 MiB, for example streaming smaller chunks from the client may allow the
VAD to be more responsive. Unlike made other client events, the server will
not send a confirmation response to this event.
"""
await self._connection.send(
cast(
RealtimeClientEventParam,
strip_not_given({"type": "input_audio_buffer.append", "audio": audio, "event_id": event_id}),
)
)
| AsyncRealtimeInputAudioBufferResource |
python | mozilla__bleach | bleach/_vendor/html5lib/treewalkers/etree_lxml.py | {
"start": 422,
"end": 1412
} | class ____(object):
def __init__(self, et):
self.elementtree = et
self.children = []
try:
if et.docinfo.internalDTD:
self.children.append(Doctype(self,
ensure_str(et.docinfo.root_name),
ensure_str(et.docinfo.public_id),
ensure_str(et.docinfo.system_url)))
except AttributeError:
pass
try:
node = et.getroot()
except AttributeError:
node = et
while node.getprevious() is not None:
node = node.getprevious()
while node is not None:
self.children.append(node)
node = node.getnext()
self.text = None
self.tail = None
def __getitem__(self, key):
return self.children[key]
def getnext(self):
return None
def __len__(self):
return 1
| Root |
python | RaRe-Technologies__gensim | gensim/test/test_atmodel.py | {
"start": 2183,
"end": 25102
} | class ____(unittest.TestCase, basetmtests.TestBaseTopicModel):
def setUp(self):
self.corpus = mmcorpus.MmCorpus(datapath('testcorpus.mm'))
self.class_ = atmodel.AuthorTopicModel
self.model = self.class_(corpus, id2word=dictionary, author2doc=author2doc, num_topics=2, passes=100)
def test_transform(self):
passed = False
# sometimes, training gets stuck at a local minimum
# in that case try re-training the model from scratch, hoping for a
# better random initialization
for i in range(25): # restart at most 5 times
# create the transformation model
model = self.class_(id2word=dictionary, num_topics=2, passes=100, random_state=0)
model.update(corpus, author2doc)
jill_topics = model.get_author_topics('jill')
# NOTE: this test may easily fail if the author-topic model is altered in any way. The model's
# output is sensitive to a lot of things, like the scheduling of the updates, or like the
# author2id (because the random initialization changes when author2id changes). If it does
# fail, simply be aware of whether we broke something, or if it just naturally changed the
# output of the model slightly.
vec = matutils.sparse2full(jill_topics, 2) # convert to dense vector, for easier equality tests
expected = [0.91, 0.08]
# must contain the same values, up to re-ordering
passed = np.allclose(sorted(vec), sorted(expected), atol=1e-1)
if passed:
break
logging.warning(
"Author-topic model failed to converge on attempt %i (got %s, expected %s)",
i, sorted(vec), sorted(expected)
)
self.assertTrue(passed)
def test_basic(self):
# Check that training the model produces a positive topic vector for some author
# Otherwise, many of the other tests are invalid.
model = self.class_(corpus, author2doc=author2doc, id2word=dictionary, num_topics=2)
jill_topics = model.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
self.assertTrue(all(jill_topics > 0))
def test_empty_document(self):
local_texts = common_texts + [['only_occurs_once_in_corpus_and_alone_in_doc']]
dictionary = Dictionary(local_texts)
dictionary.filter_extremes(no_below=2)
corpus = [dictionary.doc2bow(text) for text in local_texts]
a2d = author2doc.copy()
a2d['joaquin'] = [len(local_texts) - 1]
self.class_(corpus, author2doc=a2d, id2word=dictionary, num_topics=2)
def test_author2doc_missing(self):
# Check that the results are the same if author2doc is constructed automatically from doc2author.
model = self.class_(
corpus, author2doc=author2doc, doc2author=doc2author,
id2word=dictionary, num_topics=2, random_state=0
)
model2 = self.class_(
corpus, doc2author=doc2author, id2word=dictionary,
num_topics=2, random_state=0
)
# Compare Jill's topics before in both models.
jill_topics = model.get_author_topics('jill')
jill_topics2 = model2.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
self.assertTrue(np.allclose(jill_topics, jill_topics2))
def test_doc2author_missing(self):
# Check that the results are the same if doc2author is constructed automatically from author2doc.
model = self.class_(
corpus, author2doc=author2doc, doc2author=doc2author,
id2word=dictionary, num_topics=2, random_state=0
)
model2 = self.class_(
corpus, author2doc=author2doc, id2word=dictionary,
num_topics=2, random_state=0
)
# Compare Jill's topics before in both models.
jill_topics = model.get_author_topics('jill')
jill_topics2 = model2.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
self.assertTrue(np.allclose(jill_topics, jill_topics2))
def test_update(self):
# Check that calling update after the model already has been trained works.
model = self.class_(corpus, author2doc=author2doc, id2word=dictionary, num_topics=2)
jill_topics = model.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
model.update()
jill_topics2 = model.get_author_topics('jill')
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
# Did we learn something?
self.assertFalse(all(np.equal(jill_topics, jill_topics2)))
def test_update_new_data_old_author(self):
# Check that calling update with new documents and/or authors after the model already has
# been trained works.
# Test an author that already existed in the old dataset.
model = self.class_(corpus, author2doc=author2doc, id2word=dictionary, num_topics=2)
jill_topics = model.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
model.update(corpus_new, author2doc_new)
jill_topics2 = model.get_author_topics('jill')
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
# Did we learn more about Jill?
self.assertFalse(all(np.equal(jill_topics, jill_topics2)))
def test_update_new_data_new_author(self):
# Check that calling update with new documents and/or authors after the model already has
# been trained works.
# Test a new author, that didn't exist in the old dataset.
model = self.class_(corpus, author2doc=author2doc, id2word=dictionary, num_topics=2)
model.update(corpus_new, author2doc_new)
# Did we learn something about Sally?
sally_topics = model.get_author_topics('sally')
sally_topics = matutils.sparse2full(sally_topics, model.num_topics)
self.assertTrue(all(sally_topics > 0))
def test_serialized(self):
# Test the model using serialized corpora. Basic tests, plus test of update functionality.
model = self.class_(
self.corpus, author2doc=author2doc, id2word=dictionary, num_topics=2,
serialized=True, serialization_path=datapath('testcorpus_serialization.mm')
)
jill_topics = model.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
self.assertTrue(all(jill_topics > 0))
model.update()
jill_topics2 = model.get_author_topics('jill')
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
# Did we learn more about Jill?
self.assertFalse(all(np.equal(jill_topics, jill_topics2)))
model.update(corpus_new, author2doc_new)
# Did we learn something about Sally?
sally_topics = model.get_author_topics('sally')
sally_topics = matutils.sparse2full(sally_topics, model.num_topics)
self.assertTrue(all(sally_topics > 0))
# Delete the MmCorpus used for serialization inside the author-topic model.
remove(datapath('testcorpus_serialization.mm'))
def test_transform_serialized(self):
# Same as testTransform, using serialized corpora.
passed = False
# sometimes, training gets stuck at a local minimum
# in that case try re-training the model from scratch, hoping for a
# better random initialization
for i in range(25): # restart at most 5 times
# create the transformation model
model = self.class_(
id2word=dictionary, num_topics=2, passes=100, random_state=0,
serialized=True, serialization_path=datapath('testcorpus_serialization.mm')
)
model.update(self.corpus, author2doc)
jill_topics = model.get_author_topics('jill')
# NOTE: this test may easily fail if the author-topic model is altered in any way. The model's
# output is sensitive to a lot of things, like the scheduling of the updates, or like the
# author2id (because the random initialization changes when author2id changes). If it does
# fail, simply be aware of whether we broke something, or if it just naturally changed the
# output of the model slightly.
vec = matutils.sparse2full(jill_topics, 2) # convert to dense vector, for easier equality tests
expected = [0.91, 0.08]
# must contain the same values, up to re-ordering
passed = np.allclose(sorted(vec), sorted(expected), atol=1e-1)
# Delete the MmCorpus used for serialization inside the author-topic model.
remove(datapath('testcorpus_serialization.mm'))
if passed:
break
logging.warning(
"Author-topic model failed to converge on attempt %i (got %s, expected %s)",
i, sorted(vec), sorted(expected)
)
self.assertTrue(passed)
def test_alpha_auto(self):
model1 = self.class_(
corpus, author2doc=author2doc, id2word=dictionary,
alpha='symmetric', passes=10, num_topics=2
)
modelauto = self.class_(
corpus, author2doc=author2doc, id2word=dictionary,
alpha='auto', passes=10, num_topics=2
)
# did we learn something?
self.assertFalse(all(np.equal(model1.alpha, modelauto.alpha)))
def test_alpha(self):
kwargs = dict(
author2doc=author2doc,
id2word=dictionary,
num_topics=2,
alpha=None
)
expected_shape = (2,)
# should not raise anything
self.class_(**kwargs)
kwargs['alpha'] = 'symmetric'
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(all(model.alpha == np.array([0.5, 0.5])))
kwargs['alpha'] = 'asymmetric'
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(np.allclose(model.alpha, [0.630602, 0.369398]))
kwargs['alpha'] = 0.3
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(all(model.alpha == np.array([0.3, 0.3])))
kwargs['alpha'] = 3
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(all(model.alpha == np.array([3, 3])))
kwargs['alpha'] = [0.3, 0.3]
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(all(model.alpha == np.array([0.3, 0.3])))
kwargs['alpha'] = np.array([0.3, 0.3])
model = self.class_(**kwargs)
self.assertEqual(model.alpha.shape, expected_shape)
self.assertTrue(all(model.alpha == np.array([0.3, 0.3])))
# all should raise an exception for being wrong shape
kwargs['alpha'] = [0.3, 0.3, 0.3]
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['alpha'] = [[0.3], [0.3]]
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['alpha'] = [0.3]
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['alpha'] = "gensim is cool"
self.assertRaises(ValueError, self.class_, **kwargs)
def test_eta_auto(self):
model1 = self.class_(
corpus, author2doc=author2doc, id2word=dictionary,
eta='symmetric', passes=10, num_topics=2
)
modelauto = self.class_(
corpus, author2doc=author2doc, id2word=dictionary,
eta='auto', passes=10, num_topics=2
)
# did we learn something?
self.assertFalse(all(np.equal(model1.eta, modelauto.eta)))
def test_eta(self):
kwargs = dict(
author2doc=author2doc,
id2word=dictionary,
num_topics=2,
eta=None
)
num_terms = len(dictionary)
expected_shape = (num_terms,)
# should not raise anything
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([0.5] * num_terms)))
kwargs['eta'] = 'symmetric'
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([0.5] * num_terms)))
kwargs['eta'] = 0.3
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([0.3] * num_terms)))
kwargs['eta'] = 3
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([3] * num_terms)))
kwargs['eta'] = [0.3] * num_terms
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([0.3] * num_terms)))
kwargs['eta'] = np.array([0.3] * num_terms)
model = self.class_(**kwargs)
self.assertEqual(model.eta.shape, expected_shape)
self.assertTrue(all(model.eta == np.array([0.3] * num_terms)))
# should be ok with num_topics x num_terms
testeta = np.array([[0.5] * len(dictionary)] * 2)
kwargs['eta'] = testeta
self.class_(**kwargs)
# all should raise an exception for being wrong shape
kwargs['eta'] = testeta.reshape(tuple(reversed(testeta.shape)))
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['eta'] = [0.3]
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['eta'] = [0.3] * (num_terms + 1)
self.assertRaises(AssertionError, self.class_, **kwargs)
kwargs['eta'] = "gensim is cool"
self.assertRaises(ValueError, self.class_, **kwargs)
kwargs['eta'] = "asymmetric"
self.assertRaises(ValueError, self.class_, **kwargs)
def test_top_topics(self):
top_topics = self.model.top_topics(corpus)
for topic, score in top_topics:
self.assertTrue(isinstance(topic, list))
self.assertTrue(isinstance(score, float))
for v, k in topic:
self.assertTrue(isinstance(k, str))
self.assertTrue(isinstance(v, float))
def test_get_topic_terms(self):
topic_terms = self.model.get_topic_terms(1)
for k, v in topic_terms:
self.assertTrue(isinstance(k, numbers.Integral))
self.assertTrue(isinstance(v, float))
def test_get_author_topics(self):
model = self.class_(
corpus, author2doc=author2doc, id2word=dictionary, num_topics=2,
passes=100, random_state=np.random.seed(0)
)
author_topics = []
for a in model.id2author.values():
author_topics.append(model.get_author_topics(a))
for topic in author_topics:
self.assertTrue(isinstance(topic, list))
for k, v in topic:
self.assertTrue(isinstance(k, int))
self.assertTrue(isinstance(v, float))
def test_term_topics(self):
model = self.class_(
corpus, author2doc=author2doc, id2word=dictionary, num_topics=2,
passes=100, random_state=np.random.seed(0)
)
# check with word_type
result = model.get_term_topics(2)
for topic_no, probability in result:
self.assertTrue(isinstance(topic_no, int))
self.assertTrue(isinstance(probability, float))
# if user has entered word instead, check with word
result = model.get_term_topics(str(model.id2word[2]))
for topic_no, probability in result:
self.assertTrue(isinstance(topic_no, int))
self.assertTrue(isinstance(probability, float))
def test_new_author_topics(self):
model = self.class_(
corpus, author2doc=author2doc, id2word=dictionary, num_topics=2,
passes=100, random_state=np.random.seed(0)
)
author2doc_newauthor = {}
author2doc_newauthor["test"] = [0, 1]
model.update(corpus=corpus[0:2], author2doc=author2doc_newauthor)
# temp save model state vars before get_new_author_topics is called
state_gamma_len = len(model.state.gamma)
author2doc_len = len(model.author2doc)
author2id_len = len(model.author2id)
id2author_len = len(model.id2author)
doc2author_len = len(model.doc2author)
new_author_topics = model.get_new_author_topics(corpus=corpus[0:2])
# sanity check
for k, v in new_author_topics:
self.assertTrue(isinstance(k, int))
self.assertTrue(isinstance(v, float))
# make sure topics are similar enough
similarity = 1 / (1 + jensen_shannon(model["test"], new_author_topics))
self.assertTrue(similarity >= 0.9)
# produce an error to test if rollback occurs
with self.assertRaises(TypeError):
model.get_new_author_topics(corpus=corpus[0])
# assure rollback was successful and the model state is as before
self.assertEqual(state_gamma_len, len(model.state.gamma))
self.assertEqual(author2doc_len, len(model.author2doc))
self.assertEqual(author2id_len, len(model.author2id))
self.assertEqual(id2author_len, len(model.id2author))
self.assertEqual(doc2author_len, len(model.doc2author))
def test_passes(self):
# long message includes the original error message with a custom one
self.longMessage = True
# construct what we expect when passes aren't involved
test_rhots = []
model = self.class_(id2word=dictionary, chunksize=1, num_topics=2)
def final_rhot(model):
return pow(model.offset + (1 * model.num_updates) / model.chunksize, -model.decay)
# generate 5 updates to test rhot on
for _ in range(5):
model.update(corpus, author2doc)
test_rhots.append(final_rhot(model))
for passes in [1, 5, 10, 50, 100]:
model = self.class_(id2word=dictionary, chunksize=1, num_topics=2, passes=passes)
self.assertEqual(final_rhot(model), 1.0)
# make sure the rhot matches the test after each update
for test_rhot in test_rhots:
model.update(corpus, author2doc)
msg = "{}, {}, {}".format(passes, model.num_updates, model.state.numdocs)
self.assertAlmostEqual(final_rhot(model), test_rhot, msg=msg)
self.assertEqual(model.state.numdocs, len(corpus) * len(test_rhots))
self.assertEqual(model.num_updates, len(corpus) * len(test_rhots))
def test_persistence(self):
fname = get_tmpfile('gensim_models_atmodel.tst')
model = self.model
model.save(fname)
model2 = self.class_.load(fname)
self.assertEqual(model.num_topics, model2.num_topics)
self.assertTrue(np.allclose(model.expElogbeta, model2.expElogbeta))
self.assertTrue(np.allclose(model.state.gamma, model2.state.gamma))
def test_persistence_ignore(self):
fname = get_tmpfile('gensim_models_atmodel_testPersistenceIgnore.tst')
model = atmodel.AuthorTopicModel(corpus, author2doc=author2doc, num_topics=2)
model.save(fname, ignore='id2word')
model2 = atmodel.AuthorTopicModel.load(fname)
self.assertTrue(model2.id2word is None)
model.save(fname, ignore=['id2word'])
model2 = atmodel.AuthorTopicModel.load(fname)
self.assertTrue(model2.id2word is None)
def test_persistence_compressed(self):
fname = get_tmpfile('gensim_models_atmodel.tst.gz')
model = self.model
model.save(fname)
model2 = self.class_.load(fname, mmap=None)
self.assertEqual(model.num_topics, model2.num_topics)
self.assertTrue(np.allclose(model.expElogbeta, model2.expElogbeta))
# Compare Jill's topics before and after save/load.
jill_topics = model.get_author_topics('jill')
jill_topics2 = model2.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
self.assertTrue(np.allclose(jill_topics, jill_topics2))
def test_large_mmap(self):
fname = get_tmpfile('gensim_models_atmodel.tst')
model = self.model
# simulate storing large arrays separately
model.save(fname, sep_limit=0)
# test loading the large model arrays with mmap
model2 = self.class_.load(fname, mmap='r')
self.assertEqual(model.num_topics, model2.num_topics)
self.assertTrue(isinstance(model2.expElogbeta, np.memmap))
self.assertTrue(np.allclose(model.expElogbeta, model2.expElogbeta))
# Compare Jill's topics before and after save/load.
jill_topics = model.get_author_topics('jill')
jill_topics2 = model2.get_author_topics('jill')
jill_topics = matutils.sparse2full(jill_topics, model.num_topics)
jill_topics2 = matutils.sparse2full(jill_topics2, model.num_topics)
self.assertTrue(np.allclose(jill_topics, jill_topics2))
def test_large_mmap_compressed(self):
fname = get_tmpfile('gensim_models_atmodel.tst.gz')
model = self.model
# simulate storing large arrays separately
model.save(fname, sep_limit=0)
# test loading the large model arrays with mmap
self.assertRaises(IOError, self.class_.load, fname, mmap='r')
def test_dtype_backward_compatibility(self):
atmodel_3_0_1_fname = datapath('atmodel_3_0_1_model')
expected_topics = [(0, 0.068200842977296727), (1, 0.93179915702270333)]
# save model to use in test
# self.model.save(atmodel_3_0_1_fname)
# load a model saved using a 3.0.1 version of Gensim
model = self.class_.load(atmodel_3_0_1_fname)
# and test it on a predefined document
topics = model['jane']
self.assertTrue(np.allclose(expected_topics, topics))
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.DEBUG)
unittest.main()
| TestAuthorTopicModel |
python | eventlet__eventlet | tests/wsgi_test.py | {
"start": 3506,
"end": 3980
} | class ____:
def __init__(self, send_start_response=False, return_val=()):
self.send_start_response = send_start_response
self.return_val = return_val
self.env = {}
def __call__(self, env, start_response):
self.env = env
if self.send_start_response:
start_response('200 OK', [('Content-type', 'text/plain')])
else:
wsgi.WSGI_LOCAL.already_handled = True
return self.return_val
| IterableApp |
python | pandas-dev__pandas | pandas/tests/series/methods/test_tz_localize.py | {
"start": 214,
"end": 4266
} | class ____:
def test_series_tz_localize_ambiguous_bool(self):
# make sure that we are correctly accepting bool values as ambiguous
# GH#14402
ts = Timestamp("2015-11-01 01:00:03")
expected0 = Timestamp("2015-11-01 01:00:03-0500", tz="US/Central")
expected1 = Timestamp("2015-11-01 01:00:03-0600", tz="US/Central")
ser = Series([ts])
expected0 = Series([expected0])
expected1 = Series([expected1])
with tm.external_error_raised(ValueError):
ser.dt.tz_localize("US/Central")
result = ser.dt.tz_localize("US/Central", ambiguous=True)
tm.assert_series_equal(result, expected0)
result = ser.dt.tz_localize("US/Central", ambiguous=[True])
tm.assert_series_equal(result, expected0)
result = ser.dt.tz_localize("US/Central", ambiguous=False)
tm.assert_series_equal(result, expected1)
result = ser.dt.tz_localize("US/Central", ambiguous=[False])
tm.assert_series_equal(result, expected1)
def test_series_tz_localize_matching_index(self):
# Matching the index of the result with that of the original series
# GH 43080
dt_series = Series(
date_range(start="2021-01-01T02:00:00", periods=5, freq="1D"),
index=[2, 6, 7, 8, 11],
dtype="category",
)
result = dt_series.dt.tz_localize("Europe/Berlin")
expected = Series(
date_range(
start="2021-01-01T02:00:00", periods=5, freq="1D", tz="Europe/Berlin"
),
index=[2, 6, 7, 8, 11],
)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
"method, exp",
[
["shift_forward", "2015-03-29 03:00:00"],
["shift_backward", "2015-03-29 01:59:59.999999999"],
["NaT", NaT],
["raise", None],
["foo", "invalid"],
],
)
def test_tz_localize_nonexistent(self, warsaw, method, exp, unit):
# GH 8917
tz = warsaw
n = 60
dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min", unit=unit)
ser = Series(1, index=dti)
df = ser.to_frame()
if method == "raise":
with tm.external_error_raised(ValueError):
dti.tz_localize(tz, nonexistent=method)
with tm.external_error_raised(ValueError):
ser.tz_localize(tz, nonexistent=method)
with tm.external_error_raised(ValueError):
df.tz_localize(tz, nonexistent=method)
elif exp == "invalid":
msg = (
"The nonexistent argument must be one of "
"'raise', 'NaT', 'shift_forward', 'shift_backward' "
"or a timedelta object"
)
with pytest.raises(ValueError, match=msg):
dti.tz_localize(tz, nonexistent=method)
with pytest.raises(ValueError, match=msg):
ser.tz_localize(tz, nonexistent=method)
with pytest.raises(ValueError, match=msg):
df.tz_localize(tz, nonexistent=method)
else:
result = ser.tz_localize(tz, nonexistent=method)
expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz).as_unit(unit))
tm.assert_series_equal(result, expected)
result = df.tz_localize(tz, nonexistent=method)
expected = expected.to_frame()
tm.assert_frame_equal(result, expected)
res_index = dti.tz_localize(tz, nonexistent=method)
tm.assert_index_equal(res_index, expected.index)
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
def test_series_tz_localize_empty(self, tzstr):
# GH#2248
ser = Series(dtype=object)
ser2 = ser.tz_localize("utc")
assert ser2.index.tz == timezone.utc
ser2 = ser.tz_localize(tzstr)
timezones.tz_compare(ser2.index.tz, timezones.maybe_get_tz(tzstr))
| TestTZLocalize |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.